#!/usr/local/bin/perl

if ($#ARGV != 1) {
  print "Usage: nn.pl train test\n";
  exit 1;
}

open(TRAIN, "$ARGV[0]") or die "Unable to open train:$ARGV[0]";
open(TEST, "$ARGV[1]") or die "Unable to open test:$ARGV[1]";

# extract fake & real feature vectors;
my @real, @fake;
while(<TRAIN>) {
  my @vector = split /\s+/, $_;
  my $result = pop @vector;
  if ($result == 1) {
    push @real, \@vector;
  } else {
    push @fake, \@vector;
  }
}

# compute results
my @results;
$results[0] = 0; $results[1] = 0; $results[2] = 0; $results[3] = 0;
TEST: while (<TEST>) {
  # get test feature vector
  my @test = split /\s+/, $_;
  my $actual = pop @test;

  # compare to trained reals
  my $md = ~0;
  foreach $vector (@real) {
    my @features = @{$vector};
    my $d = 0;
    for ($i = 0; $i <= $#features; $i++) {
      $d += ($features[$i] - $test[$i])**2;
    }
    $d **= .5;
    if ($d < $md) {
      $md = $d;
    }
  }

  #compare to trained fakes
  foreach $vector (@fake) {
    my @features = @{$vector};
    my $d = 0;
    for ($i = 0; $i <= $#features; $i++) {
      $d += ($features[$i] - $test[$i])**2;
    }
    $d **= .5;
    if ($d < $md) {
      #closest to fake
      if ($actual == 0) {
        $results[3]++;
      } else {
        $results[1]++;
      }
      next TEST;
      exit;
    }
  }

  # closest to real
  if ($actual == 1) {
    $results[0]++;
  } else {
    $results[2]++;
  }
}

foreach $tmp (@results) {
  print $tmp." ";
}
print "\n";

close(TEST);
close(TRAIN);
