#!/bin/sh

prefix=/usr
exec_prefix=/usr
datadir=/usr/share
tmpdir=$(mktemp -d /tmp/wvText.XXXXXXXX) || { echo "$0: can not create temporary directory" >& 2; exit 1; }
i_file=
o_file=

# argument checking

case ${#} in
    1)
	i_file=${1}
	o_file=-
	;;
    2)
	i_file=${1}
	o_file=${2}
	;;
    *)
	echo "Usage: `basename ${0}` <word document> [<text output file>]"
	exit 1
	;;
esac

# start out optimistic
USING_BROWSER=1
BROWSER_CMD="w3m -dump -T text/html"
browser=none

which lynx >& /dev/null && browser=lynx
which w3m >& /dev/null && browser=w3m

case $browser in
    w3m)
	BROWSER_CMD="w3m -dump -T text/html"
	;;
    lynx)
	BROWSER_CMD="lynx -dump -force_html"
	;;
    *)
	echo "Neither w3m nor lynx found"
	echo "Output will be pretty bad."
	USING_BROWSER=0
	;;
esac

if [ ${USING_BROWSER} -ne "0" ]; then

    # first, test for wvHtml
    which wvHtml >/dev/null 2>&1
    if [ ${?} -ne "0" ]; then
       	echo "Could not find required program 'wvHtml'"
	exit 1
    fi

    # intermediate file
    TMP_FILE="wv$$.html"

    wvHtml "$i_file" --targetdir="${tmpdir}" "${TMP_FILE}" >/dev/null 2>&1
    if [ ${?} -ne "0" ]; then
	echo "Could not convert $i_file into HTML"
	exit 1
    fi

    # lynx actually does quite well
    # Output to stdout requested
    if test "x$o_file" = "x-"; then
	TERM=vt100 ${BROWSER_CMD} "${tmpdir}/${TMP_FILE}"
    else
	TERM=vt100 ${BROWSER_CMD} "${tmpdir}/${TMP_FILE}" > "$o_file"
    fi
    if [ ${?} -ne "0" ]; then
	    echo "Could not convert $i_file into Text"
	    exit 1
    fi

    # clean up
    rm -rf "${tmpdir}"

else
    # fall back onto our cruddy output
    # this is, admittedly, better than running
    # 'strings' on the word document though :)
    if test "x$o_file" = "x-"; then
	wvWare -x ${datadir}/wv/wvText.xml "$i_file"
    else
	wvWare -x ${datadir}/wv/wvText.xml "$i_file" > "$o_file"
    fi
fi
