#!/usr/bin/perl

sub usage {
    print "Usage: bin2h file.bin width\n";
    print "Creates file.h\n";
    exit(1);
}

usage() unless @ARGV == 2;

$ifnam= shift @ARGV;
$ofnam= $ifnam;
usage() unless $ofnam =~ s/\.bin$/\.h/;
$name= $ifnam;
$name =~ s/\.bin$//;
$name =~ s|.*/||g;

$wid= shift @ARGV;

die "Can't open file: $ifnam"
    unless open IN, "<$ifnam";

$/ = undef;
$data= <IN>;

die "Read error on file: $ifnam"
    unless close IN;

@data= unpack("C*", $data);

$len= 0 + @data;
$hgt= int($len / 2 / $wid);

print "Width $wid, length $len, height $hgt\n";

die "File does not contain a whole number of lines -- is the width wrong?"
    unless $wid * $hgt * 2 == $len;

die "Can't open output file: $ofnam"
    unless open OUT, ">$ofnam";

print OUT "unsigned char ${name}_data[]= {\n";
print OUT "  $wid, $hgt,\n";

for (1..$hgt) {
    print OUT "  ";
    for (1..$wid) {
	print OUT shift(@data), ",";
	print OUT shift(@data), ",";
    }
    print OUT "\n";
}

print OUT "};\n";

die "Error writing file: $ofnam"
    unless close OUT;

exit 0;



