#!/usr/bin/perl -w

use Chess::PGN::Parse;
use GD::Graph::lines;
use Data::Dumper;
use CGI qw/-no_xhtml :standard/;
use CGI::Carp qw(fatalsToBrowser);

unless (param()) {
   print header, start_html("PGNGrapher"), h1("PGNGrapher -- error."),
         "This script should be run with form parameters present.\n";
   
}

my $string = param('pgnstring');
my $player = param('player'); 
my $pgn = new Chess::PGN::Parse undef, $string;

my ($colour, $counter, $rating, $counterwhite, $counterblack);
my $lowrating=0;
my $highrating=0;
my (@ratings, @dates, @data);

while ($pgn->read_game()) {
    $colour = "white" if $pgn->white eq $player;
    $colour = "black" if $pgn->black eq $player;
    
    $hash_ref = $pgn->tags();
    
    if ($colour eq "white") {
        $rating = ${$hash_ref}{WhiteElo};
        $counterwhite++;
    } elsif ($colour eq "black") {
        $rating = ${$hash_ref}{BlackElo};
        $counterblack++;
    } else {
        die "Can't find $player in game $counter.\n";
    }

    $lowrating =  $rating if $rating < $lowrating;
    $highrating = $rating if $rating > $highrating;

    my $date = ${$hash_ref}{Date};
    $date =~ s/\.\d{2}$//;
    $counter++;
    
    push @ratings, $rating;
    push @dates, $date;
}

# Create GD's two-dimensional array.   
$data[0] = [(@dates)];
$data[1] = [(@ratings)];

# Plot.
my $graph = GD::Graph::lines->new(400, 300);
$graph->set( title => "PGNgrapher -- $player." );
$graph->set( x_label_skip => $counter/6 );
my $gd = $graph->plot(\@data);

open(IMG, '>/home/cjb/pub/pgngrapher/pgngraph.png') or die $!; binmode IMG; 
print IMG $gd->png;

print header, start_html("PGNGrapher results"), h2("PGNGrapher Results");

print "<p>I looked at <b>$counter</b> games, of which <b>$player</b> played white <b>$counterwhite</b> times and black <b>$counterblack</b> times.  The rating of <b>$player</b> ranged from <b>$lowrating</b> to <b>$highrating</b>.";
print "<P>Graph of results:";
print "<P><IMG src=\"/cjb/pgngrapher/pgngraph.png\"></IMG></HTML>"

