#!/usr/bin/perl -w

use strict;

my $input_file = $ARGV[0] || "text.bmp";

###################################################

my $buffer = '';

open(F, $input_file) or die $!;
binmode(F);
while(my $temp = <F>){$buffer .= $temp;}
close(F);

# read header
# 0  2  UINT    bfType;
# 2  4  DWORD   bfSize;
# 6  2  UINT    bfReserved1;
# 8  2  UINT    bfReserved2;
# 10 4  DWORD   bfOffBits;

my $header = substr($buffer, 0, 14);
$buffer = substr($buffer, 14);

# read info
# 0  4  DWORD   biSize;
# 4  4  LONG    biWidth;
# 8  4  LONG    biHeight;
# 12 2  WORD    biPlanes;
# 14 2  WORD    biBitCount;
# 16 4  DWORD   biCompression;
# 20 4  DWORD   biSizeImage;
# 24 4  LONG    biXPelsPerMeter;
# 28 4  LONG    biYPelsPerMeter;
# 32 4  DWORD   biClrUsed;
# 36 4  DWORD   biClrImportant;

my $info = substr($buffer, 0, 40);
my $bits = substr($buffer, 40);

my ($bitcount) = unpack('v', substr($info, 14, 2));
my ($compress) = unpack('i', substr($info, 16, 4));
my ($size_x) = unpack('i', substr($info, 4, 4));
my ($size_y) = unpack('i', substr($info, 8, 4));

unless ($bitcount == 24){
	die "can only operate on 24 bit bitmaps (this is $bitcount bit)";
}
unless ($compress == 0){
	die "can only operate on uncompressed bitmaps";
}

####################################################


my $line_shift = $size_x * 3;
$line_shift += ($size_x % 4);


print "/*Bitmap-Size: $size_x x $size_y */\n";
print "/*            |       0      ||       1      ||       2      ||       3      ||       4      ||       5      ||       6      ||       7      ||       8      ||       9      ||       :      ||     (undef)  | */\n";

my $x;
my $y;

for ($y=$size_y-1; $y >= 0; $y--) {
	printf ("/* Row %2d */ \"",($size_y - $y - 1));
	for ($x=0; $x <=$size_x-1; $x=$x+8){
		my $_8pix = 0;
		for my $subx(0..7) {
			my $offset = (($x+$subx) * 3) + ($y * $line_shift);
			my $b = ord(substr($bits, $offset+0, 1));
			my $g = ord(substr($bits, $offset+1, 1));
			my $r = ord(substr($bits, $offset+2, 1));
			unless (($r == 255) && ($g == 255) && ($b == 255)){
				$_8pix += 2 ** (7 - $subx);
			}
				
		}
		print "\\x";
		print "0" if ($_8pix < 16);
		printf ("%x",$_8pix);
	}
	print "\"\n";
}
