#!/usr/bin/perl
#
# Copyright 2003  (c) European Southern Observatory
# License             GNU Public Licenes version 2.0 or higher
#
# Read control file and correct BoundingBox of eps files.  Also remove
# MIDAS/AGL clear page path instructions in start of file if any.
#
#  Usage: ./bbmod.pl file
#
#  where file contains one line for each eps file in the format e.g.
#
#      file.eps:%%BoundingBox: 153 153 456 344
#
#  which can be generated by the comand:  grep BoundingBox *eps
#
# P.Grosbol/ESO  2003-08-15
#--------------------------------------------
#  Read line by line of control file
while (<>) {
    s/:%%BoundingBox:/ /;
    ($file,$lx,$ly,$hx,$hy) = split;
    printf "Modify file >%s< to BB: %d %d %d %d\n",$file,$lx,$ly,$hx,$hy;
    &mod_eps;
}
#
#  modify individyal eps file
sub mod_eps {
    $file_bck = $file . ".bck";
    rename($file, $file_bck) || die "cannot rename file: $file/n";
    open(IN_EPS, "$file_bck") || die "cannot open file: $file_bck\n";
    open(OUT_EPS, ">$file") || die "cannot create file: $file\n";
    $bb_found = 1;       #  BoundingBox found
    $np_found = 1;       #  New path found
    $fp_found = 0;       #  Fill path found
    while (<IN_EPS>) {   #  read original eps file line by line
	if ($bb_found && /%%BoundingBox:\s+\d+\s+\d+\s+\d+\s+\d+/) {
	    printf "Found BB %s",$_;
	    $bb_found = 0;
	    printf OUT_EPS "%%%%BoundingBox: %d %d %d %d\n",$lx,$ly,$hx,$hy;
	} elsif ($np_found && /^n\s+1\s+1\s+moveto/) {
	    $np_found = 0;
	    $fp_found = 1;
	    $path = $_;
	} elsif ($fp_found) {
	    $path .= $_;
	    if (/closepath\s+fill/) {
		$np_found = 0;
		$fp_found = 0;
	    } elsif (/closepath/) {
		$np_found = 1;
		print OUT_EPS $path;
	    }
	} else {
	    print OUT_EPS $_;
	}
    }
    close(OUT_EPS);
    close(IN_EPS);
    unlink("$file_bck");
}
