#!/usr/local/bin/perl

use strict;

my $SUCCESS = 0;
my $FAILURE = 1;
my $TOLERANCE = 0.001;

my $return_value = $SUCCESS;

if ($#ARGV != 1) {
  die "Usage: $0 <reference dist file> <test dist file>\n";
}

my $reffile = $ARGV[0];
my $testfile = $ARGV[1];

open (REF, "<$reffile") or die "Could not open $reffile\n";
open (TEST, "<$testfile") or (close(REF) and die "Could not open $testfile\n");

my $refline;
my $testline;

my $count = 0;
my $discrepancy = 0;

while (($refline = <REF>) and ($testline = <TEST>)) {
  my @refvals = ($refline =~ m/(\S+)/g);
  $count += $#refvals + 1;
  my @testvals = ($testline =~ m/(\S+)/g);
  if ($#refvals != $#testvals) {
    $return_value = $FAILURE;
    last;
  }
  for (my $i = 0; $i <= $#refvals; $i++) {
    my $diff = $refvals[$i] - $testvals[$i];
    my $sum = $refvals[$i] + $testvals[$i];
    if ($sum != 0) {
      $discrepancy += abs($diff / $sum);
    }
  }
}

if (!((eof REF) and (eof TEST))) {
  $return_value = $FAILURE;
}

close(REF);
close(TEST);

if ($discrepancy / $count > $TOLERANCE) {
  $return_value = $FAILURE;
}

exit $return_value;
