#!/usr/bin/perl

use Image::Magick;

if (length ($ENV{'QUERY_STRING'}) > 0) {
	$buffer = $ENV{'QUERY_STRING'};
	@pairs = split(/&/, $buffer);
	foreach $pair (@pairs) {
		($name, $value) = split(/=/, $pair);
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		$in{$name} = $value; 
	}
}

#$f = 'r1b1k2r.ppppqppp.2n5.8.1PP2B2.3n1N2.1P1NPPPP.R2QKB1R';
$f = $in{'forsyth'};
$f2 = $f;
$f2 =~ s/\./\//g;
@b = &forsyth2array($f);

if ( $in{'image'} eq 'image' ) {
	print "Content-Type: image/png\n\n";
	&array2magick(@b);
} else {
	print "Content-Type: text/html; charset=utf-8\n\n";
	print <<EOHTML;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
                      "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Sample chess CGI</title>
  </head>
  <body>
    <h1>Sample chess CGI</h1>
    <h2>Forsyth Notation</h2>
    <p>$f2</p>
    <h2>Preformatted Text Representation</h2>
    <pre>
EOHTML
	array2stdout(@b);
    print <<EOHTML;
    </pre>
    <h2>Image</h2>
    <p><img alt="$f2" height="384" width="384"
    src="./chess.cgi?image=image&amp;forsyth=$f"></p>
  </body>
</html>
EOHTML
}


sub forsyth2array {
	$forsyth = shift @_;
	@rows = split(/[\.\/]/, $forsyth);
	$i = 8;
	foreach $r (@rows) {
		$j = 1;
		@chars = split(//, $r);
		foreach $c (@chars) {
			if ($c =~ m/\d/) {
				$j += $c;
			} else {
				$board[$i][$j++] = $c;
			}
		}
		$i--;
	}
	return @board;
}

sub array2stdout {
	for($x=8;$x>0;$x--) {
		for($y=1;$y<9;$y++) {
			if ($_[$x][$y]) { print $_[$x][$y]; }
			else            { print ' '; }
		}
		print "\n";
	}
}

sub array2magick {
	$image_obj = Image::Magick->new;
	$colour = 'white';
	for($x=8;$x>0;$x--) {
		for($y=1;$y<9;$y++) {
			if ($_[$x][$y]) {
				$status = $image_obj->Read('squares/' . $_[$x][$y] . '-' . $colour . '.png');
			}
			else {
				$status = $image_obj->Read('squares/0-' . $colour . '.png');
			}
			if ($colour eq 'white') {
				$colour = 'black';
			} else {
				$colour = 'white';
			}
		}
		if ($colour eq 'white') {
			$colour = 'black';
		} else {
			$colour = 'white';
		}
	}
	$montage = $image_obj->Montage (
					mode => 'Concatenate',
					background => '#ffffff',
					tile => '8x8',
					gravity => 'center',
					);
	binmode STDOUT;
	$montage->Write("png:-");
        		
	undef $montage;
	undef $image_obj;
	
}