#!/usr/local/bin/perl

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

print "<BODY BGCOLOR=\"WHITE\">\n\n";


&chugCGI(*input);
$size = $input{"size"};
$diag = $input{"diag"};
if($size eq "") {
$size = 3;
}

print<<__EOQ__;
<html>
<script language ="javascript">


grid = new Array(9);
var size=$size;

function display(which){
	if(grid[which]) {
		document . images ['space'+which] . src = 'star.gif'
	} else {
		document . images ['space'+which] . src = 'blank.gif'
	}

}


function randomize(){
    var s;
    for(x = 0; x < size; x++){
	for(y = 0; y < size; y++){
	    s = x+(y*size);
	    grid[s] = Math.floor(Math.random() * 2);
	    display(s);
	}
    }
}


function remid(){
    var x,y,s;
    for(x = 0; x < size; x++){
        for(y = 0; y < size; y++){
            s = x+(y*size);
            grid[s] = 0;
            display(s);
        }
    }

    x = (size-1) / 2;
    y = (size-1) / 2;
    s = x+(y*size);
    grid[s]=1;
    display(s);
}



function flip(x, y){
var s;
if(x>=0 && x < size && y>=0 && y < size){
s=x+(y*size);
grid[s]= !grid[s];
display(s);
}
}

function toggle(s){
	var i,j,x,y;
	x = s % size;
	y = Math.floor(s / size);
__EOQ__
if($diag ne "") {	
print<<__EOQ__;
	for(i=-1;i<=1;i++){
		for(j=-1;j<=1;j++){
			flip(x+i,y+j);
		}
	}
__EOQ__
} else {
print<<__EOQ__;
	flip(x,y);
	flip(x+1,y);
	flip(x-1,y);
	flip(x,y+1);
	flip(x,y-1);

__EOQ__

}


$middle = (($size*$size) -1 ) /2 ;

print<<__EOQ__;

}




</script>


      <body onLoad="grid[$middle]=true;">
<CENTER>
<H2>'Blackhole' Puzzle</H2>

__EOQ__
$ctr = 0;
for($i = 0; $i < $size; $i++){
for($j = 0; $j < $size; $j++){

if($i == (($size - 1)/2) && $i  == $j){
	$img = "star.gif";

} else {
	$img = "blank.gif";

}

print<<__EOQ__;
	<a href="#" onClick="toggle($ctr);return false;">
	<img name = "space$ctr" src="$img" border="0"></A>
__EOQ__
$ctr++;
}
print "<BR>";
}


print<<__EOQ__;
<FORM action="index.cgi">
<INPUT TYPE="CHECKBOX" NAME="diag" $diag >include diag.<br>
<input type="button" value="Random" onClick="randomize()">
<input type="button" value="Reset" onClick="remid()">
<br>
size:
<SELECT NAME="size">
__EOQ__
for($j = 3; $j <= 15; $j+= 2){

if($j == $size) {
print "<OPTION SELECTED>$j\n";
} else {
print "<OPTION>$j\n";
}
}

if($diag ne "") { $diag = "CHECKED";}
print<<__EOQ__;
</SELECT>
<INPUT TYPE="submit" VALUE="Resize"><BR>
      </body>
     </html>

__EOQ__




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