#!/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,
    "outfile=s"  => \$outputfile,
    "verbose" => \$verbose,
    "help"    => \$help
	   )  or exit(1);

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

if(defined($outputfile)) {
   if (@ARGV > 1) {
      die "You may only specify one input filename if you use --outfile\n";
   }
}

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);

    if (defined($outputfile)) {
       $ofile = $outputfile;
    } else {
       $ofile = $filename;
    }
    die "Failed to overwrite input file"
	if !open( OUTFILE, ">", $ofile );

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

    close(OUTFILE);

}
