#!/usr/local/bin/perl
#
# Author: Brad Donison <bdonison@grmi.org>
#
# print a random line of text based on what page called this routine.
# If called from a page called random.html, then the lines of text from which
# we choose a single line at random, would be random.rnd in the same location
# as random.html
#
# this cgi relies on wwwgrab
#
# Note that the random function seems to be broken; thus the hack to generate
# a random number within our desired range...

# set this to be your Web server URL
#$site = "http://www.grmi.org";
$site = "http://".$ENV{'SERVER_NAME'};

# the location of the wwwgrab script
$wwwgrab = "/local/www/tools/wwwgrab";

print "ContentType: text/html\n\n";

$txtfile = $ENV{'DOCUMENT_URI'};
$txtfile =~ s/\.html$/\.rnd/;
$txtfile =~ s/\.htm$/\.rnd/;

if ($txtfile !~ /\.rnd$/) {
  exit 0;
}

$rndfile = $site.$txtfile;

$file = `$wwwgrab $rndfile`;
@lines = split (/\n/, $file);
$max = $#lines + 2;
$mult = 10;
srand(time);
$num = rand;
$orignum = $num;
while (!$valid) {
  while ($num < 1) {
    $mult = $max if ($num > 0.1);
    $num = $num * $mult;
  }
  $index = int($num);
  if ($index < $max) {
    $valid = $index;
  } else {
    $num = rand;
  }
}

#print "Lines read: $max<br>Random number: $num ($orignum)<br>Index number: $index<p>\n";

print "$lines[$index - 1]";
