#!/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: genPPMfromClut.pl <input 1 color raw> <output PPM> <width> <height> <clut>\n" unless $#ARGV==4;

$in = shift;
$out = shift;
$width = shift;
$height = 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: $!";

printf( OUTFILE "P3 ");
printf( OUTFILE $width );
printf( OUTFILE " " );
printf( OUTFILE $height );
printf( OUTFILE " 255\n");

read( CLUTFILE, $clut, 1000 );

$idx = 0;

while( read(INFILE, $byte, 1) != 0 ) {
    $val =vec($byte, 0, 8);

    $rgb = vec( $clut, $val, 16 );

    $r = int(  (( $rgb & 0xf800 ) >> 11) * 255/31 );
    $g = int( (( $rgb & 0x07c0 ) >> 6)  * 255/31);
    $b = int( (( $rgb & 0x003e ) >> 1)  * 255/31);

    $idx++;
    if ( $idx > 10 ) { printf OUTFILE "\n"; $idx = 0; }
    print( OUTFILE $r, " ", $g, " ", $b, " " );

}
close INFILE;
close OUTFILE;
