#!/bin/bash
#
# psrotate - Rotates a PostScript file by 0/90/180/270 degrees.
# Usage: psrotate <angle> [input]
#
# Developed by Marcelo Ricardo Leitner @ Conectiva.
# Contacts: mrl@conectiva.com.br
# 20040827

cleanup() { EXIT_CODE=$? ; rm -f $input &>/dev/null ; exit $EXIT_CODE ; }
trap 'cleanup' 0 1 2 3 15

input=$(mktemp $TMPDIR/psrotate.XXXXXX)
if [ -z "$input" ]; then
	echo "Failed to create temp file at $TMPDIR." > /dev/stderr
	exit 1
fi

cat $2 > $input || exit 1
angle=$1

box=$(sed -ne '/^%%BoundingBox: /{p;q;}' $input)
if [ -z "$box" ]; then
	echo "Couldn't find %%BoundingBox tag.\n" > /dev/stderr
	exit 1
fi

IFS=' '
set - $box
a=$(echo "$4-$2" | bc)
b=$(echo "$5-$3" | bc)
if [ "$a" -gt "$b" ]; then
	c=$a
else
	c=$b
fi
unset IFS

case "$angle" in
	0)
		cat $input
		;;
	90)
		cat $input | pstops -p "R(0,$c)"
		;;
	180)
		cat $input | pstops -p "U($a,$b)"
		;;
	270)
		cat $input | pstops -p "L($c,0)"
		;;
esac

cleanup

# vim:ts=4:sw=4
