#!/bin/sh 

if [ ${#} -ne "1" ]; then
	echo "Usage: ${0} <word document>"
	exit 1
fi

# check our requirements
type wvPS >/dev/null 2>&1
if [ ${?} -ne "0" ]; then
	echo "Error: required program 'wvPS' was not found"
	exit 1
fi

# viewer application
GV=""

# check for gnome ghost-view first
type ggv >/dev/null 2>&1
if [ ${?} -eq "0" ]; then
	GV="ggv"
else
	# TODO: does kde have something?

	# try to default back onto gv
	type gv >/dev/null 2>&1
	if [ ${?} -eq "0" ]; then
		GV="gv"
	else
		# old solaris systems
		type ghostview >/dev/null 2>&1
		if [ ${?} -eq "0" ]; then
			GV="ghostview"
		else
			# unrecoverable error
			echo "Could not find a suitable PostScript viewer."
			echo "Please install ggv, gv, or ghostview"
			exit 1
		fi
	fi
fi

# temporary PS file, mangled to get some sort
# of semi-uniqueness
FILE="`basename "${1}"`"
TMPDIR=$(mktemp -d /tmp/wvMime.XXXXXXXX) || { echo "$0: can not create temporary directory" >& 2; exit 1; }
TMPPS="$TMPDIR/tmp.ps"
TMPFILE="$TMPDIR/tmpfile"
TMPTEX="$TMPDIR/tmp.tex"
#TMPPS="$TMPDIR/${FILE}-${USER}-${$}.ps" 

# Make sure all graphics go into /tmp as well
cp "${1}" "$TMPFILE"

# Extract graphics
wvLatex "$TMPFILE" "$TMPTEX" 2>/dev/null >/dev/null

# Graphics conversion if make_epses.sh installed:
#STEM=$TMPDIR/"`basename "${1}" .doc`"
#type make_epses.sh >/dev/null 2>&1 
#  if [ ${?} -eq "0" ]; then
#    (cd $TMPDIR; make_epses.sh $STEM)
#  fi

cd $TMPDIR
wvPS `basename $TMPFILE` `basename ${TMPPS}`
if [ ${?} -ne "0" ]; then 
	echo "Could not translate into Postscript" 
	rm -rf $TMPDIR
	exit 1 
fi 

# call our ghost-viewer
${GV} "${TMPPS}"
rm -f "${TMPPS}"

cd /
rm -rf $TMPDIR
