#!/usr/bin/perl -w

use strict;

unshift(@::ARGV, 'registration.html') if $#::ARGV == -1;
if (-t STDOUT) {
  open(OUT, '>ranked.html') || die;
  select(OUT);
  }

my @gP;

# read and parse input file
while (<>) {
  if (/^<pre>$/../^<\/pre>$/) {
    next unless /^[A-Z]/ && !/^Name/;
    my ($name, $club, $p1996, $qual, $regd, $mem, $ratings)
      = unpack('A21 A13 A5 A5 A4 A4 A*', $_);
    $ratings =~ s/[- ]+$//;
#CHI    my (@ratings, $chicago);
#CHI    (@ratings[0..2], $chicago) = split(/\s+/, $ratings);
#CHI    my $isEst = 0;
#CHI    if (defined $chicago) { # player shows Chicago NSC estimate
#CHI      @ratings = sort {$b<=>$a} @ratings;
#CHI      if ($chicago > $ratings[0]) { 
#CHI        unshift(@ratings, $chicago);
#CHI        $isEst = 1;
#CHI        }
#CHI      }
#CHI    else { # no Chicago estimate
#CHI      @ratings = sort {$b<=>$a} (@ratings);
#CHI      }
    my @ratings = sort {$b<=>$a} split(/\s+/, $ratings);
    push(@gP, 
#CHI     [$name, $club, $p1996, $qual, $regd, $mem, $ratings, $ratings[0], $isEst]);
      [$name, $club, $p1996, $qual, $regd, $mem, $ratings, $ratings[0]]);
    }
  }

my ($i, $p);
my %gkSortValue = ('yes', 4, 'gm?', 2, 'ip', 3, 'no', 1, 'n/a', 0, 'NO', 0);
$i = 1;
print "<html>\n";
print "<head>\n";
print "<title>1998 CNSC Qualification Standings</title>\n";
print "<link rev=made href=\"http://www.math.utoronto.ca/jjchew\">\n";
print "</head>\n";
print "<body>\n";
print "<h2>1998 CNSC Qualification Standings</h2>\n";
print "\n";
print "This automatically generated list shows who has qualified and\n";
print "who has registered to play in the 1998 CNSC.\n";
print "<a href=\"mailto:jjchew\@math.utoronto.ca\">E-mail</a>ed";
print " corrections welcome.\n";
print "<p>\n";
print "<h3>Legend</h3>\n";
print "<ul>\n";
print "<li>Qual: yes, no, gm? (# of games played uncertain), n/a\n";
print "(not planning on playing)\n";
print "<li>Regd: yes, ip (registration in progress), no, NO (definitely won't play)\n";
print "<li>Rtng: Peak qualifying rating (June-September)\n";
#CHI print "or estimated post-Chicago rating marked with ? if higher.\n";
print "</ul>\n";
print "<pre>\n";
print "\n";

printf "%-3s %-21s %-13s %-4s %-4s %-4s\n", 
  'Rnk', 'Name', 'Club', 'Qual', 'Regd', 'Rtng';
print "\n";
for $p (sort { 
  $gkSortValue{$b->[4]} <=> $gkSortValue{$a->[4]} ||
  $gkSortValue{$b->[3]} <=> $gkSortValue{$a->[3]} ||
  $b->[7] <=> $a->[7] ||
  $b->[1] cmp $a->[1] ||
  $b->[0] cmp $a->[0]
  } @gP) {
  print "\n" if $i == 51;
  printf "%02d. %-21s %-13s %4s %4s %4d%s\n", $i++, @{$p}[0,1,3,4,7],
#CHI   $p->[8] ? '?' : 
    '';
  }
print "</pre>\n";
print "</body>\n";
print "</html>\n";
0;
