#!/usr/bin/perl

print "Content-type:text/html\n\n";
&chugCGI(*input);

$text = $input{"text"};
$includecode = $input{"includecode"};


foreach $line (split(/\n/,$text)){
#    if($line =~ /^(\s+)(\S.*)$/){
#        $oldspace = $1;
#        $oldrest = $2;
#        $newspace = "&amp;nbsp;" x length($oldspace);
#        $result .= $newspace.$oldrest."\n";

    if($line =~ /^( +)(.*)$/){
	$oldspace = $1;
	$oldrest = $2;
	$newspace = "  " x length($oldspace);
	$result .= $newspace.$oldrest."\n";
    } else {
	$result .= $line."\n";
	}
}



if($includecode ne ""){
    $result = "[CODE]\n".$result;
    chomp $result;
    $result .= "\n[/CODE]";
}


print<<__EOQ__;
__EOQ__

if($result ne ""){
    print <<__EOQ__;
<pre>$result</pre>
__EOQ__
} else {
    print<<__EOQ__;
<font face="courier,fixed">
<h2>AAbBCc -- The Atari Age Batari BASIC Code Cleaner</h2>

Copy bB programs below and hit the button. The program will return a version, ready for cutting and pasting (On windows, ctrl-a select all, ctrl-c copy) that will preserve the crucial indentation for using in the Atari Age forums.<br><br>
</font>

<form method="POST">

<textarea rows=20 cols=80 name="text"></textarea>
<br>
<input type="checkbox" name="includecode" CHECKED>Include [CODE] tags
    &nbsp;    &nbsp;    &nbsp;    &nbsp;    &nbsp;    &nbsp;

<input type="submit" value="generate indented code">

</form>

</font>

__EOQ__

}


sub chugCGI { local (*in) = @_ if @_; local ($i, $key, $val);
if($ENV{'REQUEST_METHOD'}eq"POST") { read(STDIN,$in,$ENV{'CONTENT_LENGTH'});
 }else {$in = $ENV{'QUERY_STRING'};} @in = split(/&/,$in);
foreach $i (0 .. $#in) { $in[$i] =~ s/\+/ /g;
($key, $val) = split(/=/,$in[$i],2);$key =~ s/%(..)/pack("c",hex($1))/ge;
$val =~ s/%(..)/pack("c",hex($1))/ge; $in{$key}.= $val;}return length($in);}

