#! /usr/bin/perl

# Fix output of disassemble.pl for SWITCHON.

#012345678901234567890123456789012345678901234567890123456789
#      LDN   4  S0057                    [ 12478 -7339366 "MULT"
#      LDX   0  230(3)                   [ 12598 12518

# First pass - find switch targets

my %LABEL;

while (<>) {
	my $addr = substr ($_, 42, 5);

	if (/^(\w{5})/) {
		$LABEL {$addr} = $1;
	}

	if (/EXIT  4  0/) {
		while (<>) {
			last if (/^\w+/);
			my $content = substr ($_, 48, 5);
			unless ($LABEL{$content}) {
				$LABEL{$content} = 'C' . substr ($content,1);
			}
		}
	}
}

# Second pass, add appropriate labels and fix jump table

seek STDIN, 0, 0;

while (<>) {
	my $addr = substr ($_, 42, 5);
	if ($LABEL{$addr}) {
		substr ($_, 0, 5) = $LABEL{$addr};
	}

	print;

	if (/EXIT  4  0/) {
		while (<>) {
			if (/^\w+/) {
				print;
				last;
			}
			my $content = substr ($_, 48, 5);
			print "               /", 
				$LABEL{$content} // '-1', "\n";
		}
	}
}
