#!/local/perl/bin/perl -w
# =============================================================================
#  An attempt at FORTUNE in perl
#
#  - Kevin O. Grover, 15 Feb 1993
#
#  To Do:
#  - Find out how scene,obscene and long are differentiated
#  - all QTS and IDX files to be specified in env vars
#  - make compatible w/ berkly fortune
# =============================================================================

$fortfileqts = $ENV{"FORTUNE"} || "c:/etc/fortunes";      # Quotes
$fortfileidx = $ENV{"FORTIDX"} || "c:/etc/fortunes.idx";  # Index into quotes

open (IDX,"<$fortfileidx") || die "Can't open index, $fortfileidx: $!\n";
binmode IDX;
$tmp = 0;
sysread (IDX, $tmp, 4);
($numfortunes) = unpack("L", $tmp);

srand(time());
&getfortune(int(rand($numfortunes)));
close(IDX);

#
# -----------------------------------------------------------------------------
#
 
sub getfortune {
 local($num) = @_;

 #print "Num = $num\n";

 if ($num ==  0) {
     $pos = 0;
 } else {
     seek (IDX, $num*4, 0);
     sysread (IDX, $tmp, 4);
     $pos = unpack ("L", $tmp);
 }

 open(QTS, "<$fortfileqts")  || die "Can open quotes, $fortfileqts: $!\n";
 seek (QTS, $pos, 0);
 print "\n";                            # Blank line before quote
 while (($_ = <QTS>) && !m/^%/o) {
   print;
 }
 print "\n";                            # Blank line after quote
 close(QTS);
}
