#!/usr/bin/perl

=head1 NAME
   SplitSayings

=head1 SYNOPSIS
   SplitSayings [-p prefix] [file]..

=head1 DESCRIPTION
   This program splits its input file(s)  into  chunks  separated  by
   blank  lines,  and  writes  each into a separate file.  The files'
   names are the first 40 alpha charsof the chunk. The use of this is
   to  split up files that contain cookies or single-paragraph jokes,
   putting each entry into a separate file.

   If an output file already exists, we add a  number  to  the  name.
   This will happen if you rerun this program on the same input.

=head1 FILES
   We read from standard input if there are no files  listed  on  the
   command line. The default output prefix is "$HOME/cookies/" at the
   present, though this may change without warning.

=head1 AUTHOR
   John Chambers <jc@trillian.mit.edu>

=cut

$| = 1;
if ($ARGV[0] =~ m/^-p(.*)/i) {
	if ($1 eq '') {
		$prefix = $ARGV[2];
		shift;
	} else {
		$prefix = $1;
	}
	shift;
} else {
	$prefix = $ENV{HOME} . '/cookies/';
	if (! -d $prefix) {
		mkdir($prefix,0775);
	}
}

for $l (<>) {
	$l =~ s/\s*$//;
	if ($l) {
		$txt .= $l . "\n";
		next;
	}
	next if !$txt;
	($let = $txt) =~ s/[^A-Za-z0-9]//g;
	$n = length($let);
	$n = 40 if $n > 40;
	$fil = $prefix . substr($let,0,$n);
	$path = $fil;
	$i = 0;
	while (-f $path) {
		$i++;
		$path = sprintf("%s%03d",$fil,$i);
	}
	if (open(F,">$path")) {
		print F $txt;
		close F;
	} else {
		print STDERR "$0: Can't write $path [$!]\n";
	}
	$txt = '';
}
