#!/usr/local/bin/perl

# ADDLOAD -- Add specified loadfile keywords

use strict;
use FileHandle;

# The change hash contains the changed keywords, their values, 
# and their locations

my %change = (
	      OPUS_FLAG => {
			    value => 'Y',
			    location => 'header',
			   },
 	      
 	      COMPARISON_FILE => {
				  oldval => ',.*$',
				  value => '',
				  location => 'header',
				 },
 	      
  	      CHANGE_LEVEL => {
 			       value => 'severe',
 			       location => 'row',
 			      },
 	      
 	      COMMENT => {
 			  value => 'Redeliver with new filename',
 			  location => 'both',
 			 },
 	      
	     );

foreach my $file (@ARGV) {
    # The old switcheroo

    my $oldfile = "$file~";
    rename ($file, $oldfile);

    my $old = FileHandle->new ($oldfile, 'r');
    my $new = FileHandle->new ($file, 'w');

    # Flags used in parsing

    my $location = 'header';
    my $hascomment = 0;
    my $comment;
    my %found;
    my $data;

    while (<$old>) {
	my ($name, $value) = /^(\S+)[ \t=]*(.*)/s;

	if ($name =~ /^END(HEADER|ROW)/) {
	    # End of section, add missing keywords

	    while (($name, $data) = each %change) {
		print $new "$name = $data->{value}\n" 
		  if $data->{location} eq $location && ! exists $found{$name};
	    }

	    # Print the cached comment

	    print $new "COMMENT = $comment" if $hascomment;

	    # Update flags used in parse

	    $location = 'row' if $1 eq 'HEADER';
	    $hascomment = 0;
	    undef $comment;
	    undef %found;

	} elsif ($hascomment) {
	    # Add line as a continuation of comment

	    $comment .= $_;

	} elsif (exists $change{$name}) {
	    # Update keyword that is marked for changing

	    if ($change{$name}->{location} eq $location ||
		$change{$name}->{location} eq 'both') {

		if (exists $change{$name}->{oldval}) {
		    $value =~ 
		      s/$change{$name}->{oldval}/$change{$name}->{value}/;

		} elsif ($value =~ /^\s*$/) {
		    $value = "$change{$name}->{value}\n";
		}

		$_ = "$name = $value"; 
	    }

	    # Mark it as found

	    $found{$name} = 1;
	}

	# Cache comment until end of section

	if ($name eq 'COMMENT') {
	    $comment = $value;
	    $hascomment = 1;
	}

	# All lines in original file get printed except for cached comment

	print $new $_ unless $hascomment;
    }

    # Close files

    $old->close ();
    $new->close ();

    # Delete original if you are brave, comment out if you are not

    unlink ($oldfile);
}




