#!/usr/bin/env perl
use strict;
$^W=1;

@ARGV == 1 or die "Syntax: macrocode-check <dtx file>\n";

my $infile = $ARGV[0];
my $pairs = 0;
my $state = 'end';
my $line = 0;

open(IN, $infile) or die "!!! Cannot open `$infile'!\n";

while(<IN>) {
    $line++;
     
    if (/^%([ ]*)\\(begin|end){macrocode}/) {
        my $length = length($1);
        my $cur = $2;

        if (length($1) != 4) {
            print "* Line $line: Wrong number of spaces ($length)!\n";
        }
        $state = ($state eq 'begin') ? 'end' : 'begin';
        if ($state ne $cur) {
            if ($state eq 'begin') {
                print "* Line $line: Missing '\\end{macrocode}!\n";
            }
            else {
                print "* Line $line: Missing '\\begin{macrocode}!\n";
            }
            # error recovery
            $state = $cur;
        }
    }
}
close(IN);

__END__
