#!/usr/bin/perl
#
# Congen copyrighter -- puts new copyright notice into CONGEN.

$copyright = <<EOF;
Copyright \@copyright{} 1987-1988 Robert E. Bruccoleri

Copyright \@copyright{} 1990-1997 Bristol-Myers Squibb Company

Please see the file, COPYRIGHT, for the copyright notice and
terms and conditions for use of this file.
EOF

@copyright = split("\n", $copyright);

while (@ARGV) {
    $file = shift @ARGV;
    if ((-f $file) && ($file !~ /^(copyrighter|COPYRIGHT|congen\.texinfo|foo\..*)$/)) {
	open (IN, "<$file") || die "Unable to open $file: " . $! . "\n";
	print "====> $file\n";
	$prefix = "";
	@lines = ();
	while (<IN>) {
	    if (/(Copyright.*Bruccoleri)|(Copyright.*Squibb)/ .. /Princeton, NJ 08543-4000 for more information\./) {
		push (@lines, $_);
		chop;
		if (/^(.*)((Copyright.*Bruccoleri)|(Copyright.*Squibb))/) {
		    $prefix = $1;
		}
		elsif (substr($_, 0, length($prefix)) ne $prefix) {
		    if ((length($_) < length($prefix)) &&
			(substr($prefix, 0, length($_)) eq $_)) { }
		    else {
			print "Inconsistent prefix: ", $_, "\n";
		    }
		}
	    }
	}
	close IN;
 	if ($#lines >= 0) {
 	    &system_with_check("cp $file $file.bak");
 	    open (IN, "<${file}.bak") || die "Unable to open ${file}.bak: " . $! . "\n";
 	    open (OUT, ">$file") || die "Unable to open $file: " . $! . "\n";
 	    $state = "START";
 	    while (<IN>) {
 		if ($state eq "END1") {
 		    $state = "END";
 		}
 		elsif (/(Copyright.*Bruccoleri)|(Copyright.*Squibb)/) {
 		    if ($state eq "START") {
 			foreach $line (@copyright) {
 			    print OUT $prefix . $line . "\n";
 			}
 		    }
 		    $state = "MIDDLE";
 		}
 		elsif (/Princeton, NJ 08543-4000 for more information\./) {
 		    $state = "END1";
 		}
 		if (($state eq "START") || ($state eq "END")) {
 		    print OUT $_;
 		}
 	    }
 	    close IN;
 	    close OUT;
 	    if ($state ne "END") {
 		print "Complete copyright notice not found. Reverting to previous version.\n";
 		&system_with_check("cp $file.bak $file");
 	    }
 	}
    }
}

sub system_with_check {
    # Issue a system command, but check the result.
    
    local($command) = @_;
    local($status);

    $status = system("$command");
    if ($status != 0) {
	printf STDERR "Shell command: $command returned %d error code.\n", $status;
	exit 1;
    }
}
