#!/usr/bin/perl

my $TDCOLOR = '#f6f6f6';

#==============================

use strict;
use vars;
use CGI qw(:standard);
my ($label, $link, $line, $ncount, $ucount, $url);
my (@articles);


# Direct to what we need to do.
$url = param("link");
if ($url) {
&display_frames();
} else {
&getlink();
}

sub getlink {
print header();
open(ARTICLES, "toc/rant_articles") || 
	&bail("Something is very, very wrong. $!");

# Get articles for display.
while (defined($line = (<ARTICLES>))) { 
next unless ($line =~ /^[N|E|U]/);
push(@articles, $line); 
}
close ARTICLES;

# Get the counts.
foreach $line (@articles) {
  $ncount++ if ($line =~ /^N/);
  $ucount++ if ($line =~ /^U/);
}

my @newarts;
if ($ncount > 0) {
foreach $line (@articles) {
next unless ($line =~ /^N/);
($label, $link) = (split(/\#/, $line))[0,1];
push(@newarts, $link);
}
   $link = $newarts[rand(@newarts)];
} else {

# Randomize and display an article if there are no NEW
# articles.
   $link = $articles[rand(@articles)];
   $link = (split(/\#/, $link))[1]; 
}

$ncount--;

# Massage the link. 
# Fix it so it goes to the right spot, and includes the frames.
$link =~ s/\.\.\//\.\//;
$link =~ s/<A HREF="(.*)">/<A HREF="new_article.cgi?link=$1">/ig;

# Tables.
print '
<table BORDER="0" CELLPADDING="1">
<tr><td bgcolor="#DEDEDE">
<table width=300 BORDER="0" CELLPADDING="6" CELLSPACING="0">
<tr><td bgcolor="#ffffff">
<center>';

print '<TABLE BORDER=0 cellpadding=4>';
print '<TD>';
print '<FONT COLOR=RED SIZE=-2 FACE=verdana><B>NEW</B>'
         if ($label eq "N");
print '</TD>';
print "<TD BGCOLOR=\"$TDCOLOR\"><FONT FACE=verdana SIZE=-2>";
print '<center>';
print $link;
print '</center>';
print '</font></TD></TABLE>';

print '<font size=-2 face=\"arial narrow\">';
if ($ncount > 0) {
	print '<br>' . $ncount . " other ";
	print '<FONT COLOR=RED SIZE=-2 FACE=verdana><b>';
	print 'NEW';
	print '</b></FONT>';
	print  ' tidbit'; 
	print "s" if ($ncount > 1);
	print ".";
}
if ($ucount > 0) {
	print '<br>';
	print $ucount;
	print '<FONT COLOR=RED SIZE=-2 FACE=verdana>';
	print ' UPDATED';
	print '</FONT>';
	print  ' tidbit'; 
	print "s" if ($ucount > 1);
	print ".";
}
print '</font>
</td></tr></table></td></tr></table>';
}


sub bail {
print '<font size=-1 color=red><b>';
print shift;
print '</font><br><br>
Please mail <a href="mailto:rant@martini.nu">rant</a> with this error and the time.';
print "</FONT>";
exit;
}

# Output frames.
sub display_frames {
print header();
print <<EOT;
<HTML>
<HEAD></HEAD>

<frameset rows='42,*' frameborder='No' framespacing='0' border='0'>
  <frame src='topframe.html' name='header' marginwidth='0' scrolling='no'
        marginheight='0' frameborder='no' noresize framespacing='0'>
  <frame src="$url" name='content' scrolling='yes' marginwidth='0'
        marginheight='0' frameborder='no' noresize framespacing='0'>
</frameset>


<BODY>Jump into the 21st century and get a browser with frames.</BODY></HTML>
EOT

exit;
}

