#!/usr/bin/perl
use Data::Dumper;
require "../cgi-lib.pl";
use GD;
$fname = "/tmp/tmp.$$.gif";
ReadParse(*params);
print "Content-Type: text/html\n\n";

print "<form method=post enctype=\"multipart/form-data\">\n";
print "GIF File: <input type=file name=\"file\"><br>\n";
print "Hide Color Values? <input type=checkbox name=hide_values value=1".(($params{hide_values}) ? " checked" : "")."><br>\n";
print "<input type=submit value=\"Upload\"><br>\n";
print "</form>\n";

if($params{file}) {
    if($params[0] =~ /filename=['"]([^\'\"]*)['"]/) {
	print "File Recieved: <b>$1</b><br>\n";
    }
    #print "Processing upload...<br>\n";
    if(open(GIF,"> $fname")) {
	#print "Examining file...<br>\n";
	print GIF $params{file};
	close GIF;
	if(!open(GIF,$fname)) {
	    print "Could not read file!<br>\n";
	    exit(1);
	}
	$img = newFromGif GD::Image(GIF);
	close GIF;
	if(!$img) {
	    print "Could not process GIF file (maybe not a GIF?)<br>\n";
	    exit(1);
	}
	my($maxx,$maxy) = $img->getBounds();
	if($maxx <= 0 && $maxy <= 0) {
	    print "Absurdly small GIF or file error?<br>\n";
	    exit(1);
	}
	print "Dimensions: <b>$maxx x $maxy</b><br>\n";
	
	print "Colors:<br>\n";
	for($x=0;$x<=$maxx;$x++) {
	    for($y=0;$y<=$maxy;$y++) {
		$color = $img->getPixel($x,$y);
		$colors{$color}++;
	    }
	}
	print "<table border=1>\n";
	print "<tr>\n";
	print "<th>Color</th>\n";
	if(!$params{hide_values}) {
	    print "<th>RGB</th>\n";
	    print "<th>Hex</th>\n";
	}
	print "<th>Count</th>\n";
	print "</tr>\n";
	foreach my $color (keys %colors) {
	    print "<tr>\n";
	    my($r,$g,$b) = $img->rgb($color);
	    my($hex) = sprintf("%02X%02X%02X",$r,$g,$b);
	    print "<td bgcolor=#".$hex.">&nbsp;&nbsp;&nbsp;</td>\n";
	    if(!$params{hide_values}) {
		print "<td>$r,$g,$b</td>\n";
		print "<td>$hex</td>\n";
	    }
	    print "<td>$colors{$color}</td>\n";
	    print "</tr>\n";
	}
	print "</table>\n";
    }
}

END {
    unlink($fname);
}
