#!/usr/bin/perl

# Copyright (C) 2004  Somebody
#
# $Id$

use strict;
use warnings;

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

my @errorCodes;
my @errorDescriptions;

my $data = "psErrorCodes.dat";
my $verbose;
my $help;

# 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;
open(my $dataFile, "<", $data) or die "Can not open data file $data";

print "Datafile:\n" if $verbose;
foreach my $record (<$dataFile>) {
    chomp $record;
    if ($record =~ /^\s*\#/) {
        print "C $record\n" if $verbose;
    } else {
        if ($record =~ /^\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 $record\n" if $verbose;
        }
    }
}
close($dataFile) or die "Can not close file $data";

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

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

    open(my $inFile, "<", $filename) or die "Failed to open input file";

    print "\nOutput File:\n" if $verbose;
    foreach my $record (<$inFile>) {

        chomp $record;
        push(@result, $record);
        if ($record =~ /^\s*\/\/~Start(.*)$/) {
            my $line = $1;
            for (my $n = 0; $n < $found; $n++) {
                $line =~ s/\$1/$errorCodes[$n]/g;
                $line =~ s/\$2/$errorDescriptions[$n]/g;
                $line =~ s/\$n/$n/g;
                push(@result, $line);
                print "$line\n" if $verbose;
            }

            my $break = 0;
            while (($break == 0) && (my $record = <$inFile>)) {
                if ($record =~ /^\s*\/\/~End/) {
                    $break = 1;
                }
            }
            chomp $record;
            push(@result, $record);
        }
    }

    close($inFile) or die "Can not close file $filename";

    open(my $outFile, ">", $filename) or die "Failed to overwrite input file";

    foreach my $res (@result) {
        print $outFile, "$res\n";
        print "$res\n" if $verbose;
    }

    close($outFile) or die "Can not close file $filename";

}
