#!/usr/local/bin/perl

#
#  This script will be used on a postscript file that contains many 
#  postscript files that are printing upsidedown.  This script reads 
#  in a postscript file until it gets past the comments, then inserts 
#  a comment and two commands that will rotate each page of the
#  postscript image 180 degrees.  
#
#  Output will be written to a file named by prepending an 'R' to the
#  input file name.
#
#  Dawn Tice   02/05/98
#


if ($#ARGV != 0) {
   die "Usage: add.rotate-ps.pl filename\n";
}

$postscript_file = $ARGV[0];
$new_file = "R$ARGV[0]";
$FOUND="false";

open(NEWFILE, "> $new_file") || die "Can't open the output file:$!\n";

open(DATA, "< $postscript_file") || die "Can't open postscript file:$!\n";
while(<DATA>){
   $line = $_;

   if(grep(/^%%EndComments/, $line) >=1){ 
      print NEWFILE $line;
      print NEWFILE "%% following two lines added to rotate image\n";
      print NEWFILE "612 792 translate\n";
      print NEWFILE "180 rotate\n";
   }
   elsif((grep(/^%%Page:/, $line) >=1) && ($FOUND eq 'false')){
      print NEWFILE $line;
      $FOUND="true";  #setting FOUND to be true
   } 
   elsif((grep(/^%%Page:/, $line) >=1) && ($FOUND eq 'true')){
      print NEWFILE "%% following two lines added to rotate image\n";
      print NEWFILE "612 792 translate\n";
      print NEWFILE "180 rotate\n";
      #print the rest of the postscript as-is.
      print NEWFILE $line;
   }
   else {
      #print the rest of the postscript as-is.
      print NEWFILE $line;
   }
}
close(NEWFILE);
close(DATA);
