ROBOTestFrame/is_latex_balanced [ Functions ]

FUNCTION

Test the balance of a latex file. A latex file is balanced if every

     /begin{xxxx}

is ended with a

     /end{xxx}

INPUTS

RETURNS * 0 -- file is not balanced * 1 -- file is balanced

SOURCE

sub is_latex_balanced {
    my $path = shift;
    my @stack;
    local( $/ ) ;
    my $file = IO::File->new("<$path") or die "$path : $!";
    my $string = <$file>;
    $file->close();

    while ( $string =~ m/(begin|end)\{([^}]+)\}/g ) {
        my $b_e  = $1;  # begin or end
        my $kind = $2;  # document, or equation, or ...
        if ( $b_e eq "begin" ) {
            push( @stack, $kind );
        } else {
            if ( pop( @stack ) eq $kind ) {
                # OK.  begin and end matches.
            } else {
                # Not OK!  
                #   begin{ something }
                # followed by 
                #   end{ something else }
                return 0;  # Failure.
            }

        }
    }
    if ( scalar( @stack ) ) {
        # there are items left!
        return 0; # Not OK.
    }
    return 1;  # OK!
}