#!/usr/bin/perl -w
#
#    Copyright (c) 2009 by Michal Hucik <http://www.ordoz.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    MZ-800 Unicard 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.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with MZ-800 Unicard; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

use strict;

my $FILENAME = "setup";

open ( "MZF", "<", $FILENAME.".mzf" );
open ( "MZQ", ">", $FILENAME.".mzq" );

my $filesize = -s $FILENAME.".mzf";
$filesize -= 0x80; # odecteme header

print ( MZQ chr(0x00) . chr(0x16) x 2 . chr(0xa5) );
print ( MZQ chr(0x02) );
print ( MZQ "CRC" );
print ( MZQ chr(0x00) . chr(0x16) x 2 . chr(0xa5) );
print ( MZQ chr(0x00) );
print ( MZQ chr(0x40) . chr(0x00) );

# prcist a zapsat 0x40 B header
for ( my $i = 0; $i <= 0x3d; $i++ ) {
  my $c = getc ( MZF );
  if ( $i == 18 ) { print ( MZQ chr(0x0d) x 2 ); }; # QD ma o 2 B delsi jmeno souboru?
  print ( MZQ $c );
};

print ( MZQ "CRC" );
print ( MZQ chr(0x00) . chr(0x16) x 2 . chr(0xa5) );
print ( MZQ chr(0x05) ); # podle dokumentace tu ma byt 0x01

my $size_l = $filesize - ( int ( $filesize / 0x100 ) * 0x100);
my $size_h = int ( $filesize / 0x100 );
print ( MZQ  chr ( $size_l ) . chr ( $size_h ) );

# udelame seek za header
for ( my $i = 0; $i <= 0x41; $i++ ) {
  my $c = getc ( MZF );
};

while ( ! eof ( MZF ) ) {
  my $c = getc ( MZF );
  print ( MZQ $c );
};
print ( MZQ "CRC" );

# na konec image kaslem je to zbytecne plytvani mistem ;)

