#!/usr/bin/perl

# Provides functions for handling long command line options
use Getopt::Long;

my @ErrorCodes        = ();
my @ErrorDescriptions = ();

my $data = "psErrorCodes.dat";

# Assign variables based on the presence of command line options to the script
GetOptions(
    "data=s"  => \$data,
    "verbose" => \$verbose,
    "help"    => \$help
);

if ($help) {
    print "Usage: parseErrorCodes ", "[--data=$data] ", "[--help] ",
      "[--verbose] filename [filename ...]\n\n";
    exit(0);
}

print "Using data file '$data'\n" if $verbose;
unless ( open( DATAFILE, "<", $data ) ) {
    die "Can not open data file $data.";
}

print "Datafile:\n" if $verbose;
while (<DATAFILE>) {
    chop;
    if (/^\s*\#/) {
        print "C $_\n" if $verbose;
    }
    else {
        if (/^\s*(\w+)\s+([\%\w].*)/) {
            my $ErrorCode        = $1;
            my $ErrorDescription = $2;
            print "  $ErrorCode: '$ErrorDescription'\n" if $verbose;
            push( @ErrorCodes,        $ErrorCode );
            push( @ErrorDescriptions, $ErrorDescription );
        } else {
            print "I $_\n" if $verbose;
        }
    }
}
close(DATAFILE);

my $found = $#ErrorCodes + 1;
print "\nFound $found error codes.\n" if $verbose;

foreach (@ARGV) {
    my $filename = $_;
    my @result   = ();

    die "Failed to open input file '$filename'"
      if !open( INFILE, "<", $filename );

    print "\nOutput File:\n" if $verbose;
    while (<INFILE>) {
        chop;
        push( @result, $_ );
        if (/^\s*\/\/~Start(.*)$/) {
            $line = $1;
            for ( $n = 0 ; $n < $found ; $n++ ) {
                $_ = $line;
                s/\$1/$ErrorCodes[$n]/g;
                s/\$2/$ErrorDescriptions[$n]/g;
                s/\$n/$n/g;
                push( @result, $_ );
                print "$_\n" if $verbose;
            }

            $break = 0;
            while ( ( $break == 0 ) && ( $_ = <INFILE> ) ) {
                if (/^\s*\/\/~End/) {
                    $break = 1;
                }
            }
            chop;
            push( @result, $_ );
        }
    }

    close(INFILE);

    die "Failed to overwrite input file"
      if !open( OUTFILE, ">", $filename );

    foreach (@result) {
        print OUTFILE "$_\n";
        print "$_\n" if $verbose;
    }

    close(OUTFILE);

}
