#!/usr/bin/perl
$MAGIC = "Xsheetnumber";

$where = "head";
$sheet = 1;
while (<>) {
	if (/^\$Sheet/) {
		$where = "sheet";
		$tmp = $_;
		$sheet++;
		next;
	}
	if ($where eq "head") {
		$head .= $_;
		next;
	}
	if ($where ne "sheet") {
		$tail .= $_;
		next;
	}
	if (/^\$EndSheet/) {
		$where = "outside";
		$tmp .= $_;

		die "file name not found" unless $tmp =~ /^F1\s+"([^"]+)"/ms;
		$file = $1;
		open(FILE, $file) || die "$file: $!";

		undef $explicit;
		while (<FILE>) {
			next unless /^Comment4\s+"$MAGIC=([1-9]\d*)"/;
			$explicit = $1;
			last;
		}
		close FILE;

		if (!defined $explicit) {
			warn "$file: sheet $sheet has no explicit tag\n";
			$explicit = $sheet;
		}
		die "$file: sheet number must be 2 or higher\n"
		    if $explicit < 2;
		die "$file: collision on number $explicit\n"
		    if defined $sorted[$explicit];
		$sorted[$explicit] = $tmp;
		$was[$explicit] = $sheet;
		next;
	}
	$tmp .= $_;
}

print $head;
for ($i = 2; $i <= $#sorted; $i++) {
	if (!defined $sorted[$i]) {
		warn "sheet #$i is missing in sequence\n";
		next;
	}
	warn "sheet $was[$i] is now $i\n" unless $was[$i] == $i;
	print $sorted[$i];
}
print $tail;
