#!/usr/bin/perl

use LWP::Simple;
use Time::Local;

print "Content-type: text/html\n\n";
print <<EOT;
<HTML>
<TITLE>Metabuzz</TITLE>
</HTML>
<BODY BGCOLOR=darkgreen>
<CENTER>
<TABLE BORDER=0 WIDTH=500 CELLSPACING=0 CELLPADDING=0>
<TR><TD BGCOLOR=white>
<img src=../metabuzz.gif WIDTH=500 HEIGHT=150><br>
<table border=0 bgcolor=black cellpadding=50 width=500><tr><td bgcolor=white>
<!--If you have Flash, try the <a href=../buzz.swf>aggregator tool</a>.-->
<p>
<table><tr>
EOT

$googleurl = "http://www.google.com/press/zeitgeist.html";
$google = cachedget("cache/google", $googleurl);

($chunk) = ($google =~ m!Gaining Queries.*?</table>(.*?)</table>!s);
while ($chunk =~ m!<b>(\d+)\..*?>([^<]+)</a>!gs) {
	$google[$1] = $2;
}

display ("Google", $googleurl, @google);

print "\n";

$yahoourl = "http://buzz.yahoo.com/overall/";
$yahoo = cachedget("cache/yahoo", $yahoourl);
while ($yahoo =~ m!<tr.*?<b>(\d+)</b>.*?<b>(.*?)</b>!gis) {
	$yahoo[$1] = $2;
}

display("Yahoo", $yahoourl, @yahoo);

print "\n";

$lycosurl = "http://50.lycos.com/";
$lycos = cachedget("cache/lycos", $lycosurl);

while ($lycos =~ m!<b><font size="2">(\d+)</font></b>.*?([^<>]*)</a>!gs) {
	$lycos[$1] = $2;
}

display ("Lycos", $lycosurl, @lycos);

print "</tr></table>";
print <<EOT;
<div align="right">
<!-- Google Conversion Code -->
<script language="JavaScript">
<!--
    google_conversion_id = 1070872221;
google_conversion_language = "en_US";
if (1.0) {
    google_conversion_value = 1.0;
}
google_conversion_label = "Purchase";
-->
</script>
<script language="JavaScript" src="http://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<a href="http://services.google.com/sitestats/en_US.html" target=_blank>
<img height=27 width=135 border=0 src="http://www.googleadservices.com/pagead/conversion/1070872221/?value=1.0&label=PageView&hl=en">
</a>
</noscript>
</div>
EOT
print "</td></tr></table></td></tr></table></body></html>";

sub display {
	my ($site, $url, @listings) = @_;
	print "<td width=33% valign=top><table bgcolor=lightgreen>";
	print "<tr><td colspan=2 bgcolor=yellow><h3><a href=$url>$site</a></h3></td></tr>";
	for ($i = 1; $i <= $#listings; $i++) {
		print "<tr><td><font size=-1>$i</font></td><td><font size=-1>$listings[$i]</font></td></tr>\n";
	}
	print "</table></td>\n";
}

sub cachedget {
	($file, $url) = @_;
	$filetime = timelocal(localtime((stat($file))[9]));
	$now = timelocal(localtime(time));
        $filetime += (60 * 60 * 24);
 	if ((-e $file) && ($filetime > $now)) {
		open (F, $file);
		my $foo = join("\n", <F>);
		close(F);
                return $foo;
	}
	$retval = get($url);
	open (F, ">$file");
	print F $retval;
	close(F);
	return $retval;
}
