#!/usr/bin/perl
require "kisrael.pl";

&chugCGI(*input);

$raw = $input{"text"};
$old = $input{"old"};
$other = $input{"other"};
$dobreak = $input{"dobreak"};

if($raw eq ""){

print "Content-type:text/html\n\n";

print<<__EOQ__;
<head><title>FATLINER</title></head>
<a href="/">kisrael.com</a> | <a href="/tools/">tools</a> |
<b>FATLINER</b><br>
This tool is useful if you have plain text (for example, from 
<a href="http://www.gutenberg.org/">Project Gutenberg</a>) that has been 
"wordwrapped" at a certain width with carriage returns, but your preferred viewing method can do its own wordwrapping thankyouverymuch.  Cut and paste 
the text into the box below, select the current paragraph marker, indicate if you
would like a blank line left between paragraphs, then hit "FATLINE!"
<br>
<form method="post">
<b>original text:</b><br>
<textarea name="text" cols=80 rows=15></textarea><br>
<table border=0><tr><td>
<b>current paragraph marker:</b><br>
<select name="old">
<option selected value="returns">blank lines
<option value="4space">4 spaces
<option value="5space">5 spaces
<option value="8space">8 spaces
<option value="tab">tab
<option value="other">Other (specify)
</select>
other:<input name="other"><br>
<b>output:</b><br>
<input type="checkbox" checked name="dobreak">include blank line between paragraphs
</td><td>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="submit" value="FATLINE!"><br>	
</td></tr></table>

</form>
__EOQ__
} else {
$raw =~ s/\r//g;
if($old eq "returns"){
	$oldbreak = "\n\n";
} elsif($old eq "4space"){
	$oldbreak = " "x4;
} elsif($old eq "5space"){
	$oldbreak = " "x5;
} elsif($old eq "8space"){
	$oldbreak = " "x8;
} elsif($old eq "tab"){
	$oldbreak = "\t";
} else {
	$oldbreak = $other;
}

if($dobreak ne "") {
	$newbreak = "\n\n";
} else {
	$newbreak = "\n";
}
$buffer = "";
$raw =~ s/$oldbreak/\[\[EOL\]\]/g;
@lines = split(/\n/,$raw);
foreach $line(@lines){
    $blank = "";
    #if the buffer ends with a non blank character
    #and this line starts with a nonblank character,
    #insert a space between
    if($buffer =~ /\S$/ && $line =~ /^\S/){
	$blank = " ";
    }	
    $buffer .= $blank.$line;
    
}
$buffer =~ s/\[\[EOL\]\]/$newbreak/g;

print "Content-type:text/plain\n\n";
print $buffer;
}

