#!/u/jc0/aix/bin/perl -w
#
#NAME
#  ExtractFortunes - write fortune cookies to ASCII files.
#
#SYNOPSIS
#  ExtractFortunes
#
#DESCRIPTION
#  This script  runs  the  fortune  program  repeatedly,  to  extract
#  fortunes  one  at a time.  It puts them into a subdirectory called
#  "fortune", using a name that is the first M chars of the  fortune.
#  With time, this should give us everything in the fortune file, one
#  per file.  So much for their attempt to hide it all from us  in  a
#  binary file.
#
#BUGS
#  We use the first 40 letters for the file name, so if two  fortunes
#  are identical in the first 40 chars, we will only get one of them.
#
#AUTHOR
# John Chambers <jc@trillian.mit.edu>

$M = $ARGV[0] || 50;
$path = $ENV{'PATH'};
$path = "/usr/games:$path";
$ENV{'PATH'} = $path;
$dir = "fortune";
system "mkdir -p $dir" if (! -d $dir);

while ($fortune = `fortune`) {
	($longname = $fortune) =~ s/\W//g;
	$name = $longname;
	if (length($name) > $M) {
		$name = substr($longname,0,$M);
	}
	$file = "$dir/$name";
	if (open(F,">$file")) {
		print F $fortune;
	} else {
		die "$0: Can't write $file [$!]\n";
	}
	sleep 1;
}
