#!/usr/local/bin/perl

# Where is palette.dat
$palfile= "/home/pauillac/cristal/pessaux/ocamldoom/palette.dat";

#### palette creation

$header = "id=ImageMagick \
columns=64 rows=64 \
class=PseudoClass colors=256 \
 \
:\n";

# We suppose palette.dat exactly contains 256 RGB triples
open (PIN, $palfile);
$p = "";
for($i=0; $i<256*3; $i++){
    $c = <PIN>;
    $c = sprintf ("%c", $c);
    $p = "$p$c";
}
close PIN;
$header = "$header$p";

# create a data file for mogrify 
open (POUT, "> colorsample.miff");
print POUT $header;
for($i=0; $i<4096; $i++){
    printf POUT "%c", ($i % 256); # So that it uses all the colors.
}
close POUT;

# Loop

for $file (@ARGV){
# make tmp and use it
    print STDERR "Converting $file -> ";
    if ( !($file =~ /([^\/]+)\.[^\.]*$/)) {
	die "use body.ext filename!";
    }
    $filebody = "$1"; 
    print STDERR "$filebody.raw ... ";
    
# make temp. file for mogrify
    `convert $file +compress MIFF:$filebody.miff`;
    $file = "$filebody.miff";

# use mogrify so that the image has the same colormap.
    `mogrify -map colorsample.miff +compress $file`;
# for checking the result.
    `convert $file GIF:$filebody.result.gif`;

# unfortunately, the colormap is compressed...
# so, we must translate them by hand...

#### GET COLORSAMPLE's COLORMAP

# It contains whole the colors defined in duke.pat
    open (IN, "colorsample.miff"); 
    while(<IN>){
	chop;
	if ( $_ eq ":" ) { last; }
	if (/colors=([0-9]+)/) { # How many colors ?
	    $samplecolors = $1;
	}
    }
    read(IN, $samplemap, $samplecolors*3);
    close IN;
    for($i=0; $i<$samplecolors; $i++){
	$sample[$i] = substr($samplemap, $i * 3, 3); 
    }

#### GET INPUT FILE's COLORMAP

    open (IN, $file);
    while(<IN>){
	chop;
	if ( $_ eq ":" ) { last; }
	if (/colors=([0-9]+)/) { # How many colors ?
	    $colors = $1;
	}
	if (/columns=([0-9]+)/) { # Width
	    $columns = $1;
	}
	if (/rows=([0-9]+)/) { # Height
	    $rows = $1;
	}
    }

    $pixels = $rows * $columns;

    read(IN, $colormap, $colors*3);

# Make color translation table
    for($i=0; $i<$colors; $i++){
	$rgb = substr($colormap, $i * 3, 3); 
	# and which color id in the sample colormap ?
	$trans[$i] = -1;
	for($j=0; $j<$samplecolors; $j++){ # Yes we know the size
	    if ( $sample[$j] eq $rgb ){
		$trans[$i] = $j;
		last;
	    }
	}
	if($trans[$i] == -1){ die "not mogrified"; }
    }

#### OK, We have now the translation table. Now convert !!!

    open(OUT, "> $filebody.raw");
    read(IN, $buffer, $pixels);
    close IN;
    for($i=0; $i<$pixels; $i++){ # Yes we know the size
	$c = ord(substr($buffer, $i, 1));
	if($c >= $colors){
	    die "ERROR";
	}
	printf OUT "%c", $trans[$c];
    }
    close OUT;

#### Last delete temporary files.
    unlink ("$filebody.miff");
    printf STDERR "done.\n";
}

#### Finally delete pallete file.
#unlink ("colorsample.miff");
