#!/bin/csh

# route latex output to printer using latex | dvi2ps

set printer=""
set dviopts=""
set cmd=""
set dvifilter="/usr/local/dvi2ps"
set rm="/bin/rm"
set lpr="lpr"
set lpropts=""

# what tex processor should we use?
set hold=$0		# csh doesn't allow $0:t
switch ($hold:t)
case "platex":
	set texcmd="latex"
	breaksw
case "ptex":
	set texcmd="tex"
	breaksw
case "pslitex":
	set texcmd="slitex"
	breaksw
default:
	set texcmd="tex"
	breaksw
endsw

# parse the arguments
foreach arg($*)
	switch ($arg)
	case "-twopass":	# run latex twice before printing
		set twopass=yes
		breaksw
	case "-P*":		# change printer
                set printer="$arg"
		breaksw
	case "-*":		# assume all other opts go to filter
		set dviopts="$dviopts $arg"
		breaksw
	default:		# assume everything else is a file name
		if ($?file) then
			echo ${hold:t}: too many files.
			exit(-1)
		endif	
		set file="$arg"
		breaksw
	endsw
end

# to save some grief check if the file actually exists
if (!(-e $file)) then
	echo ${hold:t}: \"${file}\" does not exist.
	exit(-1)
endif

# what type of file is it?
switch ($file:e)
case "tex":		# run TeX preprocessor on document
	set base=${file:t}
	set base=${base:r}

	if (${?twopass}) then
		set cmd="$texcmd $file;"
	endif
	set cmd="$cmd $texcmd $file; "
	set cmd="$cmd $dvifilter $dviopts ${base}.dvi | $lpr $lpropts $printer; "
	# remove the auxilary files if they do not exist
	if (!(-e ${base}.dvi)) then
		set cmd="$cmd $rm -f ${base}.dvi; "
	endif
        if (!(-e ${base}.aux)) then
		set cmd="$cmd $rm -f ${base}.aux; "
	endif
	if (!(-e ${base}.log)) then
		set cmd="$cmd $rm -f ${base}.log;  "
	endif
	breaksw
case "dvi":		# latex already run so just filter
        set cmd="$dvifilter $dviopts $file | $lpr $lpropts $printer"
	breaksw
default:		# all else is normal lpr output
	set cmd="$lpr $printer $file"
	breaksw
endsw

# execute the command
csh -c "$cmd"
# debug the command
# echo $cmd

