#! /usr/bin/perl

# Extract all GLOBAL definitions from a BCPL source file

my $GLOBAL = 0;

# GET "NHEAD0"

# GLOBAL $( READN:69 $)

# GLOBAL $(
#            OPTION:125; PRINTING:126; STACKDEPTH:127
#            SEG:143; SEGMAX:144

extract ();

sub extract {

	while  (<>) {
		chomp;

		if (/^\s*GET\s*"([^"]+)"/) {
			local *GET;
			open GET, $1 . "SRC" or die "Can't open $1: $!\n";
			my $old = select GET;
			extract ();
			select $old;
		}

		if (/(^|\s+)GLOBAL(\s+|\$\(|$)/) {
			++$GLOBAL;
		}

		if ($GLOBAL) {
			for (split /;/) {
				if (/([A-Za-z0-9.]+)\s*:\s*(\d+)/) {
					# complicated because the same
					# global could have multiple names
					++$GLOBAL{$2}->{$1};
				}
			}
			if (/\$\)/) {
				$GLOBAL = 0;
			}
		}
	}
}

for (sort { $a <=> $b } keys %GLOBAL) {
	print $_, "\t", join (";", sort keys %{$GLOBAL{$_}}), "\n";
}
