#!/usr/local/bin/perl -w

# coloroverlay.pl
# overlays multiple .ps (PostScript) files in progressive colors
# jonathan sheehan 4-25-01

# should fix: output to sdtout, add -outfile option
#           : should accept colors as arguments?
# Make sure you're in a directory you can write into
# These RGB values go from 0-1

@initialcolor = (1, 0.3, 0.3);
@finalcolor   = (0.2, 0, 0.5);
$numfiles     = ($#ARGV + 1);
$numsteps     = ($numfiles - 1);
$outfile      = "overlayOutput.ps";

sub StripNColor
{
	my ( $infile, $R, $G, $B ) = @_;
	if ( $infile eq $outfile ){
		print " or, rather, overwriting $outfile...\n";
		return;
	}
	open( IN, "$infile" ) || die "Couldn't read from $infile.\n";
	open( OUT, ">>$outfile" ) || die "Couldn't write to $outfile.\n";
	until ( <IN> =~ /EndPageSetup/ ){};
	while ( <IN>  ) {
		if (/showpage/) {
			last;
		}
		s/^.*(set(gray|rgbcolor))/$R $G $B setrgbcolor/;
		print OUT $_;
	}
}

sub WriteHeader
{
	my ( $infile ) = $_[0];
	open ( IN, "$infile" ) || die "Couldn't read from $infile.\n";
	open ( OUT, ">$outfile" ) || die "Couldn't write to $outfile.\n";
	while ( <IN> ){
		print OUT $_;
		if (/EndPageSetup/) {
			last;
		}
	}
	close (IN);
	close (OUT);
}

sub usage
{
	die<<EOF;
>>>usage:
	coloroverlay.pl file1.ps file2.ps [...fileX.ps]
EOF
}

################################################# 
#main
#################################################

if ( $numfiles < 2 ) {
	usage();
};

$RED   = $initred   = $initialcolor[0];
$GREEN = $initgreen = $initialcolor[1];
$BLUE  = $initblue  = $initialcolor[2];

$finalred   = $finalcolor[0];
$finalgreen = $finalcolor[1];
$finalblue  = $finalcolor[2];

WriteHeader ( $ARGV[0] );
foreach $file ( 0..$#ARGV ) {
	print "Processing ".$ARGV[ $file ]."...\n";
	StripNColor( $ARGV[ $file ], $RED, $GREEN, $BLUE );
	$RED -= ($initred - $finalred)/$numsteps;
	$GREEN -= ($initgreen - $finalgreen)/$numsteps;
	$BLUE -= ($initblue - $finalblue)/$numsteps;
};
print OUT "showpage\n";
print OUT "%%EOF\n";
close OUT;

