#!/usr/bin/perl -w

die "Usage: gen5551.pl <input Photoshop RGB raw format> <output> \n" unless $#ARGV==1;

$in = shift;
$out = shift;

open(INFILE, "<$in") or die "Can't open $in: $!";
open(OUTFILE, ">$out") or die "Can't open $out: $!";

while( read(INFILE, $byte, 4) != 0 ) {
    $r = 31.0 / 255.0 * vec($byte, 0, 8);
    $g = 31.0 / 255.0 *vec($byte, 1, 8);
    $b = 31.0 / 255.0 *vec($byte, 2, 8);
    $a = 31.0 / 255.0 *vec($byte, 3, 8);

    if ( $a > 0 )
    {
        $rgb = ($r<<11 & 0xf800) | ($g<<6 & 0x07c0) | ($b<<1 & 0x003e) | 1;
    }
    else
    {
        $rgb = ($r<<11 & 0xf800) | ($g<<6 & 0x07c0) | ($b<<1 & 0x003e) | 0;
    }

#    printf ( "%d, ", $rgb >> 8);
 #   printf ("%d, ", $rgb & 255);

    syswrite( OUTFILE, (pack("C",($rgb>>8)  ) ), 1 );
    syswrite( OUTFILE, (pack("C",($rgb&255) ) ), 1 );
}
close INFILE;
close OUTFILE;
