#!/packages/bin/perl
#
# Copyright (c) 1995 Xerox Corporation.  All Rights Reserved.
#
# Permission to use, copy, modify  and  distribute  without  charge
# this  software,  documentation, images, etc. is granted, provided
# that this copyright and the author's name is retained.
#
# A fee may be charged for this program ONLY to recover  costs  for
# distribution  (i.e.  media costs).  No profit can be made on this
# program.
#
# The author assumes no responsibility for  disasters  (natural  or
# otherwise) as a consequence of use of this software.
#
# Adam Stein (adam@iset.scan.mc.xerox.com)
#

#
# NOTE:
#
# You will probably have to change the path to the perl program in line 1
# for this program to work on your system.
#
# This was written using Perl v4.036.
#

# Maximum length of output from a command.
$MAXLEN = 1024;

# Parse argument
($subfile = shift) || die "Usage: $0 filename\n";

# Parse substitution file
%fields = &getfields($subfile);

# Filter STDIN to do substitutions
while (<>) {
  while (($key,$value) = each %fields) {
    s/$key/$value/g;
  }

  print $_;
}

exit 0;

# Read in and parse substitution file
sub getfields
{
  local($subfile) = @_;
  local($HANDLE);

  # Open substitution file
  open($HANDLE,$subfile) || die "$0: $subfile: $!\n";

  # Parse file
  while(<$HANDLE>) {
    if (/^([^#\n][^\t ]*)[\t ]*(.*)$/) {
      $key = $1;

      # Run command if one is given in backquotes (`)
      if ($2 =~ /`([^`]*)`/) {
	open($CMD,"$1|");
	read($CMD,$value,$MAXLEN);
	chop $value;
	close($CMD);
      } else {
	       $value = $2;
	     }

      $subs{$key} = $value;
    } else {
             # Ignore comment and blank lines
             next;
	   }
  }

  close($HANDLE);

  %subs
}

