#!/usr/bin/perl
use GD;
require "/home/dave/roll.pl";
require "../cgi-lib.pl";
ReadParse(*params);

my($roll) = $params{roll} || "3d6-1";
my($iters) = ($params{iters} =~ /^\d+$/) ? $params{iters} : 10000;
$iters = 1 if($iters < 1);
$iters = 1000000 if($iters > 1000000);

if(!verify_roll($roll)) {
    print "Content-Type: text/html\n\n";
    print "Error: Bad roll: $roll<br>\n";
}
my($max) = maxroll($roll);
my($min) = minroll($roll);
for($i=0;$i<$iters;$i++) {
    $r = roll($roll);
    $results{$r}++;
    $max = $r if($r>$max);
}

$bar_width = $params{bar_width} || 5;
$bar_width = 5 if($bar_width > 20 || $bar_width < 1 || $bar_width !~ /^\d+$/);
$space_width = $params{space_width} || 1;
$space_width = 1 if($space_width > 20 || $space_width < 0 || $space_width !~ /^\d+$/);
$width = ($max - $min + 1) * ($bar_width+$space_width) + $space_width;
$height = 200;
$maxv = $params{maxv} || 0.25;
$maxv = 0.1 if($maxv > 1 || $maxv <= 0 || $maxv !~ /^\d*\.?\d+/);

$img = new GD::Image($width+10,$height+20,1);
$img->fill(0,0,color(255,255,255));
$last_x = -1000;
for($r=$min;$r<=$max;$r++) {
    $offset = ($r-$min)*($bar_width+$space_width);
    $img->filledRectangle($offset+1,$height-($results{$r}/($iters*$maxv))*$height,$offset+$bar_width,$height,color(255,0,0));
    if($offset > $last_x+15) {
	$img->line(int(($offset*2+$bar_width+1)/2),$height+2,int(($offset*2+$bar_width+1)/2),$height+4,color(0,0,0));
	$img->string(gdTinyFont,int(($offset*2+$bar_width+1)/2)-1,$height+5,"$r",color(0,0,0));
	$last_x = $offset;
    }
}

print "Content-Type: image/png\n\n";
binmode STDOUT;
print $img->png;

sub color {
    my($r,$g,$b) = @_;
    if(!defined($pal{"$r\_$g\_$b"})) {
        $pal{"$r\_$g\_$b"} = $img->colorAllocate($r,$g,$b);
    }
    return $pal{"$r\_$g\_$b"};
}
