#!/usr/local/bin/perl -w

# compare-ratings-calculations - compare NSA and ratings2.pl Elo ratings

# Copyright (C) 2002 by John J. Chew, III <jjchew@math.utoronto.ca>

use strict;

sub Main ();
sub Process ($);

Main;

sub Main () {
  our @ARGV;
  if (@ARGV) {
    for my $ARGV (@ARGV) {
      Process $ARGV;
      }
    }
  else { Process ''; }
  }

sub Process ($) {
  my $ARGV = shift;
  my @lines = `bin/xt-to-t.pl $ARGV`;
# print @lines;
  my $tmpfile = '/tmp/' . $::ENV{'USER'} . '.' . $$ . rand;
  my @tlines = grep(!/^#/, @lines);
  # save NSA calculations
  my %initr;
  my %nsar;
  for my $line (grep(/^# player:/, @lines)) {
    $line =~ s/.*://;
    chomp $line;
    my ($name, $initr, $finalr) = split(/;/, $line);
    $initr{$name} = $initr;
    $nsar{$name} = $finalr;
    }
  # feed results to tourney.pl assuming everyone has their fifty games
  open(TMP, ">$tmpfile") or die;
  print TMP @tlines;
  close(TMP);
  my @lines2 = `tourney.pl -S $tmpfile`;
  # feed results to tourney.pl assuming no one has their fifty games
  map { s/(\d+)/$1*1/ } @tlines;
  open(TMP, ">$tmpfile") or die;
  print TMP @tlines;
  close(TMP);
  my @lines3 = `tourney.pl -S $tmpfile`;
  unlink $tmpfile;
  # parse and compare
  my %jjc50;
  for my $line (@lines2) {
    next unless $line =~ /\./;
    $line =~ s/n\.r\./   0/;
    $line =~ s/^[ \d]+([^\d]+[A-Z])\s+\d+\.[05]\s+\d+\s+(\d+)// || die;
    $jjc50{$1} = $2;
    }
  my %jjc1;
  for my $line (@lines3) {
    next unless $line =~ /\./;
    $line =~ s/n\.r\./   0/;
    $line =~ s/^[ \d]+([^\d]+[A-Z])\s+\d+\.[05]\s+\d+\s+(\d+)// || die;
    $jjc1{$1} = $2;
    }
  for my $key (sort keys %nsar) {
    if ($nsar{$key} != $jjc1{$key} && $nsar{$key} != $jjc50{$key}) {
      my $e1 = abs($nsar{$key} - $jjc1{$key});
      my $e50 = abs($nsar{$key} - $jjc50{$key});
      my $e = $e1 < $e50 ? $e1 : $e50;
      print "E=$e $key I=$initr{$key} N=$nsar{$key} J0=$jjc1{$key} J50=$jjc50{$key}\n";
      }
    delete $jjc1{$key};
    delete $jjc50{$key};
    }
  while (my ($key, $val) = each %jjc1) {
    print "$key is in jjc1 but not nsa.\n";
    }
  while (my ($key, $val) = each %jjc50) {
    print "$key is in jjc50 but not nsa.\n";
    }
  }
