#!/usr/bin/perl

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

$text = $input{"text"};
$perline = $input{"perline"};
$startline = $input{"startline"};
$advline = $input{"advline"};

if($text eq ""){
    $showtext = "";
    for($i = 0; $i < 11; $i++){
	$showtext .= "."x32 . "\n";
    }

    $perline = 4;
    $startline = 100;
    $advline = 10;



    } else {
	$showtext = $text;
        $x = 0; $y = 0;
	foreach $line (split(/\n/,$text)){
	    $rems .= " rem $line\n";
	    for($x = 0; $x < length($line); $x++){
		$c = substr($line,$x,1);

		if(isOnChar($c)){
		    push @pfp,"pfpixel $x $y on";
		}

	    }
	    $y++;
	}


    }


$result = "";


$c = 0;

$thisline = $startline; 

if($usenum ne "") {
    $result = "$thisline ";
} else {
    $result = " ";
}
$startnextthing = "";
foreach $p (@pfp){
    
    $result .=  $startnextthing."$p";
    $c++;
    if($c >= $perline){
	$c = 0;

	if($usenum ne "") {
	    $thisline += $advline;
	    $linefront = "$thisline ";
	} else {
	    $linefront = " ";
	}

	 $startnextthing =  "\n<br>$linefront";
    } else {
	$startnextthing = " : ";
    }
    

} 

sub isOnChar {
    my ($c) = @_;
    if($c eq "X" || $c eq "x" || $c eq  "#" || $c eq "1") {return 1;}
    return 0 ;
}

print<<__EOQ__;
<font face="courier,monospace,courier new">
<h2>bBpf</h2></font>
<pre>$result</pre>
<form method="POST">
A brutally simple tool for building up playfield graphics in batari BASIC.<br>
Edit the graphic below by enter "X" "1" or "#" for "on" Pixels.<br>
Press the button and bBpf will convert those pixels in to pfpixel x y on statements.<br>
<i>(Hint: press the "Insert" key to ensure you're in "overwrite" mode when typing in pixels)</i>
<br>
<textarea rows=12 cols=34
style="font-family: courier,monospace,courier new"
 name="text">$showtext</textarea>
<br><br>

    <input type="submit" value="convert to pfpixel instructions"><br>
<input name="perline" value="$perline" size=2> commands per line<br>
<input type="checkbox" name="usenum" $usenum value="CHECKED">Use Line Numbers
(Starting with line # <input name="startline" value="$startline" size=3>
advancing <input name="advline" value="$advline" size=2> each line)
<br>


</form>

</font>
<pre>$rems</pre>
__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);}

