#!/bin/sh

# Write a simple eps to gif routine, in sh not csh!
# MJR 11/97, 5/00, 6/02, 5/04, 11/07
#
# Usage: see help text below
#
# Output is to stdout, errors to stderr
#
# Inspired by pstopnm, (C) 1992 Alberto Accomazzi
#
# Requires: gs, pnmscale and ppmtogif, cjpeg, pnmtopng, jpegtran, dc
#
# Revisions of 6/02
#
#   -interlace as separate flag
#   try to parse %%BoundingBox: (atend)
#   don't grep for showpage, but surround PostScript with /showpage {} def
#
# Revisions of 5/04
#
#   check whether stdout is a terminal, and abort if so
#   oversample range changed to 1 to 9 (single digit), not 0 to 9
#
# Revisions of 11/07
#
#   allow resolution of xnnn to set height without setting width
#
# Revisions of 3/09
#
#   add pnga output
#
# Revisions of 7/15
#
#   make pnga work correctly with oversample=1
#

# set defaults

convert="ppmtogif"
res=100
oversample=2
interlace=false
infile=
colours=0
gs_dev=ppmraw
gs_opt=
verbose=false

# parse arguments

while [ x$1 != x ]
do
  case $1 in
  -h*|--*)
    echo "Usage: eps2gif [-res nn[xnn]|xnn] [-gif|-ppm|-png|-jpeg[=nn]]"
    echo "               [-colours nn] [-interlace] [-nn] infile.[e]ps"
    echo
    echo " -res         specify resolution of resulting bitmap. Aspect taken from"
    echo "                 eps bounding box if only width specified"
    echo " -colours nn  reduce number of colours. Might be necessary with gifs"
    echo " -interlace   interlace output. Gif, png and jpeg only."
    echo " -nn          oversampling rate for antialiasing. Default 2"
    echo " -gif|ppm|png output format. Default gif"
    echo " -pnga        output as png with transparency. -colours ignored"
    echo " -jpeg[=nn]   jpeg, with optional quality factor. Default quality 75"
    echo
    echo "Reading from stdin is not supported. Output is to stdout."
    echo
    echo "Example: eps2gif -res 300x300 -colours 256 foo.eps > foo.gif"
    echo
    echo "MJR 5/00, 6/02, 11/07, 3/09"
    exit
    ;; 
  -res)
    res=$2
    shift
    shift
    ;;
  -gif)
    convert="ppmtogif"
    shift
    ;;
  -jpeg)
    convert="cjpeg -optimize"
    shift
    ;;
  -jpeg=*)
    q=`echo $1 | sed 's/-jpeg=//'`
    convert="cjpeg -optimise -quality ${q}"
    shift
    ;;
  -interlace)
    interlace=:
    shift
    ;;
  -ppm)
    convert="cat"
    shift
    ;;
  -png)
    convert="pnmtopng"
    shift
    ;;
  -pnga)
    convert="cat"
    gs_dev=pngalpha
    shift
    ;;
  -colours|-colors)
    colours=$2
    shift
    shift
    ;;
  -[1-9])
    oversample=`echo $1 | tr -d -`
    shift
    ;;
  -verbose)
    verbose=:
    shift
    ;;
  -debug)
    set -vx
    shift
    ;;
  *ps)
    infile=$1
    shift
    ;;
  *)
    echo Unsupported option $1 ignored 1>&2
    echo Specify -h for help 1>&2
    shift
    ;;
  esac
done

if $interlace
then
  case $convert in
  pnmtogif|pnmtopng)
    $convert="${convert} -interlace"
    ;;
  cjpeg*)
    $convert="${convert} | jpegtran -progressive -optimize"
    ;;
  *)
    echo "-interlace not supported by $convert. Ignored" 1>&2
    ;;
  esac
fi  

if [ $colours != "0" ]
then
  convert="ppmquant -fs ${colours} | ${convert}"
fi

# Do we have an input file?

if [ x$infile = x ]
then
   echo No input file specified. 1>&2
   exit 1
fi

if [ ! -r $infile ]
then
  echo Cannot read input file $infile 1>&2
  exit 1
fi

# Is our output redirected? Bash (i.e. Linux) requires a file descriptor here.

if [ -t 1 ]
then
  echo Stdout appears to be a terminal. Please redirect.  1>&2
  exit 1
fi


# Go looking for our bounding box
# Not perfect, but I don't want to parse the PostScript!

bb=`grep '^%%BoundingBox' $infile | head -1`

if [ "x$bb" = "x" ]
then
  echo No BoundingBox found in $infile 1>&2
  exit
fi

set $bb

if [ "x$2" = "x(atend)" ]
then
  bb=`grep '^%%BoundingBox' $infile | tail -1`
  set $bb
fi

llx=$2
lly=$3
urx=$4
ury=$5

# Bother DOS

ury=`echo $ury | tr -d '\r'`

sx=`expr $urx - $llx`
sy=`expr $ury - $lly`


if echo "$res" | grep -q '^[0-9][0-9]*x[0-9][0-9]*$'
then
   xres=`echo $res | sed 's/x.*$//'`
   yres=`echo $res | sed 's/^[0-9]*x//'`
elif echo "$res" | grep -q '^[0-9][0-9]*$'
then
   xres=$res
   yres=`echo "$xres $sy * $sx / p" | dc`
elif echo "$res" | grep -q '^x[0-9][0-9]*$'
then
   yres=`echo $res | sed 's/^x//'`
   xres=`echo "$yres $sx * $sy / p" | dc`
else
   echo Invalid resolution specified $res 1>&2
   exit
fi

# We have the resolution of the desired output

# What we are going to do next is increase this resolution,
# then feed the image to pnmscale to reduce it.
# This will give us some anti-aliasing

# But if we are using pnga as an output device, we will get it to do
# antialiasing itself

if [ $gs_dev = pngalpha ]
then
  if [ ${oversample} != "" ]
  then
    case "$oversample" in
    1|2|4)
      gs_opt="-dTextAlphaBits=${oversample} -dGraphicsAlphaBits=${oversample}"
      ;;
    *)
      echo "pnga supports oversampling rates of 1, 2 and 4 only" 1>&2
      echo "requested rate of $oversample ignored" 1>&2
      gs_opt="-dTextAlphaBits=2 -dGraphicsAlphaBits=2"
      ;;
    esac
  fi
  oversample=1
  convert=cat
fi

xres=`expr ${xres} \* ${oversample}`
yres=`expr ${yres} \* ${oversample}`
res=${xres}x${yres}

if [ ${oversample} != 1 ]
then
  scale=`echo "10 k 1 ${oversample} / p" | dc`
  convert="pnmscale ${scale} | ${convert}"
fi

# We need to know how many pixels per inch will give us this

xdpi=`echo "1 k $xres 72 * $sx / p" | dc`
ydpi=`echo "1 k $yres 72 * $sy / p" | dc`
dpi=${xdpi}x${ydpi}

# Now do it...

$verbose && echo "gs -sDEVICE=$gs_dev \
  -sOutputFile=- -g${res} -r${dpi} ${gs_opt} -q - $infile | \
  eval ${convert}" 1>&2

{
cat <<EOH
%!
/b4_Inc_state save def
/showpage {} def
/setpagedevice {pop} def
$llx neg $lly neg translate
EOH

cat $infile

cat <<EOT
 b4_Inc_state restore
showpage
EOT
} | gs -sDEVICE=$gs_dev \
  -sOutputFile=- -g${res} -r${dpi} ${gs_opt} -q - | \
  eval ${convert}

