#!/usr/bin/perl -w

die "Usage: gzimg.pl <format(RGBA|IA|I)> <bpp(16|8|4)> <SGI img file> <output c file> <image_var name> <gz_size_var name>\n" unless $#ARGV==5;

$format     = shift;
$bpp        = shift;
$in         = shift;
$out        = shift;
$gzimg_var  = shift;
$gzsize_var = shift;

sub write_short {
  my $f = shift;
  my $val = shift;
  printf $f "%c", (hex($val)&0xFF00) >> 8;
  printf $f "%c", (hex($val)&0x00FF);
}

##### write out image as binary chunck img.bin######
#$root = $ENV{ROOT};
`rgb2c -F -f $format -s $bpp -m texImg $in > img.h`;
open(OUT_DATA,">img.bin");
binmode(OUT_DATA);
open(IN_FILE, "<img.h");
while (<IN_FILE>) {
  if (/^\s+0x/) {
    @pixel = split /,\s*/;
    foreach $rgba (@pixel) {
      $rgba =~ s/^\s*//;
      write_short(OUT_DATA, $rgba); 
    }
  }
}
close IN_FILE;
close OUT_DATA;

##### write out gzipped chunck ######
`gzip -c -9 -n img.bin | dd bs=10 skip=1 of=img.gz`;

$idx=0;
open(INFILE, "<img.gz") or die "Can't open $in: $!";
binmode(INFILE);
open(OUTFILE, ">$out") or die "Can't open $out: $!";

$size = `stat img.gz`;
$size =~ /(.*Size: )(\d+)/;
$gz_size = $2;
printf OUTFILE "int %s = %s;\n", $gzsize_var, $gz_size;

printf OUTFILE "unsigned char %s[] __attribute__((aligned (16))) = { \n", $gzimg_var;
while( read(INFILE, $byte, 1) != 0 ) {
  printf OUTFILE "0x%02x, ", vec($byte, 0, 8);
  $idx++;
  if ($idx%80==0) {
      printf OUTFILE "\n";
  }
}
printf OUTFILE "};\n";

close INFILE;
close OUTFILE;

`rm img.gz img.h img.bin`;
