#!/map/sys/bin/perl
#
# add-csg-cover.pl
# 
# Andy Shaw 
# Tue Jun 11 20:06:02 EDT 1996
# 
# This is based on RPaul's add-coversheet command for Emacs.
#
#    add-csg-cover.pl <cover-file.ps> <main-file.ps>
#
# This outputs to standard out ... 
#

$version = "2.1";
$insert_blank_page_p = 1;

$EPS_magic = "%* -------------------------EPSCapsule.ps ------------------------------------
%* This element provides the capsulization code for including .eps files
%* in a document.
%*
%*	Usage:	BeginEPSFile
%*				<--- .eps code goes in here
%*		EndEPSFile
%*
%* The code sets the graphics state to its default for the .eps file. It then
%* returns the graphics state to its original state for the importing code.

/BeginEPSFile {
  /EPSSave save def		% Capture a copy of the current state
  /DictCount countdictstack def % Remember how many dictionaries there are
  /OpnCount count 1 sub def	% Remember the size of the operand stack
  userdict begin		% Make sure userdict is the current dictionary
  0 setgray			% Establish the default graphics state
  0 setlinecap
  1 setlinewidth
  0 setlinejoin
  10 setmiterlimit 
  [] 0 setdash
  newpath
%%  /showpage {} def		% Turn off the showpage command
} bind def


/EndEPSFile {
  count OpnCount sub {pop} repeat 	   % Remove extraneous stack items
  countdictstack DictCount sub{end} repeat % As well as extra dictionaries
  EPSSave restore			   % Restore the original state
} bind def
";

sub output_cover {
    local($coverfile, $n_cover_pages) = @_;
    
    print "%%Page: 0 1\n";
    print "%%Add-Coversheet: Version $version\n";
    print "%%Cover: $coverfile\n";
    print $EPS_magic;
    print "BeginEPSFile\n";
    # Stick the cover in here, removing %%EOF, and modifying %%Page
    while ($line = <COVERFILE>) {
	unless (($line =~ /^%%EOF/) || ($line =~ /^%%Page:/)) {
	    print $line;
	} 
    }
    # Stick in a blank page if necessary
    if ($insert_blank_page_p) {
	print "%%Page: 0 ", $n_cover_pages+1, "\nshowpage\n";
    }
    print "EndEPSFile\n";
}

sub main {
    local($coverfile, $mainfile) = @_;
    local($n_cover_pages) = split(" ", `grep "Page:" $coverfile | wc`);
    local($realpagenum) = $n_cover_pages + $insert_blank_page_p;
    local($pagenum) = 0;

    die "Can't handle cover sheets unless they have exactly 1 page"
	unless ($n_cover_pages == 1);

    open(MAINFILE,$mainfile);
    open(COVERFILE,$coverfile);
    #
    # Put in the header information of the main file
    #
    until (($line = <MAINFILE>) =~ /^%%EndSetup/) {
	print $line;
    }
    print $line;
    
    #
    # Next, encapsulate the cover, and print it
    #
    &output_cover($coverfile, $n_cover_pages);

    #
    # Finally, stick in the rest of the file, and adjust the page comments
    #
    while (<MAINFILE>) {
	if (/^%%Page:/) {
	    print "%%Page: ", ++$pagenum, " ", ++$realpagenum, "\n";
	} else {
	    print;
	}
    }
    close(MAINFILE);
    close(COVERFILE);
}

&main(@ARGV);
