use strict;
@ARGV == 4 or die "Usage: perl xexcut.pl INPUT.XEX AAAA BBBB OUTPUT.RAW\n";
my ($infile, $cutfirst, $cutlast, $outfile) = @ARGV;
open F, $infile and binmode F or die "$infile: $!\n";
my $memory = v0 x 65536;
while (1) {
	my $first;
	do {
		read(F, $first, 2) == 2 or last;
		$first = unpack 'v', $first;
	} while $first == 0xffff;
	my $last;
	read(F, $last, 2) == 2 or last;
	$last = unpack 'v', $last;
	printf "%04x-%04x\n", $first, $last;
	my $block;
	read F, $block, $last - $first + 1 & 0xffff;
	substr $memory, $first, length($block), $block;
}
open F, ">$outfile" and binmode F or die "$outfile: $!\n";
#print F $memory;
print F substr $memory, hex($cutfirst), hex($cutlast) - hex($cutfirst) + 1;
