#!/usr/local/bin/perl

print <<EOF
Content-type: text/html

<html>
<head>
<title>AI Olympics 2003 Scoring
</title>
<link href=../style.css rel=stylesheet type=text/css>
</head>
<body>

<center><img src="../crests/hogwarts.gif"> <br>
<h2>2003 AI Olympics Current Standings</h2>

<pre>
</pre>

EOF
    ;

@events= <../events/*>;

%scores = ("gryffindor", 0, "slytherin", 0, "hufflepuff", 0, "ravenclaw", 0);
$totalscore = 0;

foreach $event (@events) {
    ($dir= $event)=~ s!^.*/([^/]*)!$1!;
    if (open(IN, "$event/info")) {
	while(<IN>) {
	    if (/^([^:]*):(.*)/) {
		($type, $value) = ($1, $2);
		if ($type eq "SCORE") {
		    $value=~ s/^\s+//;  # strip the whitespace from the beginning
		    $value=~ s/\s+$//;  # and the end of the string
		    @places= split(/\s*\/\s*/, $value);
		    @points = (5, 3, 2, 1);
		    $i = 0;
                    $teamexisted = 0;
		    foreach $team (@places) {
                        $teamexisted = 1; 
			if ($team=~ /\s+/) {
			    @tied= split(/\s+/, $team);
			    if ( $#tied == 1 ) { #if 2 teams tied
				$tiedpoints = ($points[$i] + $points[$i + 1]) / 2;
				$i = $i + 2;
			    }
			    elsif($#tied == 2) { #if 3 teams tied
				$tiedpoints = ($points[$i] + $points[$i + 1] + $points[$i + 2]) /3;
				$i = $i + 3;
			    } else {
                              $tiedpoints = 11 / 4;                              $i = $i + 4;   
                            }
			    foreach $tiedteam (@tied) {
				$scores{$tiedteam} = $scores{$tiedteam} + $tiedpoints;
			    }
			}
			else {
			    $scores{$team} = $scores{$team} + $points[$i];
			    $i = $i + 1;
			}
		    }
                    if ($teamexisted == 1)
                    {
                      $totalscore = $totalscore + 11;
		    }

		}
	    }
	}
    }
}

if ($totalscore != 0) {
    foreach $team (keys %scores) {
	$scores{$team} = $scores{$team};
#	$scores{$team} = ($scores{$team} * 100) / $totalscore;
	$scores{$team}=~ s/^([^\.]*)\..*/$1/;
    }
}

$totalbattles = $totalscore / 11;

print <<EOF

<table width=600 border>
<tr> 
  <td>Total Battles </td>
  <td colspan=4>Points Won</td>
</tr>
<tr>
EOF
    ;
print( "<td> $totalbattles</td>");
print("<td> <img src=\"../crests/gryffindor.gif\" width=50> 
$scores{gryffindor}</td>");
print( "<td> <img src=\"../crests/slytherin.gif\" width=50> $scores{slytherin}</td>");
print( "<td><img src=\"../crests/hufflepuff.gif\" width=50> $scores{hufflepuff}</td>");
print( "<td><img src=\"../crests/ravenclaw.gif\" width=50> $scores{ravenclaw}</td>");

print <<EOF
</tr>

</table>

<br>
<hr>
<br>
<h3>
A note on scoring
</h3>
Each event is worth a total of 11 points.
<br>
<bR>
First Place: 5 points
<br>
Second Place: 3 points
<br>
Third Place: 2 points
<br>
Fourth Place: 1 point
<br>
<br>
If there is a tie, the total number of possible points are divided between the 
tied teams. 
<br>
Note that fractions in the total number of points are not displayed, but they
are accumulated. 

</center>

</body>
</html>
EOF
;
