# numbers the entities and brush in a map file
# Version 2.0 by Zoner
#
# This file is a script, which requires a version of Perl to be installed so it may function.
#
# A Windows version of Perl can be obtained at http://www.activestate.com
#

sub Usage
{
    print STDOUT <<__FOO__
numberbrush.pl Usage:

perl dumpbrush.pl <mapname>

__FOO__
;
    exit 0;
}

$state = 0;
@states = ('null', 'Entity ', 'Brush', 'null2');
@total = (0, 0, 0, 0);

sub main
{
    $_ = $ARGV[0];
    if (($ARGV[0] eq "") || (/(\?|help)/i))
    {
        Usage();
    }

    local $file = $ARGV[0];
    local $i = 0;

    $file =~ s/\.map//i;

    $old = "$file.map";
    $new = "$file.tmp.$$";
    $bak = "$file.bak";

    unlink $bak;

    open(OLD, "< $old")         or die "can't open $old: $!";
    open(NEW, "> $new")         or die "can't open $new: $!";

    while (<OLD>)
    {
        if (/{\s/)
        {
            $state++;
            
            s/{/{ \/\/ @states[$state] $total[$state]/i;

            $total[$state]++;
        }
        elsif (/}\s/)
        {
            $total[$state+1] = 0;
            $state--;
        }
        print NEW $_            or die "can't write to $new: $!";
    }

    close(OLD)                  or die "can't close $old: $!";
    close(NEW)                  or die "can't close $new: $!";


    rename($old, $bak)          or die "can't rename $old to $bak: $!";
    rename($new, $old)          or die "can't rename $new to $old: $!";
}

&main;
