#! /bin/sh
# -*- ksh -*-

# fixps --- fix as much as possible PS errors that break the psutils

# Copyright (c) 1988, 89, 90, 91, 92, 93 Miguel Santana
# Copyright (c) 1995, 96, 97, 98 Akim Demaille, Miguel Santana

# $Id: fixps.in,v 1.4 1998/04/02 20:34:10 demaille Exp $

# 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, 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, you can either send email to this
# program's maintainer or write to: The Free Software Foundation,
# Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA.

# Commentary:

# Author: Akim Demaille <demaille@inf.enst.fr>

# In the interest of general portability, some common bourne shell
# constructs were avoided because they weren't guaranteed to be available
# in some earlier implementations.  I've tried to make this program as
# portable as possible.  Welcome to unix, where the lowest common
# denominator is rapidly diminishing.
#
# Among the more interesting lossages I noticed with some bourne shells
# are:
#     * No shell functions.
#     * No `unset' builtin.
#     * `shift' cannot take a numeric argument, and signals an error if
#       there are no arguments to shift.

# Todo:
# Should be rewriten in perl.  It would help to handle
# (Begin|End)Document which allows several Trailers etc.

# Code:

# Minimal path.  It must be able to see the psutils.
PATH=/usr/local/bin:$PATH
export PATH

# Get the name of the program
program=`echo $0 | sed 's#.*/##g'`

# Local vars
debug=
file=
output=
tmpdir=/tmp/$program.$$
verbose=echo

# The version/usage strings
version="fixps 0.5 (a2ps 4.10.2)

Copyright (c) 1988, 89, 90, 91, 92, 93 Miguel Santana
Copyright (c) 1995, 96, 97, 98 Akim Demaille, Miguel Santana
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Written by <Akim.Demaille@inf.enst.fr> and <Miguel.Santana@st.com>
News, updates and documentation: visit http://www.inf.enst.fr/a2ps/"

usage="\
Usage: $program FILE
Tries to fix common PostScript problems that break postprocessing.

Options:
 -h, --help           display this help and exit
 -v, --version        display version information and exit
 -q, --quiet          don't print informational messages
 -o, --output=FILE    save result in FILE.  If FILE is \`-', send to stdout

Report bugs to <a2ps-bugs@inf.enst.fr>"

help="Try \`$program --help' for more information."

# Parse our command line options once, thoroughly.
while test $# -gt 0
do
  arg="$1"
  shift
  
  case "$arg" in
    -*=*) optarg=`echo "$arg" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
    *) optarg= ;;
  esac
  
  # If the previous option needs an argument, assign it.
  if test -n "$prevopt"; then
    optarg="$arg"
    arg="$prevopt="
    prevopt=
  fi
  
  # Have we seen a non-optional argument yet?
  case "$arg" in
    --help|-h)
      echo "$usage"
      exit 0
      ;;
    
    --version|-v)
      echo "$version"
      exit 0
      ;;
    
    -s|-q|--quiet|--silent) message=: ;;
    # Delay debugging so that options parsing does not appear
    -D|--debug) debug=: ;;
    
    --output|-o) prevopt="--output" ;;
    --output=*) 
      output=$optarg
      ;;
    
    -) # We are working with stdin
       nonopt="$nonopt $arg"
       ;;

    -*)
      case "$arg" in
        --*=* ) arg=`echo "$arg" | sed -e 's/=.*//'` ;;
      esac
      exec 1>&2
      echo "$program: Unknown or ambiguous option \`$arg'."
      echo "$help"
      exit 1
      ;;
    
    *)
      nonopt="$nonopt $arg"
    ;;
  esac
done

if test -n "$prevopt"; then
  exec 1>&2
  echo "$program: option \`$prevopt' requires an argument"
  echo "$help"
  exit 1
fi

case `echo "$nonopt" | wc -w | sed -e 's/[\t ]//g'` in
  0)  file=-;;
  1)  file=$nonopt;;
  *)  exec 1>&2
     echo "$program: too many arguments"
     echo "$help"
     exit 1;;
esac

# Set -x now if debugging
test $debug && set -x

# Temp dir.  Get ready not to leave junk (if not debugging)
test $debug || trap "/bin/rm -rf $tmpdir" 0 1 2 3 13 14 15
mkdir $tmpdir

# If printing from stdin, save into a tmp file
if test $file = '-'; then
  file=$tmpdir/stdin.ps
  cat > $file
fi

#################### Global fixes ####################

# 1. Extract what looks like a real PS file, i.e. something between
# a "%!PS" and a "%%EOF".  If the latter is not present, go until
# the end of the file.
# It typically remove JCL junk, but also permits to print the PS content
# of a mail without having to remove at hand what is not part of the PS.
if sed 1q $file | grep '^\?%!PS' >/dev/null; then :; else
  fix=1
  $verbose "$program: removing junk around PostScript content." >&2
  sed -n -e '/%!PS/,/^%%EOF$/p' $file > $tmpdir/fixed$fix.ps
  file=$tmpdir/fixed$fix.ps
fi

# 2. Broken magic number (PC?)
if sed 1q $file | fgrep '' >/dev/null; then
  fix=2
  $verbose "$program: fixing broken magic number." >&2
  sed 's/^%!PS/%!PS/' $file > $tmpdir/fixed$fix.ps
  file=$tmpdir/fixed$fix.ps
fi

# If at this point the file does not start with a real PostScript
# magic number, fail
if sed 1q $file | grep '^%!PS' >/dev/null; then :; else
  echo "$program: error: the file seems not to be PostScript." >&2
  exit 1
fi

############ After this line everything can be done with a pipe ##########
command="cat $file"
# 4. Broken end-of-line (Mac?)
if sed 20q $file | fgrep '
%%' > /dev/null; then
  fix=4
  $verbose "$program: fixing broken end of line." >&2
  command="$command | tr '\r' '\n'"
fi

#################### Fixes on prologues/structure ####################
comments=`sed -n -e '/^%!/,/^%%EndComments/p' $file`

# 5. Broken AppleDict procset
if sed 20q $file | fgrep 'AppleDict' > /dev/null; then
  fix=5
  $verbose "$program: fixing Macintosh broken prologue." >&2
  command="$command | fixmacps"
fi

# 6. Broken Frame Maker procset
if sed 20q $file | fgrep 'Frame' > /dev/null; then
  fix=6
  $verbose "$program: fixing Frame Maker broken prologue." >&2
  command="$command | fixfmps"
fi

# 7. Broken CorelDRAW ps
if echo "$comments" | grep '^%%Title:.*CorelDRAW' > /dev/null; then
  fix=7
  $verbose "$program: fixing CorelDRAW broken prologue." >&2
  command="$command | fixnt"
# 8. Broken CorelDRAW ps (fixed by the same prog)
elif echo "$comments" | grep '^%%Creator: Windows NT 4.0' > /dev/null; then
  fix=8
  $verbose "$program: fixing Windows NT broken prologue." >&2
  command="$command | fixnt"
fi

# Output the result
if test "$output" && test "$output" != "-"; then
  eval $command > $output || exit 1
else
  eval $command || exit 1
fi

# Don't remove files if debugging
test $debug || /bin/rm -rf $tmpdir

exit 0

