#!/usr/bin/perl

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

if ($ENV{'QUERY_STRING'} =~ /result(\=(\w+))|/)
{
	my ($result) = "";
	my ($ip_used) = 0;
	my ($message) = "";
	my ($successful) = 0;
	my (%results) = ();

	$results{"paper"} = 0;
	$results{"populist"} = 0;
	$results{"iconview"} = 0;
	$results{"parameteriser"} = 0;

	$result = $2;

	# Check the IP address
	my ($ip) = $ENV{"REMOTE_ADDR"};

	if (open (IPADDR, "ipaddresses"))
	{
		while ($ips = <IPADDR>)
		{
			chomp ($ips);
			if ($ips eq $ip)
			{
				$ip_used = 1;
			}
		}

		close (IPADDR);
	}

	$successful = 1;

	if ($ip_used != 1)
	{
		# This address has not been used yet, we need to add it to our file
		if (open (IPADDR, ">>ipaddresses"))
		{
			print IPADDR "$ip\n";
			close (IPADDR);
		}
		
		# Write the results out to file
		if (open (RESULTS, ">>results"))
		{
			print RESULTS "$result\n";
			close (RESULTS);
		}
	}

	# Read in the file and print out the results
	if (open (RESULTS, "results"))
	{
		while ($result_line = <RESULTS>)
		{
			chomp ($result_line);

			if ($result_line eq "paper")
			{
				$results{"paper"}++;
			}

			if ($result_line eq "populist")
			{
				$results{"populist"}++;
			}

			if ($result_line eq "iconview")
			{
				$results{"iconview"}++;
			}

			if ($result_line eq "parameteriser")
			{
				$results{"parameteriser"}++;
			}
		}

		close (RESULTS);
	}

	# draw the bar charts
	if ($successful == 1)
	{
		my $width = $results{"paper"} * 10;
		$output  = "<BR><a href=\"paper.shtml\">Paper</a><BR><IMG SRC=\"barstart.gif\" width=7 height=15><IMG SRC=\"barmiddle.gif\" width=$width height=15><IMG SRC=\"barend.gif\" width=12 height=15> $results{\"paper\"}<BR><BR><BR>";
		$width = $results{"populist"} * 10;
		$output .= "<BR><a href=\"populist.shtml\">Populist</a><BR><IMG SRC=\"barstart.gif\" width=7 height=15><IMG SRC=\"barmiddle.gif\" width=$width height=15><IMG SRC=\"barend.gif\" width=12 height=15> $results{\"populist\"}<BR><BR><BR>";
		$width = $results{"iconview"} * 10;
		$output .= "<BR><a href=\"iconview.shtml\">Iconview</a><BR><IMG SRC=\"barstart.gif\" width=7 height=15><IMG SRC=\"barmiddle.gif\" width=$width height=15><IMG SRC=\"barend.gif\" width=12 height=15> $results{\"iconview\"}<BR><BR><BR>";
		$width = $results{"parameteriser"} * 10;
		$output .= "<BR><a href=\"parameteriser.shtml\">Parameteriser</a><BR><IMG SRC=\"barstart.gif\" width=7 height=15><IMG SRC=\"barmiddle.gif\" width=$width height=15><IMG SRC=\"barend.gif\" width=12 height=15> $results{\"parameteriser\"}<BR><BR><BR>";
	}

	# output the templates
	if (open (HEADER, "results_top.shtml"))
	{
		while (<HEADER>)
		{
			print $_;
		}

		close (HEADER);
	}

	if (open (MENU, "menu.shtml"))
	{
		while (<MENU>)
		{
			print $_;
		}

		close (MENU);
	}

	if (open (MID, "results_mid.shtml"))
	{
		while (<MID>)
		{
			print $_;
		}

		close (MID);
	}

	print $output;

	if (open (FOOTER, "results_bottom.html"))
	{
		while (<FOOTER>)
		{
			print $_;
		}

		close (FOOTER);
	}
}
