#!/usr/bin/perl
# Substitute EXPRESSION in chfile with content of wfile.
# USAGE: substfile expr chfile wfile
# Changes:
#	2002-03-23 Ola Lundqvist <opal@debian.org>
#		Wrote it.

$expr   = shift @ARGV;
$chfile = shift @ARGV;
$wfile  = shift @ARGV;
print("Substituting $expr in $chfile with content of $wfile.\n");
$expr =~ s/\%/\\\%/g;

if (open (CF, "$chfile")) {
    my @lines = <CF>;
    close (CF);
    undef $/;
    $wcont = "";
    if (open (WF, "$wfile")) {
	$wcont  = <WF>;
	close (WF);
    }
    else {
	print ("Unable to open $wfile for reading.\n");
    }
    if (open (CF, ">$chfile")) {
	foreach my $l (@lines) {
	    if ($l =~ /\s*$expr\s*/) {
		print CF $wcont;
		print "C";
	    }
	    else {
		print CF $l;
		print ".";
	    }
	}
	close (CF);
	print ("\n");
    }
    else {
	print ("Unable to open $chfile for writing.\n");
    }
}
else {
    print ("Unable to open $chfile for reading.\n");
}
