#!/usr/bin/perl
#
# Perl script to patch CLX binaries
#
# Last change: DL6RAI Tue Feb 23 21:09:37 GMT 1999

if ( $#ARGV < 2 ) {
	print "Usage: $0 <filename> <address> <byte> [<byte>...]\n";
	exit 1;
}

$file = $ARGV[0];

if ( ! -e $file ) {
	print "$0: file $file does not exist.\n";
	exit 1;
}

if ( ! -w $file ) {
	print "$0: file $file is not writable.\n";
	exit 1;
}

eval "\$addr=$ARGV[1]";
print "Patching file $file\n"; 

@bytes = splice(@ARGV,2); # the rest

foreach $b (@bytes) {
	eval "\$byte = $b";
	$b = $byte;
}

open(BIN,"+<$file") || die "Cannot open $file\n";
seek(BIN,$addr,0) || die "Cannot seek address $addr in file $file\n";

# reading
foreach ($i=0;$i<=$#bytes;$i++) {
	$p = tell(BIN);
	read(BIN,$old,1);
	$old = unpack('C',$old);
	printf("0x%08x (%08d):    0x%02x ---> 0x%02x\n",
		$p,$p,$old,$bytes[$i]);
}

# writing
seek(BIN,$addr,0) || die "Cannot seek address $addr in file $file\n";
foreach ($i=0;$i<=$#bytes;$i++) {
	 print BIN pack('C',$bytes[$i]);
}

close(BIN);
