#!/usr/bin/perl -- 

#
# bitmap2wxperl.pl
#
# Converts the Windows bitmap files given on the command line
# into executable wxPerl code.
#
# In addition to Wx, the module Compress::Zlib is required
# to execute the resulting code and recover the bitmaps.
#

use strict;
use warnings;
use Compress::Zlib;
use Wx 0.26 qw( wxBITMAP_TYPE_ANY );

die "usage: bmp2wxperl.pl <bitmap file(s)>\n" unless @ARGV;


# Check all the files first
my @bitmaps = ();
while (my $filename = shift @ARGV) {
    die "error: cannot read file \"$filename\"\n" unless ( -r $filename );
    my $bitmap = Wx::Bitmap->new( $filename, wxBITMAP_TYPE_ANY );
    die "error: cannot parse file \"$filename\"\n" unless ($bitmap and $bitmap->Ok);
    push @bitmaps, [$filename, $bitmap];
}


# Generate the code
print STDOUT "\n";
print STDOUT "use Wx 0.26;\n";
print STDOUT "use Compress::Zlib;\n\n\n";
print STDOUT "my %bitmaps = ();\n\n\n";

for (my $n = 0; @bitmaps; $n++) {
    my ($filename, $bitmap) = @{ shift @bitmaps };

    my $image  = $bitmap->ConvertToImage();
    my $data   = $image->GetData();
    my $height = $image->GetHeight();
    my $width  = $image->GetWidth();

    my $c_data = compress( $data, 9 );
    my $u_data = pack( 'u', $c_data );
    chop($u_data) if ( $u_data =~ m/\n$/ );

    print STDOUT <<"__END_OF_CODE__";

\$bitmaps{'$filename'} = Wx::Bitmap->new(
    Wx::Image->new( $width, $height,
        uncompress( unpack('u',
<<'__END_OF_IMAGE_${n}_DATA__'
$u_data
__END_OF_IMAGE_${n}_DATA__
        ))
    ),
);

__END_OF_CODE__

}

print STDOUT "\n\n#undef \%bitmaps;\n\n";

exit;


__END__


