#!/usr/local/bin/perl
#############################################################################
#  This scripts changes a postscript with twoup so that every other page
#  will no longer be printed upside down.
#
#  The postscript code was copied from the 'parr' program that came together
#  with the perl-reference guide by Johan Vromans.
#
#  Copyright (C) 1999 Dov Grobgeld <dov@imagic.weizmann.ac.il>
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
# 
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
# 
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
# 
#############################################################################

while ($ARGV[0] =~ /^-/) {
    $_ = shift;
    
    if (/^-mode/) {
        $mode = shift;
    }
    elsif (/^-tumble/) {
        $tumble++;
    }
    elsif (/^-simplex/) {
        $simplex++;
    }
    elsif (/-h(elp)?/) {
        print<<EOH
fixdt - insert tumble and duplex directives in a PostScript file

Syntax:
    fixtumble [-simplex] [-tumble] filename
    
Options:

       -simplex  Simplex printing. (Default is duplex)
       -tumble   Tumble pages.
EOH
;   exit;
    }
}

while(<>) {
     unless ($mode) {
        if (/dvips/) { $mode='dvips'; }
        elsif (/mpage/) { $mode='mpage'; }
        elsif (/Start of enscript\.pro/) { $mode='enscript'; }
        elsif (/pstops/) { $mode='pstops'; }
        elsif (/ditroff/) { $mode='reenc'; }
        elsif (($.==1000) || eof) { $mode='giveup'; last; }
    }
    else {
        if ($mode eq 'dvips') {
            last if /%%EndSetup/;
        }
        elsif ($mode eq 'mpage') {
            last if /^statusdict/;
        }
        elsif ($mode eq 'enscript') {
            last if /^%%EndProlog/;
        }
        elsif ($mode eq 'reenc') {
            last if /^\/reencsmalldict/;
        }
    }
    push(@P,$_);
}
die "Unable to determine format!\n" unless $mode;

if ($mode eq 'giveup') {
    # Insert in  first noncomment place
    $i=0;
    $p=shift(@P);
    (print $p), ($p=shift(@P)) until $p!~ /^%/;
    $_= $p.join("",@P) . $_;
}
else { print @P; }
print 'statusdict /setduplexmode known ' . 
      '{ statusdict begin true setduplexmode end } if',"\n" unless $simplex;
print 'statusdict /settumble known ' .
      '{ statusdict begin true settumble end } if',"\n" if $tumble;
print $_;

# Copy the rest of it
while (<>) {
    print;
}

