#!/usr/bin/perl -w

# This takes a file that is a 1 byte grayscale (or, in some cases, an indexed 
# color file) and converts it into a PPM for viewing. 

die "Usage: genRawFromClut.pl <input RGBA raw> <1-byte output> <RGBA16 clut>\n" unless $#ARGV==2;

#discards alpha!

$in = shift;
$out = shift;
$clutFile = shift;


open(INFILE, "<$in") or die "Can't open $in: $!";
open(OUTFILE, ">$out") or die "Can't open $out: $!";
open(CLUTFILE, "<$clutFile") or die "Can't open $clutFile: $!";

read( CLUTFILE, $clut, 1000 );

$idx = 0;
$counter = 0;

while( read(INFILE, $byte, 4) != 0 ) {
    $rval =vec($byte, 0, 8);
    $gval =vec($byte, 1, 8);
    $bval =vec($byte, 2, 8);

    $it = -1;

    for ($i = 0; $i < 1000; $i++) {
	$rgb = vec( $clut, $i, 16 );

	$r = int(  (( $rgb & 0xf800 ) >> 11) * 255/31 );
	$g = int( (( $rgb & 0x07c0 ) >> 6)  * 255/31);
	$b = int( (( $rgb & 0x003e ) >> 1)  * 255/31);
#	$a = ( $rgb & 1 );

	if ($rval == $r && $gval == $g && $bval == $b )
	{
#	    print"!";
	    $it = $i;
	    last;
	}
    }  
    $idx++;
#    if ( $idx > 10 ) { printf OUTFILE "\n"; $idx = 0; }
    if ( $it != -1 )
    {
	syswrite( OUTFILE, (pack("C", $it ) ), 1 );
    } else {
	$it = 0;
	print("*");

	$counter++;

	print("Couldn't find color $rval $gval $bval \n");

	syswrite( OUTFILE, (pack("C", $it ) ), 1 );
    }

}
print "\nMissed colors on the following number of pixels: $counter $in\n";
close INFILE;
close OUTFILE;
