#!/usr/bin/perl -w

#######################################################################################
# xbm2crw 0.2a - A converter for xbm to casio raw files to print with pegg
# (C)2004 Daniel Amkreutz
# compatibility & code enhancements by Alexander Reichl, March 2004
#
#                                                       Many Thanks
#
#        Only 1Bit Black&White XBMs with a size of 64x512 (wxh) are valid !!!
#
#        This program is distributed in the hope that it will be useful,
#        but WITHOUT ANY WARRANTY; without even the implied warranty of
#        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
#	You may use this program for whatever you want as long the above written
#	text remains.
#
#
#  Print the .crw file using pegg
#
#########################################################################################

my (@bitmap, $sXBM, $pos);

print "\nxbm2crw Version 0.2a (C) 2004 Daniel Amkreutz\n";
print "modified by Alexander Reichl, March 2004\n";

if (@ARGV == 0) {
  print "convert an black&white xbm file to a casio raw file\n\n";
  print "\tXBM format:\t1-Bit black&white\n";
  print "\t\t\twidth=64dots\n";
  print "\t\t\theight=512dots\n";
  print "\nERROR! Wrong number of Parameters.\n\n\tUsage: xbm2crw.pl XBMFILE\n\n";
  exit;
}

print "converting...\n";

open(IN, "<",$ARGV[0]) || die "Could not open file!\n\n";
sysread IN, $sXBM, -s IN;
close(IN);

$sXBM =~ s/\n//g;
$sXBM =~ s/\s//g;
$sXBM =~ s/^.*{//;
$sXBM =~ s/}.*$//;

$pos = 0;
foreach (split(/,/,$sXBM))
{
  if (length($_) != 4)
  {
    print "WARNING: read '$_' at image byte $pos, but expected hex value as for example '0xA2'.\n";
  }
  $bitmap[$pos++] = $_;
}

if ($pos != 4096)
{
  print "WARNING: read $pos image bytes from xbm, but expected 64x512 pixel / 8 pixel/byte = 4096 bytes.\n";
  print "Perhaps wrong dimension or color depth! Filling space with 0x00...\n\n";

  while ($pos < 4096)
  {
    $bitmap[$pos++] = "0x00";
} }

open(WRITE, ">".$ARGV[0].".crw") || die "Could not open file! \n\n";
binmode WRITE;
for (my $row=0; $row<=511; $row++)
{
  for(my $col=0; $col<=7; $col++)
  {
    print WRITE pack("C", hex($bitmap[4095 - $row*8 - 7 + $col]));
} }
close(WRITE);
