#!/bin/sh

#set -vx

USAGE="$0 [-r <resolution>] [-landscape] [psfile]"

res=72
outfile=-

#if [ $# = 0 ]; then
#  echo $USAGE >&2; exit 1
#fi

while [ $# != 0 ]; do
  case "$1" in
    -l*)
      landscape=true
      shift;;
    -r)
      res=$2
      shift 2;;
    *)
      if [ "$infile" = "" ]; then
	infile="$1"
      elif [ "$outfile" = "-" ]; then
	outfile="$1"
      else
	echo $USAGE >&2; exit 1
      fi
      shift;;
  esac
done

if [ -z "$infile" ]; then
  infile=/tmp/mypstopnm$$
  trap "rm $infile" 0
  cat >$infile
fi

set -- `grep "%%BoundingBox" "$infile"`
comment="$1"
x1="$2"
y1="$3"
x2="$4"
y2="$5"

if [ "$comment" != "%%BoundingBox:" ]; then
  echo "No BoundingBox found in EPS file" >&2; exit 2
fi

if [ "$landscape" = "true" ]; then
  trans="270 rotate $x2 neg $y1 neg translate"
  xsize=`expr \( $y2 - $y1 \) \* $res / 72`
  ysize=`expr \( $x2 - $x1 \) \* $res / 72`
else
  trans="$x1 neg $y1 neg translate"
  xsize=`expr \( $x2 - $x1 \) \* $res / 72`
  ysize=`expr \( $y2 - $y1 \) \* $res / 72`
fi

echo $trans | gs \
 -sDEVICE=ppmraw \
 -sOutputFile="$outfile" \
 -r${res} \
 -g${xsize}x${ysize} \
 -dNOPAUSE -dQUIET -dSAFER -q - "$infile" -c showpage -c quit
