#!/usr/bin/perl
# The Missing Textutils, Ondrej Bojar, obo@cuni.cz
# http://www.cuni.cz/~obo/textutils
#
# 'coleval' evals contents of the specified columns using Perl eval.
# Useful for numbers like 2/3.
#
# $Id: coleval,v 1.1 2012-05-22 17:42:32 bojar Exp $
#

use strict;
use warnings;
use Getopt::Long;

my $cols=shift;

die "usage: coleval 3-5,1,2,-4
Evaluates the given columns.
" if !$cols;

my @use;
my $all_beyond = undef;
foreach my $item (split /,/,$cols) {
  if ($item =~ /^([0-9]+)$/) {
    # an item in the form of "3", i.e. an exact column
    push @use, $1-1;
    next;
  }
  if ($item =~ /^([0-9]+)-$/) {
    # an item in the form of "3-", i.e. tail
    $all_beyond = $1;
    next;
  }
  if ($item =~ /^(-[0-9]+)$/) {
    # an item in the form of "-3", i.e. an item from the end
    push @use, (0..$1);
    next;
  }
  if ($item =~ /^([0-9]+)-([0-9]+)$/) {
    my $b = ($1<=$2 ? $2 : $1);
    for(my $i=$1; $i<=$b; $i++) {
      push @use, $i-1;
    }
    next;
  }
  if ($item =~ /^([0-9]+)-(-[0-9]+)$/) {
    # an item in the form of "3--2", i.e. tail up to 2col from the right
    push @use, ("tailfrom".($1-1)."upto$2");
    next;
  }
  die "Bad item $item";
}
# print STDERR join(", ", @use)."\n";

my %use = map { ($_, 1) } @use;

my $nr=0;
while (<>) {
  $nr++;
  chomp;
  my @line = split /\t/;
  my @outline = ();
  for (my $i=0; $i<=$#line; $i++) {
    if ($use{$i} || (defined $all_beyond && $all_beyond <= $i)) {
      my $val = eval "$line[$i]";
      $val = "$line[$i]" if !defined $val;
      $line[$i] = $val;
    }
  }
  print join("\t", @line)."\n";
}

