#!/usr/bin/perl -w

$CONFIG="/home/pabs/.tetrinet";
$CONNECTED="/home/pabs/.tetrinet_connected";
$URLS="/home/pabs/.tetrinet_urls";
$list = "";;

$th="<TABLE BORDER=\"0\" WIDTH=\"100\%\">\n<TR><TD><FONT FACE=\"sans-serif\" SIZE=\"-1\"><B>Name</B></FONT></TD><TD><FONT FACE=\"sans-serif\" SIZE=\"-1\"><B>Rating</B></FONT></TD><TD><FONT FACE=\"sans-serif\" SIZE=\"-1\"><B>Points</B></FONT></TD></TD><TD><FONT FACE=\"sans-serif\" SIZE=\"-1\"><B>Games</B></FONT></TD></TR>\n";
$eh="<TR><TD>";
$delim="</TD><TD>";
$ef="</TD></TR>";
$tf="</TR></TABLE>";

print "Content-type: text/html\n\n";

&print_error_and_exit unless (open IN, "$CONFIG");

while (<IN>) {
	$list = $_ if (/^winlist/);
}
close IN;

@connected="";
if (open IN, "$CONNECTED") {
	push @connected, $_  while (<IN>);
	close IN;
}

$urls=();
if (open IN, "$URLS") {
	while(<IN>) {
		/(.*?),(.*)$/;
		$urls{$1}=$2;
	}
	close IN;
}

$list =~ s/winlist //;
$true_name="";
if ($list) {
	print "$th\n";
	do {
		$name = ""; $team="0"; $points="0"; $games="0";
		$list =~ s/(.*?);(.*?);(.*?);(.*?)( |$)//;
		$name = $1; $team=$2; $points=$3; $games=$4;

		if ($name&&!$team) {
			$true_name=$name;
			if ($urls{$true_name}) {
				$name = "<a href=\"$urls{$true_name}\">".$name."</a>";
			}
			foreach(@connected) {
				$name .= " (connected)"
					if (/$true_name/);
			}

			$team="" if $team eq "0";
			$rating = int(3333.333*($points)/$games * (1+$games/100))/100;
			#$rating =~ s/\.([0-9]{2,2}).*$//;
			$scores{$name} = $rating;
			$strings{$name} = "$name $delim " . ($rating+1) . " $delim $points $delim $games\n";
		}
	} while ($name);

	$rank = 1;
	foreach (sort {$scores{$b} <=> $scores{$a}} keys %scores) {
		print"$eh <B>$rank.</B>  $strings{$_} $ef\n";
		$rank++;
	}
	print "$tf\n";
}


sub print_error_and_quit() {
	print "Error opening configuration file.\n";
	exit 0;
}

