#!/usr/bin/perl -w

use lib "../stat";
use Vector;

my $usage = "renameColumns.pl [field=NewName ... ] [-keep] filename > output\n"
    . "  Special values for NewName: \$LINENO (line number)\n";

my %rename;
my $keep = 0;
my @fields = ();

die $usage if scalar @ARGV == 0;

while (scalar @ARGV > 1) {
    my $arg = shift @ARGV;
    if ($arg eq "-keep") {
	$keep = 1;
    } elsif ($arg =~ m/^([^=]+)=(.*)$/) {
	die "Renaming $1 twice" if exists $rename{$1};
	$rename{$1} = $2;
	push @fields, $1;
    } else {
	die "Cannot interpret argument $arg:\n$usage";
    }
}

my ($list, $attrs) = Vector::readXLSList(shift @ARGV);

die "Empty input" if scalar @$list == 0;

foreach my $field (keys %rename) {
    die "Cannot rename missing field $field" if !exists $list->[0]{$field}
        && $field ne "\$LINENO";
}

if ($keep) {
    foreach my $field (keys %{ $list->[0] }) {
	if (!exists $rename{$field}) {
	    push @fields, $field;
	    $rename{$field} = $field;
	}
    }
}

while (my ($name,$value) = each %$attrs) {
    print "!$name=$value\n";
}

print join("\t",map {$rename{$_}} @fields),"\n";

my $nrow = 1;
foreach my $row (@$list) {
    $row->{"\$LINENO"} = $nrow;
    $nrow++;
    print join("\t", map {$row->{$_}} @fields), "\n";
}

