#! /uva/bin/perl5

# split file paragraphs (separated by \n\n) into separate numbered files and
# store them in a directory named inputfile.dir along with an indexdir.html
# file containing links to each file

# John Porter, Sept. 2000

print("Input file is $ARGV[0]\n");
$infilename= $ARGV[0];
if (!(open (INFILE,"<$infilename"))){
	die("Input file $infilename not found");
	}

$outputdir=$ARGV[0] . ".dir";
if (!( -d $outputdir)){
	if (!(mkdir($outputdir))){
		die("could not create output directory $outputdir\n");
	}
}

$indexfilename= $outputdir . "/indexdir.html" ;
if (!(open(INDEXFILE,">$indexfilename"))){
	die("unable to open $indexfilename for output");
}

$inline=<INFILE>;
chop($inline);
$inline =~ s/\r//gi;
$lastlineisblank=0;
$ref="";
$count=1;
until (eof(INFILE)){
 	if ($lastlineisblank == 1){
		$outfilename= $ARGV[0] . sprintf("%05d",$count) . ".txt" ;
		print("Writing $outputdir/$outfilename \r");
		if (!(open (OUTFILE,">$outputdir/$outfilename"))){
			die("\nCan't open output file $outputdir/$outfilename");
			}
		$ref =~ s/^ //;
		$ref =~ s/[ \t]$/ /g;
		$ref =~ s/[ \t]+/ /g;
		print(OUTFILE "$ref\n\n");
		print(INDEXFILE "<a href=\"$outfilename\">$count</a><br>\n");
		$ref="";
		close(OUTFILE);
		$count++;
	}
	$ref = $ref . $inline . " " ;
	$lastlineisblank = ($inline =~ /^[\t ]*$/) ;
	$inline=<INFILE>;
	chop($inline);
	$inline =~ s/\r//gi;
}
close(INDEXFILE);
$count--;
print("\nDone - $count references output\n");
