#!/usr/bin/perl

use strict;
use warnings;

binmode STDIN, ":utf8";
binmode STDOUT, ":utf8";


my @gold;
my @predicted;

open (GOLD, "<:utf8", $ARGV[0]) or die;
while (<GOLD>) {
    chomp;
    my ($l1, $l2, $ali) = split /\t/;
    my @alignment = split /\s/, $ali;
    push @gold, \@alignment;
}
close GOLD;

open (PREDICTED, "<:utf8", $ARGV[1]) or die;
while (<PREDICTED>) {
    chomp;
    my ($l1, $l2, $ali) = split /\t/;
    my @alignment = split /\s/, $ali;
    push @predicted, \@alignment;
}
close PREDICTED;

die "Different number of lines" if scalar @gold != scalar @predicted;

my $agree = 0;
my $total_gold = 0;
my $total_predicted = 0;

foreach my $i (0 .. $#gold) {
    my %is_in_gold;
    map {$is_in_gold{$_} = 1} @{$gold[$i]};
    foreach my $j (0 .. $#{$predicted[$i]}) {
        $agree++ if $is_in_gold{$predicted[$i][$j]};
    }
    $total_gold += $#{$gold[$i]} + 1;
    $total_predicted += $#{$predicted[$i]} + 1;
}

my $precision = $agree/$total_predicted;
my $recall = $agree/$total_gold;
my $f_measure = 2 * $precision * $recall / ($precision + $recall);
print "Precision: $precision\nRecall: $recall\nF-measure: $f_measure\n";
