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

if($#ARGV<0) {
    ## No arguments supplied.  
    ## Assume input comes from stdin.  Send output to stdout.
    ## Read in stdin to a temp file so that it can be processed.
    $tmppsfile="/tmp/psfbb$$.ps";
    open(NEW, ">$tmppsfile");
    while(<>){
	print NEW;
    }
    close(NEW);
    $psfile = $tmppsfile;
    $newfile = "-";

} elsif ($#ARGV==0) {
    ## One argument supplied: name of input file.  Send output to stdout.
    $psfile = $ARGV[0];
    #$newfile = $psfile;
    $newfile = "-";
} else {
    ## We have two arguments: name of input file and name of output file.
    $psfile = $ARGV[0];
    $newfile = $ARGV[1];
}


#$psfile = "a.ps";
#$newfile = "n.ps";

## Run gs to find the proper bounding box.  The output is normally two
## lines long, one with `BoundingBox' and one with `HiResBoundingBox'.
$op = `gs -dBATCH -dNOPAUSE -q -sDEVICE=bbox $psfile 2>&1`;

##print STDERR"output from gs is $op";

@bblines = split /\n/, $op;
##print STDERR "bb is $bblines[0]";


open(IN, "$psfile");
open(OUT, ">$newfile");

## Copy the input file to stdout, just changing the bounding box on the way.
## Note, if the input file doesn't have the `BoundingBox' comment, we 
## don't replace it with the new one!!!
while(<IN>){

    if (/^%%BoundingBox:/) {
	print OUT "$bblines[0]\n";
    } else {
	print OUT;
    }
}

	

## Delete temporary files.   
if ($tmppsfile) {unlink $tmppsfile;}

	

########################################################


__END__

=head1 NAME

psfbb - Fix the bounding box within a postscript file

=head1 SYNOPSIS

psfbb <infile> <outfile>

=head1 DESCRIPTION

This script uses ghostscript (gs) to find the correct bounding box for
a file.  It then duplicates your file, but inserting the proper
bounding box along the way.

If no arguments are given, input is from stdin and output is sent to
stdout.  If one argument is given, it is assumed to be the output
file.  Output is sent to stdout.  If two arguments are given, arg 1 is
the input file and arg 2 is the output file.

=head1 OPTIONS

=head1 ENVIRONMENT

=head1 EXAMPLES


The following three commands all convert `file.ps' into `newfile.ps'.

psfbb < file.ps > newfile.ps

psfbb file.ps > newfile.ps

psfbb file.ps newfile.ps

=head1 FILES

=head1 AUTHOR

Stephen Eglen <stephen@anc.ed.ac.uk>

=head1 SEE ALSO

=head1 DIAGNOSTICS

=head1 BUGS

It assumes that your file has a bounding box, however faulty.

=cut
