#!/usr/bin/perl -W

#use strict;

my %teams;
my %homegames;
my %awaygames;
my %prev;
my %wins;
my %loses;
my %stdev;
my %pntsfor;
my %pntsagainst;

while (<>)
{
    my ($id, $team1, $score1, $team2, $score2) = /^([^ ]*) (.*): (.*) -- (.*): (.*)/;

    next if (!defined $team1);
#    print("$team1: $score1, $team2: $score2\n");

    $teams{$team1} .= ":$team2,$score1,$score2";
    $awaygames{$team1} .= ":$team2,$score1,$score2";

    $teams{$team2} .= ":$team1,$score2,$score1";
    $homegames{$team2} .= ":$team1,$score2,$score1";

    $pntsfor{$team1} += $score1;
    $pntsagainst{$team1} += $score2;
    $pntsfor{$team2} += $score2;
    $pntsagainst{$team2} += $score1;

    if ($score1 > $score2)
    {
        $wins{$team1}++;
        $loses{$team2}++;
        $wins{$team2} += 0;
        $loses{$team1} += 0;
    }
    elsif ($score1 < $score2)
    {
        $wins{$team2}++;
        $loses{$team1}++;
        $wins{$team1} += 0;
        $loses{$team2} += 0;
    }
}

my %home;
my %away;

for my $team (sort keys %teams)
{
    $prev{$team} = 50;
    $home{$team} = 50;
    $away{$team} = 50;
}

my %next;
my %nexthome;
my %nextaway;

for my $i (1..100)
{
    for my $team (keys %teams)
    {
        $next{$team} = computeWeight($teams{$team});
    }

    %prev = %next;
}

printResults();

sub computeWeight
{
    my $sum = 0;
    my @results = split(/:/, $_[0]);
    shift(@results);

    for my $result (@results)
    {
        my ($opp, $score1, $score2) = split(/,/, $result);
        $sum += $score1 - $score2 + $prev{$opp};
    }
    
    return $sum / @results;
}

sub printResults
{
    for my $team (sort keys %teams)
    {
        if ($wins{$team} + $loses{$team} > 5)
        {
            my $std = 0;
            my $sos = 0;
            my $oppCount = 0;
            my @results = split(/:/, $teams{$team});
            shift(@results);
    
            for my $result (@results)
            {
                my ($opp, $score1, $score2) = split(/,/, $result);
                $std += ($next{$team} - ($score1 - $score2 + $prev{$opp})) ** 2;
                $sos += $prev{$opp};
                $oppCount++;
            }
            $std = sqrt($std / @results);
    
            printf("%8.5f: (+/- %8.5f) %8.5f (%2d-%2d) (%5d-%5d) %s\n", $next{$team}, $std,
                $sos / $oppCount, $wins{$team}, $loses{$team}, $pntsfor{$team}, $pntsagainst{$team}, $team);
        }
    }
}
