#!/usr/bin/perl -w

my $infilename = shift or die "Usage: $0 FILENAME\n";

open(my $FILE, $infilename) or die $!;
binmode($FILE);

my $max=8192;

# read file to $ifub
for ($i=0;$i<$max;$i++) {
   read($FILE, my $byte, 1);
   $ibuf[$i]=ord( $byte);
};

$crc=0;

#calc CRC
for ($i=0;$i<$max;$i++) {
    $crc += $ibuf[$i];
    $crc &= 0xff;
};

printf ("CRC=0x%02x",$crc);
if ($crc == 0) {
   printf (" OK! Exitting...\n");
   exit 0;
};
my $newcrc=(0x100 - $crc) & 0xff;
printf (" WRONG! Injecting code 0x%02x at 0x%04x...\n",$newcrc,$max-1);
$ibuf[$max-1]=$newcrc;

close $FILE;
printf ("\n Overwriting $infilename..\n");
open(my $OUT, '>:raw', $infilename) or die $!;

# write buffer
for ($i=0;$i<$max;$i++) {
   print $OUT pack('C', $ibuf[$i] ) ;
}

close $OUT;

