#!/bin/bash

PAPERSIZES="a0 2384 3370 
a1 1684 2384 
a2 1191 1684 
a3 842 1191 
a4 595 842 
a5 420 595 
a6 297 420 
a7 210 297 
a8 148 210 
a9 105 148 
a10 73 105 
isob0 2835 4008 
isob0 load def
isob1 2004 2835 
isob1 load def
isob2 1417 2004 
isob2 load def
isob3 1001 1417 
isob3 load def
isob4 709 1001 
isob4 load def
isob5 499 709 
isob5 load def
isob6 354 499 
isob6 load def
jisb0 2920 4127 
jisb1 2064 2920 
jisb2 1460 2064 
jisb3 1032 1460 
jisb4 729 1032 
jisb5 516 729 
jisb6 363 516 
c0 2599 3677 
c1 1837 2599 
c2 1298 1837 
c3 918 1298 
c4 649 918 
c5 459 649 
c6 323 459 
archE 2592 3456 
archD 1728 2592 
archC 1296 1728 
archB 864 1296 
archA 648 864 
flsa 612 936 
flse 612 936 
halfletter 396 612 
pa4 595 792"

function usage() {
	echo -en "Usage: $0 <papersize> <ps2pdf options>\n\twhere <papersize> is one of: "
	while read p w h; do
		echo -n "$p ${p}l "
	done << __ENDS
		$PAPERSIZES
__ENDS
	echo
	echo -e "\tor <papersize> is <width_in_mm>x<height_in_mm>"
}

if [[ -z $1 ]]; then
	usage >&2
	exit 1
fi

unset W
unset H
while read p w h; do
	if [[ $1 == $p ]]; then
		H=$h
		W=$w
	fi
	if [[ $1 == ${p}l ]]; then
		W=$h
		H=$w
	fi
done << __ENDS
$PAPERSIZES
__ENDS


#has an undefined paper size been specified?
if [[ -z $W ]]; then
	#try to parse <width_in_mm>x<height_in_mm>
	W=${1%%x*}
	H=${1##*x}
	
	if [[ -z $W ]] || [[ -z $H ]]; then
		echo "Error: $1 not a known papersize and could not parse $1 as \"<width>x<height>\"" >&2
		exit 1
	fi
	
	#convert mm to points
	W=`echo "($W*72+12.7)/25.4"|bc 2>/dev/null`
	H=`echo "($H*72+12.7)/25.4"|bc 2>/dev/null`
	
	if [[ -z $W ]] || [[ -z $H ]] || [[ $W == 0 ]] || [[ $H == 0 ]]; then
		echo "Error: cannot convert $1 from mm to points" >&2
		exit 1
	fi
fi

shift
ps2pdf -dDEVICEWIDTHPOINTS=$W -dDEVICEHEIGHTPOINTS=$H "$@"	
