#!/usr/bin/perl -w 

die "Usage: parse5551.pl <input>\n       converts RGBA16 texture files <input> to photoshop raw image files <input>.raw\n" unless $#ARGV>=0;

foreach $file (@ARGV) {
    open(INFILE, "< $file") or die "Can't open $file: $!\n";
    open(OUTFILE, "> $file.raw") or die "Can't open $file.raw: $!\n";
    while (<INFILE>) {
        if (/^\s*\d/) {
            @pixel = split /,\s*/;
            foreach $rgba (@pixel) {
                $rgba =~ s/\s+//;
                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;
            }
        }
    }
    close INFILE;
    close OUTFILE;
}
