#!/usr/local/bin/perl
##########################################################################################
use strict;

die "Content-type: text/plain\n\nCan't find input file \"count.dat\"" unless -f "count.dat";

##########################################################################################
my %stats;
my $count;
my $file;
my $hitcount;

open(STATS, "<count.dat");
# lock file

# read current value
while(<STATS>)
{
	chop;
	($file,$count) = split(/=/,$_);
	$stats{$file} = $count;
}
close(STATS);
# unlock file

	print "Content-type: text/html\n\n";

	print "<html><head><title>Tom Paton's Homepage - Statistics</title>";

	open(BOILERPLATE,"<../child_pre.html");
	while(<BOILERPLATE>)
	{
		print $_;
	}
	close(BOILERPLATE);
	print "\n<!-- BEGIN CONTENT	-->\n";
	print "<h1><a name=\"TOP\">Statistics</a></h1>\n";
	print '
<div class="menu">
	<span class="menuitem"><a href="#CLIENT">CLIENT</a></span>
	<span class="menuitem"><a href="#DATE">DATE</a></span>
	<span class="menuitem"><a href="#FILE">FILE</a></span>
	<span class="menuitem"><a href="#HOST">HOST</a></span>
	<span class="menuitem"><a href="#HTTP">HTTP</a></span>
	<span class="menuitem"><a href="#KEYWRD">KEYWRD</a></span>
	<span class="menuitem"><a href="#QUERY">QUERY</a></span>
	<span class="menuitem"><a href="#REFER">REFER</a></span>
	<span class="menuitem"><a href="#REFER">REFERS</a></span>
	<span class="menuitem"><a href="#SEARCH">SEARCH</a></span>
	<span class="menuitem"><a href="#TOTAL">TOTAL</a></span>
</div>
';

print	"<p class=\"desc\">This page is generated from a simple <a href=\"http://www.cs.monash.edu.au/~tomp/cgi-bin/echo.pl?statistics.pl\">perl script</a> that reads my <a href=\"http://www.cs.monash.edu.au/~tomp/cgi-bin/echo.pl?count.dat\">counter file</a>, written to by the master perl <a href=\"http://www.cs.monash.edu.au/~tomp/cgi-bin/echo.pl?CGI.pl\">CGI</a> script...</p>\n";

print	"<table>";

my $total = $stats{"TOTAL : "};
my $lastcat = "";

foreach (sort(keys %stats))
{
	my ($cat,$item) = split(/:/,$_);

	if(not $item gt " ")
	{
		$item = "(none)";
	}
	if($cat ne $lastcat)
	{
		$lastcat = $cat;
		$cat =~ s/ //g;
		print "<tr><td><h2><a name=\"$cat\">$cat</a></h2></td><td><a href=\"#TOP\">[top]</a></td></tr>\n";
	}
	print "<tr><td align=\"center\">$stats{$_}</td>";
	if($lastcat eq "REFER " || $lastcat eq "REFERS")
	{	
		$item =~ s/\.\./:/g;
		$item =~ s/--/=/g;
		print "<td><a href=\"$item\">$item</a></td></tr>\n";
	} elsif($lastcat eq "HTTP  ")
	{	
		$item =~ s/\.\./:/g;
		$item =~ s/--/=/g;
		print "<td>$item</td></tr>\n";
	} else
	{
		print "<td>$item</td></tr>\n";
	}
}

print	"</table>";

	print "<!-- END CONTENT -->\n";

	open(BOILERPLATE,"<../child_post.html");
	while(<BOILERPLATE>)
	{
		print $_;
	}
	close(BOILERPLATE);
