#!/usr/bin/perl

use strict;
use warnings;

sub Main ();
sub Munge ();

Main;

sub sort_low_loss { $a->[1] <=> $b->[1] };
sub sort_high_loss { $b->[1] <=> $a->[1] };
sub sort_low_win { $a->[0] <=> $b->[0] };
sub sort_high_win { $b->[0] <=> $a->[0] };

sub Munge () {
  my @data;
  my $id = 0;
  my (@names, @scores, @pairings);
  while (<>) {
    s/#.*//;
    next unless /\S/;
    $id++;
    my ($name, $rating, $o, $s) 
      = /^([^;]+[^;\s\d])\s+(\d+)\s+([\d\s]*);\s*([-\d\s]*)(?:;[^;]+)*$/;
    die "Can't parse: $_\n" unless defined $s;
    $pairings[$id] = [split(/\s+/, $o)];
    $scores[$id] = [split(/\s+/, $s)];
    $names[$id] = $name;
    }

  for my $id (1..$#scores) {
    my $op = $pairings[$id];
    my $sp = $scores[$id];
    next if $op == 0;
    for my $round (0..$#$sp) {
      my $opp = $op->[$round];
      next unless $opp; # skip byes
      my $ms = $sp->[$round];
      my $os = $scores[$opp][$round];
      if (!defined $os) { warn "No score for #$id in round $round+1.\n"; }
      next if $ms <= $os; # skip losers
      push(@data, [
	$ms,
	$os,
	$names[$id],
	$names[$opp],
	$round+1,
	]);
      }
    }
  return @data;
  }

sub Main () {
  die "This command is obsolete.  Please use highroundwins instead.\n";
  @::ARGV = ('a.t') unless @::ARGV;
  my $div = uc $::ARGV[0]; $div =~ s/\.T$//;
  my (@data) = Munge;
  my $sortsub = $0 =~ /high/i 
    ? $0 =~ /win/i ? \&sort_high_win : \&sort_high_loss
    : $0 =~ /win/i ? \&sort_low_win : \&sort_low_loss;
  my $count = 0;
  my $type = $0; $type =~ s/.*\///;
  my $notee;
  open (TEE, ">$div-$type.txt") || $notee++;
  my $s = "Rd Result\n";
  print $s; print TEE $s unless $notee;
  my @highs;
  my $score_of_interest = $0 =~ /win/ ? 0 : 1;
  for my $gamep (sort $sortsub @data) {
    my $round = $gamep->[4];
    if ($highs[$round]) {
      next if $highs[$round][$score_of_interest] > $gamep->[$score_of_interest];
      push(@{$highs[$round]}, $gamep);
      }
    else {
      $highs[$round] = [$gamep];
      }
    }
  for my $round0 (1..$#highs) {
    for my $gamep (@{$highs[$round0]}) {
      $s = sprintf("%2d %3d %s\n       %3d %s\n", @{$gamep}[4,0,2,1,3]);
      print $s; print TEE $s unless $notee;
      }
    }
  close TEE;
  }

