#!/Perl/bin/perl

use strict;
use constant USAGE => "usage\n $0 DATAFILE OUTPUTFILE\n";
use Data::Dumper;

($#ARGV == 1)
  or die USAGE;

my $ifname = shift;
my $ofname = shift;
$| = 1;
defined (my $all_data = do $ifname)
  or die ($@ ? "Error parsing data from $ifname: $@\n"
	  : "Can't read data from $ifname: $!\n");

(my ($accuracy, $kappa, $guess_tags, $correct_tags, $pair_counts))
  = @{$all_data}{qw|accuracy kappa guess_tags correct_tags pair_counts|};


open (FH, ">", $ofname)
  or die "Can't write to $ofname: $!";

print FH "accuracy,$accuracy\n";
print FH "cohen's kappa,$kappa\n";
print FH "\n";

print FH "0,";
foreach my $guess_tag (sort keys %{$guess_tags}) {
  next unless (length ($guess_tag) > 0);
  $guess_tag =~ s{"}{""};
  print FH '"' . $guess_tag . '",';
}
print FH "total\n";
foreach my $correct_tag (sort keys %{$correct_tags}) {
  next unless (length ($correct_tag) > 0);
  print FH '"' . $correct_tag . '",';
  foreach my $guess_tag (sort keys %{$guess_tags}) {
    next unless (length ($guess_tag) > 0);
    my $pair_count = (grep { (($_->[0] eq $guess_tag)
			      and
			      ($_->[1] eq $correct_tag)) } (@{$pair_counts}))[0];
    print FH "" . ($pair_count->[2] / $correct_tags->{$correct_tag}) . ",";
  }
  print FH "" . $correct_tags->{$correct_tag} . "\n";
}

print FH "0,";
foreach my $guess_tag (sort keys (%{$guess_tags})) {
  next unless (length ($guess_tag) > 0);
  print FH $guess_tags->{$guess_tag} . ",";
}
print FH "0\n";

my $error_pairs = [ (reverse (sort { $a->[2] <=> $b->[2] }
			      (grep { $_->[0] ne $_->[1] } (@{$pair_counts})))) ];
print FH "\n";
print FH "error pairs\n";
foreach (@{$error_pairs}) {
  next if ($_->[2] == 0);
  print FH '"' . $_->[0] . '","' . $_->[1] . '",' . $_->[2] . "\n";
}

close (FH);
