#!/usr/bin/perl -w 

sub write_raw {
    my ($format, $out, $size, $infile) = @_;
    $out =~ s/\.tex|\.c|\.h/\.raw/; 
    printf IDXFILE "%s\t\t",  $out;
    printf IDXFILE "%s\t", $format;
    printf IDXFILE "%s\n", $size;

    open(OUTFILE, ">$out");
    while (<$infile>) { 
        if (/^\s\d/) {
            @pixel = split /,\s*/; 
            foreach $rgba (@pixel) {
                $rgba =~ s/\s+//;
                SWITCH: {
                    if ($format eq "IA8") {
                        printf OUTFILE "%c", ((hex($rgba)&0xF0) >>4) * 255.0 / 15.0;
                        printf OUTFILE "%c", (hex($rgba)&0x0F) * 255.0 / 15.0; 
                        last SWITCH;
                    }
                    if ($format eq "RGBA16") {
                        printf OUTFILE "%c", ((hex($rgba)&0xF800) >>11) * 255.0 / 31.0;
                        printf OUTFILE "%c", ((hex($rgba)&0x07C0) >>6) * 255.0 / 31.0;
                        printf OUTFILE "%c", ((hex($rgba)&0x003E) >>1) * 255.0 / 31.0;
                        printf OUTFILE "%c", ((hex($rgba)&0x0001)==1) ? 255 : 0;  
                        last SWITCH;
                    }
                    if ($format eq "RGBA32") {
                        printf OUTFILE "%c", (hex($rgba)&0xFF000000) >> 24;
                        printf OUTFILE "%c", (hex($rgba)&0x00FF0000) >> 16;
                        printf OUTFILE "%c", (hex($rgba)&0x0000FF00) >> 8;
                        printf OUTFILE "%c", hex($rgba)&0x000000FF;
                        last SWITCH;
                    }
                }
            }
        }
    }
    close OUTFILE;
}

die "Usage: converts texture data files (ascii) to photoshop raw image files, outputs image attributes to file list.txt\n" unless $#ARGV>=0;
$idx = "list.txt";
open(IDXFILE, ">>$idx") or die "Can't open $idx: $!\n";

foreach $file (@ARGV) {
    open(INFILE, "< $file") or die "Can't open $file: $!\n";
    print $file, "\t";
    while (<INFILE>) {
        if (/(image size)\s*:\s*(\d+)\s*x\s*(\d+)\s*x\s*(\d+)/) {
            $size = $2."x".$3;
            print $size, "\n";
        }
        next if (!/(format)*(RGBA32|RGBA16|IA8)/);
        write_raw($2, $file, $size, INFILE);
    }
    close INFILE;
}

close IDXFILE;

