#!/usr/common/usg/languages/perl/5.16.0/bin/perl -w

$n_args = @ARGV;
if ($n_args != 4) {
    die "usage: unique.pl <input file> <column> <value column> <operation - 0 = sum, 1 = mean, 2 = median>\n";
}

open(F,$ARGV[0]) || die "Couldn't open file $ARGV[0]\n";

my $use_col = $ARGV[1] - 1;
if ($use_col < 0) {
    die "error: column specification must be >= 1\n";
}

my %values = ();
my $val_col = $ARGV[2] - 1;
my $operation = $ARGV[3];

if (($operation != 0) && ($operation != 1) && ($operation != 2)) {
    die "Invalid operation $operation\n";
}

my %attempts = ();

while (my $i = <F>) {
    chomp $i;

    my $val = 0;
    my @cols = split(/\s+/,$i);
#	my @cols = split(/\t/,$i);
    my $n_cols = @cols;
    if ($use_col+1 > $n_cols) {
	warn "Warning: column specification exceeds number of columns in line: $i\n";
	next;
    }
    $i = $cols[$use_col];
    $val = $cols[$val_col];

    if (exists($attempts{$i})) {
	$attempts{$i} += 1;
	push (@{$values{$i}},$val);
    } else {
	$attempts{$i} = 1;
	$values{$i} = [$val];
    }
}
close F;

while (my ($id, $count) = each(%attempts)) {
    my @vals = @{$values{$id}};

    my $result = "NA";
    if ($operation == 0) {
	#sum
	my $sum = 0;
	foreach(@vals) {
	    $sum+=$_;
	}
	$result = $sum;
    } elsif ($operation == 1) {
	#mean
	my $mean = 0;
	my $stdev = 0;
	foreach(@vals) {
	    $mean+=$_;
	    $stdev+=($_)*($_);
	}
	$mean /= $count;
	$stdev /= $count;
	$stdev = sqrt($stdev - $mean*$mean);
	$result = "$mean +- $stdev";
    } elsif ($operation == 2) {
	#median
	my @sorted_vals = sort { $a <=> $b } @vals;
	my $median_index = sprintf("%d",($count-1)/2);
	$result = $sorted_vals[$median_index];
    }
	
    print "$id\t$count\t$result\n";
}


