#! /bin/bash
# Last edited on 2024-04-01 14:55:46 by stolfi

usage="$0 [ -scale n.nnn ] [ -show ] [ EPSFILE ]"

# Converts an Encapsulated Postscript file to a GIF image.
# The input is EPSFILE if given, else the standard input.
# The result is written to standard output.

if [[  -x /usr/bin/xv  ]]; then
  view="/usr/bin/xv"
else
  view="display"
fi
getbbx="${STOLFIHOME}/bin/eps_bounding_box"
ppmtogif="${STOLFIHOME}/bin/linear_ppm_to_gif"
tmp="/tmp/$$"

unset show
scale=( ) 

while [[ ( $# -gt 0 ) && ( "/$1" =~ /-.* )  ]]; do
  if [[ ( $# -ge 2 ) && ( "/$1" == "/-scale" )  ]]; then
    scale=( "-scale" "$2" ); shift; shift
  elif [[  "/$1" == "/-show"  ]]; then
    show=1; shift
  else
    echo "** unrecognized option: $1" 1>*2
    echo "usage: ${usage}" 1>*2; exit 1
  fi
done

if [[ $# -gt 0  ]]; then
  cateps=( "cat" "$1" ); shift
else
  cateps=( "cat" )
fi

if [[ $# -ne 0 ]]; then
  echo "** bad command" 1>*2;
  echo "usage: ${usage}" 1>*2; exit 1
fi

rm -f ${tmp}.ppm ${tmp}.eps ${tmp}-x.ppm
${cateps} > ${tmp}.eps
echo "showpage quit" >> ${tmp}.eps
ls -l ${tmp}.eps >>& ${tmp}.log

bbx=( `cat ${tmp}.eps | ${getbbx} -round` )

if [[  $#bbx != 4  ]]; then
  echo "missing or invalid %%BoundingBox"; exit 1
fi

@ lox = ${bbx[1]}
@ loy = ${bbx[2]}

@ hix = ${bbx[3]}
@ hiy = ${bbx[4]}

@ hixx = ${hix} * 2
@ hiyx = ${hiy} * 2

@ wd = ${hix} - ${lox}
@ ht = ${hiy} - ${loy}

gs \
    -sDEVICE=ppmraw \
    -r144 -g${hixx}x${hiyx} \
    -sOutputFile=${tmp}-x.ppm -q \
    -dNOPLATFONTS \
    ${tmp}.eps \
  < /dev/null \
  >>& ${tmp}.log
  
if [[  ! ( -r ${tmp}-x.ppm )  ]]; then exit 1; fi

( cat ${tmp}-x.ppm \
  | pnmscale 0.50 \
  | pnmcut ${lox} 0 ${wd} ${ht} \
  | pnmdepth 255 \
  > ${tmp}.ppm ) \
  >> ${tmp}.log 2>&1

( cat ${tmp}.ppm \
  | ${ppmtogif} ${scale} \
  > ${tmp}.gif ) \
  >> ${tmp}.log 2>&1 

if [[ ${show} -ne 0 ]]; then
  ${view} ${tmp}.gif ${tmp}.ppm ${tmp}-x.ppm >>& ${tmp}.log
fi

cat ${tmp}.log 1>&2

cat ${tmp}.gif

rm -f ${tmp}.ppm ${tmp}.eps ${tmp}-x.ppm

exit 0
