#!/usr/bin/perl
use strict ;

my ($mapFH, $inFH, $outFH) ;
## Open the three files
{
    if ($#ARGV != 2) {      
	print STDERR "Wrong number of arguments\n" ;
	exit 1 ;
    }

    my $mapFile = $ARGV[0] ;
    my $inFile  = $ARGV[1] ;
    my $outFile = $ARGV[2] ;

    my $badFiles = 0 ;

    if (!open($mapFH, $mapFile)) {
	print STDERR "Unable to open map file ${mapFile}\n" ;
	$badFiles=1 ;
    }

    if (!open($inFH, $inFile)) {
	print STDERR "Unable to open input file ${inFile}\n" ;
	$badFiles=1 ;
    }

    if (!open($outFH, ">${outFile}")) {
	print STDERR "Unable to open input file ${inFile}\n" ;
	$badFiles=1 ;
    }

    if ($badFiles) {
	exit(1) ;
    }
}
# active variables at this point
#   Three file handles: $mapFH, $inFH, $outFH

my %subwordMap = ( ) ;
## Create the word map index
## Index will be stored in %subwordMap -- a hash of arrays
{
    while(my $inputLine = <$mapFH>) { 
	my($varName, $subValsAsString, $oper) ;
	chomp($inputLine) ;
	if (!(($varName, $oper, $subValsAsString)
	      = ($inputLine =~ /^s*[*](\w+)[*]\s*([+]?[=])\s*(\S.*)$/))) {
	    print STDERR "\"${inputLine}\" is invalid.\n" ;
	    exit 1 ;
	}
	if (exists($subwordMap{$varName})) {
	    if ($oper eq "=") {
		print STDERR "Trying to redefine *${varName}*\n" ;
		exit 1 ;
	    }
	} else {
	    if ($oper eq "+=") {
		print STDERR "Trying to add to undefined *${varName}*\n" ;
		exit 1 ;
	    }
	    $subwordMap{$varName} = [ ] ;
	}
	$subValsAsString =~ s/\s+$// ;
	my @words = split(/\s*,\s*/, $subValsAsString) ;
	foreach my $word (@words) {
	    push(@{$subwordMap{$varName}}, $word) ;
	}
    }
    close($mapFH) ;
}
# active variables at this point
#   Two file handles: $inFH, $outFH
#   Hash of arrays:  %subwordMap

{
    my ($inputLine, $i) ;
    while($inputLine = <$inFH>) {
	my @words = split(/[*]/, $inputLine) ;
	for ($i=0; $i<$#words; $i+=2) {
	    print $outFH $words[$i] ;
	    my @mapWords = @{$subwordMap{$words[$i+1]}} ;
	    if (defined @mapWords) {
		# Take out a word and rotate the map
		my $firstWord = $mapWords[0] ;
		shift @mapWords ;
		push @mapWords, $firstWord ;
		$subwordMap{$words[$i+1]} = \@mapWords ;
		print $outFH $firstWord ;
	    } else {
		print $outFH '*' ;
	    }
	}
	if ($i == $#words) {
	    print $outFH $words[$i] ;
	}
    }
    close($inFH) ;
    close($outFH) ;
}
