#! /bin/sh

#	$Id: apsfilter,v 1.36 2000/01/02 16:33:19 andreas Exp $

################################################################################
#
#	apsfilter 5.1.4 - Line Printer Input Filter
#	-------------------------------------------
#
#	Copyright by Andreas Klemm <andreas@klemm.gtn.com>
#		Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000
#
#	You are permitted to modify and distribute apsfilter in the
#	terms of the GNU Public License (GPL) see excerpt below.
#
#	For Unix Systems With BSD Alike Print Mechanism (lpd, /etc/printcap)
#
#	Supported filetypes
#
#		ASCII, BMP, DVI, Data (PCL,...), FIG, GIF, Group 3 FAX,
#		HTML, JPEG, PBM, PDF, PostScript, PPM, Sun Raster,
#		TIFF, troff, X11 Bitmap
#
#	Supported compression types
#
#		bzip2, gzip, compress, freeze, pack
#
################################################################################

################################################################################
#
#			C O P Y R I G H T 
#
################################################################################
#
# You are permitted to use this script in the terms of the 
#
# 		    GNU GENERAL PUBLIC LICENSE
# 		       Version 2, June 1991
#
#  Copyright (C) 1989, 1991 Free Software Foundation, Inc.
#                           675 Mass Ave, Cambridge, MA 02139, USA
#  Everyone is permitted to copy and distribute verbatim copies
#  of this license document, but changing it is not allowed.
################################################################################

################################################################################
# Only for debugging purposes. If you comment out the line set -x
# (removing the '#' at the beginning of the line, then you can find very
# useful debugging output in the printers logfile 
# (see /etc/printcap definition lf=/var/spool/.../log)
# Please note: this 'log'-file has to be present in the directory, if it's
# not present, then create it using the command
#	:>log
################################################################################

# set -x

# security for temp files
umask 077
TMP_PRINTOUT=`tempfile` || exit 1
APS_HEADER=`tempfile` || exit 1
TMP_FILE=`tempfile` || exit 1
TMP_FILE2=`tempfile` || exit 1

#
# Ignore hangup, keyboard interrupt, quit from keyboard, and broken pipes.
# Other signals for abort and on exit we should remove our temp file
#
trap "echo" SIGHUP SIGINT SIGQUIT SIGPIPE
trap "rm -f $TMP_PRINTOUT $APS_HEADER $TMP_FILE $TMP_FILE2" \
				 EXIT SIGTRAP SIGBUS SIGKILL \
				 SIGUSR1 SIGUSR2 SIGTERM

# Only for experts:
# Do we have a remote printer (printer directly connected to ethernet) ???
# Then please make a reasonable entry in /etc/printcap manually and 
# activate this line:

#REMOTE_PRINTER=True

# we don't want to waste paper when debugging printing ...
#
#	the "Save the Rain Forest Feature" ;-)
#

#PRINT_TO_FILE="True"

################################################################################
#
# remember the command line in case we need to call ourselves recursively
#
################################################################################

APS_CMD="$0 $@"

################################################################################
#
# Grab apsfilters basedir from /etc/printcap
#
################################################################################

APS_BASEDIR=/usr/share/apsfilter
APS_VARDIR=/var/lib/apsfilter
export APS_BASEDIR APS_VARDIR

###########################################################################
# to find PS init files, since gs always looks into current directory (".")
###########################################################################

cd $APS_BASEDIR/lib

################################################################################
#\	evaluate command line arguments that are given to the
# \	input filter 
#  \  
#   >	apsfilter [-c] -wwidth -llength -iindent -n login -h host acct-file     
#  /
# /	defaults: width=80, length=66, indent=0
#/
#       don't rely on order, use option letters to identify options.
#       in case you wonder: the dummy string in the echo command is
#       there so that echo doesn't treat $1 as an option.
#
################################################################################

while [ -n "$1" ]; do
	if [ `echo dummy $1 | awk '{ print substr($2,1,1) }'` = "-" ]; then
		opt=`echo dummy $1 | awk '{ print substr($2,2,1) }'`
		val=`echo dummy $1 | awk '{ print substr($2,3) }'`
		if [ -z "$val" ]; then
			val=$2
			shift
		fi
		case "$opt" in
			w)	WIDTH=$val	;;
			l)	LENGTH=$val	;;
			i)	INDENT=$val	;;
			n)	LOGINNAME=$val	;;
			h)	HOST=$val	;;
		esac
	else
		ACCTFILE=$1
	fi
	shift
done

if [ -z "$WIDTH" -o "$WIDTH" = "0" ]; then WIDTH=80; fi
if [ -z "$LENGTH" ]; then LENGTH=66; fi
if [ -z "$INDENT" ]; then INDENT=0; fi

# get users home directory...
# needed in print_dvi to look for ps pictures automatically
HOME_DIR=`grep "^$LOGINNAME:" /etc/passwd|cut -d ':' -f 6 | uniq`

################################################################################
#
# NEW: auto configuration
#
################################################################################
#
# if apsfilter is called as:
#
#	aps-djet500-a4-{auto,ascii,raw}-{color,mono}-dpi
#	$1   $2     $3      $4          $5           $6
#	then we get printer type and papersize from the apsfilter call itself
#	after some trickery with cut and sed (where cut is hopefully part of
#	every Unix disrtibution, otherwise get the gnu version of cut
#	METHOD=auto	enables filetype auto recognition
#	METHOD=ascii	force printing method print ascii
#	METHOD=raw	write to print device unfiltered ....
#	COLOR=color	use color-postscript
# 	COLOR=mono	transform color to b&w postscript... so one is
# 			able to save colored pens on a colorprinter
#	DPI=<NUM>x<NUM>	resolution of the printer
#			- optionally
#			- beware, apsfilterrc files have precedence over this
SYSTEM=`uname -s`

case $SYSTEM in
	*BSD*|*bsd*)
		set -- `basename $0 | cut -f1 -d\ | sed -e 's/-/ /g'`
		;;
	*)
		set -- `basename $0 | cut -d\  -f1 - | sed -e 's/-/ /g'`
		;;
esac

LABEL=$1; PRINTER=$2; PAPERSIZE=$3; METHOD=$4; COLOR=$5; DPI=$6

# check if symlink name in filter subdir has been setup o.k.
case $LABEL in
	*aps)	# jup, seems to be that we are installed properly
		;;
	*)	# unknown filter - therefore EXIT APSFILTER
		echo "$1 wrong input filter" 2>&1
		exit 0
		;;
esac

case $COLOR in
	color)	# color-mode! set some options so color makes it to
		# the postscript-printer!
		PNMTOPS="pnmtops"
		RAS2PS_OPTS="-C"
		DJPEG_OPTS="-colors 256"
		;;

	*)	# mono-printer! Unset all color-dependent flags
		PNMTOPS="( ppmtopgm | pnmtops )"
		DJPEG_OPTS="-grayscale"
		;;
esac

################################################################################
# apsfilter customization
# =======================
#
# These files have the following preecedence:
#
# A) by the administrator:
#	- global for every printer type in
#		/etc/apsfilterrc
#	- printer type specific,
#	  they overwrite the global settings for all printer
#		/etc/apsfilterrc.${PRINTER}
# B) by the user:
#	- global for every printer type in
#		$HOME/.apsfilterrc
#	- printer type specific,
#	  they overwrite the global settings for all printer
#		$HOME/.apsfilterrc.${PRINTER}
#
# A standard apsfilter installation only installs the global config file
# 	/etc/apsfilterrc
#
################################################################################

# Global apsfilter initialization file
if [ -f /etc/apsfilterrc ]; then
	. /etc/apsfilterrc
fi

# printer type dependent apsfilter initialization file overwrites global values
if [ -f /etc/apsfilterrc.${PRINTER} ]; then
	. /etc/apsfilterrc.${PRINTER}
fi

# WARNING:
# This user custom configuration file is indeed a shell script
# It runs with the Permissions of the lpd printer daemon.
# This might be root Permissions, so this is a big security whole.
# Default is, NOT to permit users to configure apsfilter by
# their own $HOME/.apsfilterrc file.
# You must be root to set INSECURE to True in /etc/apsfilterrc 
# to allow user custom config files !!!

if [ "$INSECURE" = "True" ]; then

	# Global user defineable apsfilter initialization file
	if [ -f $HOME_DIR/.apsfilterrc ]; then
		. $HOME_DIR/.apsfilterrc
	fi

	# printer type dependent user defineable apsfilter initialization file
	if [ -f $HOME_DIR/.apsfilterrc.${PRINTER} ]; then
		. $HOME_DIR/.apsfilterrc.${PRINTER}
	fi

fi

################################################################################
# PRINT RESOLUTION and PRINTER type tweakings
# ===========================================
#
# A) use DPI variable (set by filter script name)
# B) use GS_RESOL, if defined in one of the apsfilterrc files
# C) use gs defaults...
#
# later used by
#	- dvips -D/-P commandline option
#	- gs (fill the GS_CMD_RESOL env variable)
#
# Printer type tweakings:
#	Model		driver	resol
#	-------------+------------------------
#	LaserJet 4l	ljet4	300dpi
################################################################################

if [ ! -z "${DPI}" ]; then
	RESOLUTION=${DPI}
elif [ ! -z "${GS_RESOL}" ]; then
	RESOLUTION=${GS_RESOL}
else
	# 1) if it's a true PS printer, extract resol from pseudo printer name
	# 2) check settings for printers, that need special treating
	# 3) default to RESOLUTION="", to use ghostscript's driver defaults
	case $PRINTER in
		PS_300dpi)	RESOLUTION="300x300"	;;
		PS_400dpi)	RESOLUTION="400x400"	;;
		PS_600dpi)	RESOLUTION="600x600"	;;
		PS_800dpi)	RESOLUTION="800x800"	;;
		PS_1200dpi)	RESOLUTION="1200x1200"	;;
		ljet4l)		PRINTER=ljet4
				RESOLUTION="300x300"	;;
		*)		RESOLUTION=""		;;
	esac
fi

################################################################################
#
# ENVIRONMENT SECTION - Global settings - in most cases nothing to change here
#
################################################################################
#
#	(1)  MAILX 		<- Your mailx program (can handle -s "Subject"
#				   option)
#
#	(2)  GS_FONTPATH	<- ghostscript font add on's
#
#	(3)  PRINT_PS		<- The print ps command ...
#
################################################################################

################################################################################
#
# READ GLOBAL ENVIRONMENT from GLOBAL.sh
#
################################################################################

. $APS_BASEDIR/global/GLOBAL.sh

#-------------------------------------------------------------------------------
#
# (1)  MAILX - your favourite mail program that understands "-s" (except elm !)
#      
#	typical Linux problems: /bin/mail is often a symlink to elm which
#	doesn't work since it misses the Mail folder directory, etc ....
#	Use the mailx program instead. Another advantage of mailx is, that
#	you can give a Subject with -s on the command line.
#	SunOS 4.1.X, Solaris 1 note: I think there is a program "Mail" which does
#	the job.
#
#-------------------------------------------------------------------------------

case $SYSTEM in
	*BSD*|*bsd*)		MAILX=Mail	;;
	Linux|linux)		MAILX=mailx	;;
	Solaris|solaris)	MAILX=Mail	;;
	Sun*|sun*)		MAILX=Mail	;;
	*)			MAILX=mailx	;;
esac

#-------------------------------------------------------------------------------
#
# (2) GS_FONTPATH - Some ghostscript font hacking...
#
#-------------------------------------------------------------------------------

# make use of additional X11R6 type1 fonts if installed
# and if GS_FONTPATH hasn't already been set from one of the apsfilterrc files
if [ -z "${GS_FONTPATH}" ]; then
	if [ -f /usr/X11R6/lib/X11/fonts/Type1]; then
		GS_FONTPATH=/usr/X11R6/lib/X11/fonts/Type1
	elif [ -f /var/X11R6/lib/X11/fonts/Type1]; then
		GS_FONTPATH=/var/X11R6/lib/X11/fonts/Type1
	else
		GS_FONTPATH=""
	fi
fi
export GS_FONTPATH

#-------------------------------------------------------------------------------
#
# (3) OUR COMPLETE PRINT_PS COMMAND
#
#	This shortens the print_xxx() functions,
#	that use gs as the final filter.
#	Now they all pipe through $PRINT_PS, which includes
#	the proper call of gs including all necessary options.
#
#-------------------------------------------------------------------------------

case $PRINTER in

	PS_*dpi)	# we have a PS printer, no PS emulation via gs needed
			PRINT_PS="	${PSUTILS}			\
					cat -				"
			;;

	uniprint)	# we have a non-PS printer, gs emulation needed
			# we use the new uniprint drivers...
			PRINT_PS="	${PSUTILS}			\
					gs				\
					-q				\
					@${UP_PROFILE}			\
					-sPAPERSIZE=${PAPERSIZE}	\
					-sOutputFile=-			\
					redir_gs_msg.ps			\
					-				"
			;;

	*)		# default case
			# we have a non-PS printer

			case "$PRINTER" in
				hpdj_*)
					HPDJ_MODEL='-sModel='`echo $PRINTER | sed -e s/^hpdj_//`
					PRINTER=hpdj
					;;
				*)
					HPDJ_MODEL=''
					;;
			esac

			# build ghostscript's command for print resolution
			# a) use our computed value in $RESOLUTION or
			# b) empty string to use gs default

			if [ ! -z "${RESOLUTION}" ]; then
				# use our computed resolution
				GS_CMD_RESOL="-r${RESOLUTION}"
			else
				# use gs default
				GS_CMD_RESOL=""
			fi

			PRINT_PS="	${PSUTILS}			\
					gs				\
					-q				\
					-sDEVICE=${PRINTER}		\
					${HPDJ_MODEL}			\
					${GS_CMD_RESOL}			\
					-sPAPERSIZE=${PAPERSIZE}	\
					-dNOPAUSE			\
					-dSAFER				\
					-sOutputFile=-			\
		    			${GS_FEATURES}			\
					${PS_INIT}			\
					redir_gs_msg.ps			\
					-				"
			;;
esac

if [ "$PRINT_TO_FILE" = "True" ]; then
	PRINT_PS="(cat 1> $TMP_PRINTOUT)"
fi

if [ "$REMOTE_PRINTER" = "True" ]; then
	PRINT_PS="$PRINT_PS | lpr -Premote"
fi

################################################################################
#####
##### S h e l l  -  F u n c t i o n s
#####
################################################################################

#===============================================================================
# print ascii using a2ps
#===============================================================================

print_ascii_a2ps()
{

	# get job, user and host ...
	if [ ! -z "$CONTROL" ]; then
		# for LPRng
		CF=`tempfile` || exit 1
		trap "rm -f $CF" 0 1 9 15
		echo "$CONTROL" > $CF
	else
		# for Berkeley lpr
		SPOOL_DIR=`dirname ${ACCTFILE}`
		LOCK=${SPOOL_DIR}/lock
		CF=${SPOOL_DIR}/`tail -1 ${LOCK}`
	fi
	JOB=`egrep '^J' ${CF} | tail +2c`
	USER=`egrep '^P' ${CF} | tail +2c`
	HOST=`egrep '^H' ${CF} | tail +2c`

	case $PAPERSIZE in
		letter)	A2PS_PAPERSIZE="Letter"	;;
		legal)	A2PS_PAPERSIZE="Legal"	;;
		ledger)	A2PS_PAPERSIZE="Ledger"	;;
		a3)	A2PS_PAPERSIZE="A3"	;;
		a4)	A2PS_PAPERSIZE="A4"	;;
		*)	A2PS_PAPERSIZE="Letter"	;;                           
	esac

	case $PRINTER in
		cdesk*|cdj*|desk*|djet*|hpdj)
			case $A2PS_PAPERSIZE in
				Letter|A4)
					A2PS_PAPERSIZE=${A2PS_PAPERSIZE}dj
					;;
		esac
	esac
	
	# For a detailed description of the a2ps commandline options
	# please look up the manpage

	if [ "$JOB" = "stdin" -o "$JOB" = "(STDIN)" ]; then JOB=""; fi

	A2PS_BASIC_OPTIONS="-q -o - -M $A2PS_PAPERSIZE --center-title='$JOB' \
	                    -b'Printed by $USER from $HOST' $A2PS_LANGUAGE"

	A2PS_STD_OPTIONS="-X iso1 -m --borders=no"

	# FEATURE: see users apsfilterrc or /etc/apsfilterrc
	case $FEATURE in
		1)	A2PS_FEATURES="-R -1"			;;
		2)	A2PS_FEATURES="-R -2"			;;
		1n)	A2PS_FEATURES="-R -1 -B"		;;
		2n)	A2PS_FEATURES="-R -2 -B"		;;
		1l)	A2PS_FEATURES="-r -1"			;;
		1ln)	A2PS_FEATURES="-r -1 -B"		;;
		*)	A2PS_FEATURES="--center-title=''"	;;
	esac

	# if no user defined options then take the one we provide
	# if user defined A2PS_OPTS, we have to keep the A2PS_BASIC_OPTIONS !!!

	if [ -z "$A2PS_OPTS" ]; then
		# not user defined
		A2PS_OPTS="${A2PS_BASIC_OPTIONS} \
			   ${A2PS_STD_OPTIONS} \
			   ${A2PS_FEATURES}"
	else
		# user defined, but keep BASIC options
		A2PS_OPTS="${A2PS_BASIC_OPTIONS} \
			   ${A2PS_FEATURES} \
			   ${A2PS_OPTS}"
	fi

	#case $PRINTER in
	#	djet*|pj*)
	# 		if [ -z "$GS_FEATURES" ]; then
	# 			# sane defaults for color printer
	# 			# print ascii texts black&white
	# 			GS_FEATURES="-dBitsPerPixel=1"
	# 		fi
	# 	;;
	#esac

	cat ${APS_HEADER} - | eval a2ps ${A2PS_OPTS} | eval $PRINT_PS
}

#===============================================================================
# print ascii using recode,
# useful when having to deal with different languages
#===============================================================================

print_ascii_recode()
{
	if [ -z "$RECODE_OPTS" ]; then
		# not user defined
		RECODE_OPTS="-q latin1:ibmpc"
	else
		# user defined
		RECODE_OPTS="${RECODE_OPTS}"
	fi
	cat ${APS_HEADER} - | recode ${RECODE_OPTS}
}

#===============================================================================
# print BMP files (Windows..)
#===============================================================================

print_bmp()
{
	cat ${APS_HEADER} - | bmptoppm | $PNMTOPS | eval $PRINT_PS
}

#===============================================================================
# print data files
#===============================================================================

print_data()
{
	cat ${APS_HEADER} -
}

#===============================================================================
# print dvi files using dvips->gs
#===============================================================================

#-----------------------------------------------------------
# suported env. variables for print_dvi
#-----------------------------------------------------------
# TEXINPUTS =	list of directories, where pictures reside,
#		that might be included into the printout
# PRINT_DVI =	full command to print dvi files...

print_dvi()
{
	#-----------------------------------------------------------
	# Check wether this site has a working MakeTeXPK installed
	# with the right permissions and similar stuff.
	#-----------------------------------------------------------

	if [ "$HAVE_MAKETEXPK" != "True" ] ; then
		DVIPS_OPTS="$DVIPS_OPTS -M"
	fi

	#-----------------------------------------------------------
	# there are different dvips versions around and they use 
	# different command line switches to set the print resolution
	#-----------------------------------------------------------

	if [ -z "$DVIPS_RESOL_DorP" ]; then
		# if nothing else is set I go with Thomas Essers
		# teTeX and use his dvips sysntax ;-)
		DVIPS_RESOL_DorP=-D
	fi

	#-----------------------------------------------------------
	# *** empty RESOLUTION variable ***
	# How to deal with printing DVI files, if we do not know the
	# print resolution exactly, because user deceided to use the
	# default resolution of the ghostscript printer driver...
	# -> we have to guess print resolution based on experience
	# -> default to 300dpi, if we didn't know better....
	#-----------------------------------------------------------

	if [ -z "${RESOLUTION}" ]; then
		case $PRINTER in
			bj10e)			RESOLUTION="300x300"	;;
			cdj*|*desk*|djet*|hpdj)	RESOLUTION="300x300"	;;
			laserjet|ljet[23]*)	RESOLUTION="300x300"	;;
			paintjet|pj*)		RESOLUTION="300x300"	;;
			epson)			RESOLUTION="360x180"	;;
			bj200|escp2|st800)	RESOLUTION="360x360"	;;
			bjc600)			RESOLUTION="360x360"	;;
			necp6)			RESOLUTION="360x360"	;;
			stcolor)		RESOLUTION="360x360"	;;
			ljet4)			RESOLUTION="600x600"	;;
			*)			RESOLUTION="300x300"	;;
		esac
	fi

	#-----------------------------------------------------------
	# at this point we have at least a guessed or a default resol
	# of 300x300dpi. extract x- and -y print resolution, later we
	# need x-resol for dvips command
	#-----------------------------------------------------------

	case $SYSTEM in
		*BSD*|*bsd*)
			XRES=`echo $RESOLUTION | cut -f1 -dx`
			YRES=`echo $RESOLUTION | cut -f2 -dx`
			;;
		*)
			XRES=`echo $RESOLUTION | cut -dx -f1 -`
			YRES=`echo $RESOLUTION | cut -dx -f2 -`
			;;
	esac

	#-----------------------------------------------------------
	# OPTIONS for dvips - DVIPS_OPTS
	#	-M don't create fonts automatically using MakeTeXPK
	#	   since there is a bug in it causing apsfilter to exit
	#	   after creating the first missing Font.
	#	-q quiet mode
	#	-r print last page first
	#	-t papertype
	#		(look known formats in the config file config.ps
	#		 on Linux Slackware usually in /usr/TeX/lib/tex/ps)
	#	-D (or -P) num horizontal + vertical resolution in dpi 
	#	   or:	-X num horizontal resolution in dpi 
	#		-Y num vertical   resolution in dpi 
	#	-Z compress bitmap fonts
	#	   usually only when resolution is >= 400
	#-----------------------------------------------------------

	# set dvips commandline options and determine,
	# if -Z is needed to compress bitmap fonts (XRES >= 400dpi)
	if [ $XRES -gt 400 ]; then
		DVIPS_OPTS="-q $DVIPS_RESOL_DorP $XRES -Z"
	else
		DVIPS_OPTS="-q $DVIPS_RESOL_DorP $XRES"
	fi

	# do we need to stack pages in reverse order ?
	# first check environment variable, then for known printer types...
	if [ ! -z "${PAGES_REVERSE_ORDER}" ]; then
		DVIPS_OPTS="$DVIPS_OPTS -r"
	else
		case $PRINTER in
		    cdj*|*desk*|djet*|hpdj)	DVIPS_OPTS="$DVIPS_OPTS -r"	;;
		    ljet4l)		DVIPS_OPTS="$DVIPS_OPTS -r"	;;
		    bj200|escp2|st800)	DVIPS_OPTS="$DVIPS_OPTS -r"	;;
		    stcolor)		DVIPS_OPTS="$DVIPS_OPTS -r"	;;
		    epson)		DVIPS_OPTS="$DVIPS_OPTS -r"	;;
		    bj10e)		DVIPS_OPTS="$DVIPS_OPTS -r"	;;
		esac
	fi

	case $PAPERSIZE in
		letter|legal|ledger)
				DVIPS_OPTS="$DVIPS_OPTS -t $PAPERSIZE"	;;
		a3)
				DVIPS_OPTS="$DVIPS_OPTS -t A3"		;;
		a4)
				DVIPS_OPTS="$DVIPS_OPTS -t A4"		;;
		*)		
				DVIPS_OPTS="$DVIPS_OPTS -t letter"	;;
	esac

	#-----------------------------------------------------------
	# Does the user have a better dvi print program ?
	# Ok, here we go !!
	#-----------------------------------------------------------

	if [ -z "$PRINT_DVI" ]; then

		TEXINPUTS=$TEXINPUTS:${TMPDIR:-/tmp}:/var/tmp
		export TEXINPUTS

		cat ${APS_HEADER} - > $TMP_FILE
		dvips -f $DVIPS_OPTS < $TMP_FILE | eval $PRINT_PS 
                rm -f $TMP_FILE
	else
		# this user only trusts his dvi2xxx program ;-)
		# hope he knows how to get his data from stdin ;-)
		cat ${APS_HEADER} - | $PRINT_DVI
	fi
}

#===============================================================================
# print xfig files
#===============================================================================

print_fig()
{
	cat ${APS_HEADER} - | fig2dev -Lps -P -c | eval $PRINT_PS 
}

#===============================================================================
# print GIF pictures
#===============================================================================

print_gif()
{
	cat ${APS_HEADER} - | giftopnm | eval $PNMTOPS | eval $PRINT_PS 
}

#===============================================================================
# print Group 3 FAX
#===============================================================================

print_group3fax()
{
	case "$FILE_TYPE" in
		*group*3*fax*,*normal*resolution*)
			G3_NORMAL_RESOL="-s"
			;;
		*)
			G3_NORMAL_RESOL=""
			;;
	esac

	cat ${APS_HEADER} - \
		| g3cat - \
		| g3topbm $G3_NORMAL_RESOL \
		| pbmtolps -dpi 204x196 \
		| eval $PRINT_PS 
}

#===============================================================================
# print HTML files
#===============================================================================

print_html()
{
	# set default options if not set by one of the apsfilterrc files
	if [ -z "$HTML2PS_OPTS" ]; then
		HTML2PS_OPTS="-e ISO-8859-1 -u -H"
	fi

	# call html2ps with -U when printing on a color printer, default is b&w
	if [ "$COLOR" = "color" ]; then
		HTML2PS_OPTS="$HTML2PS_OPTS -U"
	fi

	cat ${APS_HEADER} - | html2ps $HTML2PS_OPTS | $PRINT_PS 
}

#===============================================================================
# print JPEG pictures
#===============================================================================

print_jpeg()
{
	cat ${APS_HEADER} - | djpeg $DJPEG_OPTS | eval $PNMTOPS | eval $PRINT_PS
}

#===============================================================================
# print PDF files (please note, we need temp files here, see gs docu)
#===============================================================================

print_pdf()
{
	cat ${APS_HEADER} - > $TMP_FILE
	pdf2ps $TMP_FILE $TMP_FILE2
	eval $PRINT_PS < $TMP_FILE2
	rm -f $TMP_FILE $TMP_FILE2
}

#===============================================================================
# print PNM / PBM pictures
#===============================================================================

print_pnm()
{
	cat ${APS_HEADER} - | eval $PNMTOPS | eval $PRINT_PS 
}

#===============================================================================
# print postscript
#===============================================================================

print_ps()
{
	cat ${APS_HEADER} - | eval $PRINT_PS
}

#===============================================================================
# print raw for - fast listing or
#		- Windows files
#		and fine tune printeer settings
#===============================================================================

print_raw()
{
	case $PRINTER in
		cdj*|*desk*|*[dl]jet*|laserjet|lj4*|dnj*|paintjet|pj*|hpdj)
			#Translate LF to CR+LF and FF to CR+FF
			printf "\033&k2G"
                        # Perforation Skip Mode off (DIN A4: 66 lines/page)
                        printf "\033&l0L" ;;
	esac

	if [ $PRINT_RAW_SETUP_PRINTER ]; then
		printf $PRINT_RAW_SETUP_PRINTER
	fi

	cat -

	# usually we do a nice formfeed
	if [ -z "$PRINT_RAW_SUPPRESS_FORMFEED" ]; then
		printf "\014"
	fi
}

#===============================================================================
# print sun rasterfile 
#===============================================================================

print_sunraster()
{
	cat ${APS_HEADER} - | ras2ps $RAS2PS_OPTS | $PRINT_PS 
}

print_sunraster2()
{
	cat ${APS_HEADER} - | rasttopnm | eval $PNMTOPS | eval $PRINT_PS 
}

#===============================================================================
# print TIFF pictures
#===============================================================================

print_tiff()
{
	# has to seek in a file...
	cat ${APS_HEADER} - > $TMP_FILE
	tifftopnm $TMP_FILE | eval $PNMTOPS | eval $PRINT_PS
	rm -f $TMP_FILE
}

#===============================================================================
# print troff texts
#===============================================================================

print_troff()
{
	GROFF_CMD=`cat ${APS_HEADER} | grog -Tps`
	cat ${APS_HEADER} - | $GROFF_CMD | eval $PRINT_PS 
}

#===============================================================================
#
# print according to file type
#
#===============================================================================

print_auto()
{
	if [ "$COLOR" = "mono" ]; then
		if [ "$HAVE_PNMTOPS" = "True" \
		   -a "$HAVE_PPMTOPGM" = "True" ]; then		
			HAVE_PNMTOPS=True
		else
			HAVE_PNMTOPS=False
		fi
	fi

	# lowercase content of FILE_TYPE variable
	# later we can use FILE_TYPE without having to call tr again
	# if we need a finer granularity in the print_xxx shell functions
	FILE_TYPE=`echo $FILE_TYPE | tr 'A-Z' 'a-z'`

	case $FILE_TYPE in

		# Order is important !!!
		# ascii and data should appear as last otherwise
		# *script* *text* *data* collide with other file types

		*dvi*)
			if [ "$HAVE_DVIPS" = "True"   \
			  -o -n "$PRINT_DVI" ]; then
				print_dvi
			else
				fault_filetype
			fi
			;;

		*fig*)
			if [ "$HAVE_FIG2DEV" = "True" ]; then
				print_fig
			else
				fault_filetype
			fi
			;;

		*gif*)
			if [ "$HAVE_GIFTOPNM" = "True" \
			  -a "$HAVE_PNMTOPS"  = "True" ]; then
				print_gif
			else
				fault_filetype
			fi
			;;

		# This has to be checked before *data* case !!!
		*group*3*fax*|*raw*g3*data*)
			if [ "$HAVE_G3CAT"    = "True" \
			  -a "$HAVE_G3TOPBM"  = "True" \
			  -a "$HAVE_PNMTOLPS" = "True" ]; then
				print_group3fax
			else
				fault_filetype
			fi
			;;

		*html*)
			if [ "$HAVE_HTML2PS" = "True" ]; then
				print_html
			else
				fault_filetype
			fi
			;;

		*jpeg*)
			if [ "$HAVE_DJPEG"    = "True" \
			  -a "$HAVE_PNMTOPS"  = "True" ]; then
				print_jpeg
			else
				fault_filetype
			fi
			;;

		pc*bitmap*data*)
			if [ "$HAVE_BMPTOPPM" = "True" \
			  -a "$HAVE_PNMTOPS"  = "True" ]; then
				print_bmp
			else
				fault_filetype
			fi
			;;

		*pdf*)
			print_pdf
			;;

		*pnm*|*pbm*|*ppm*)
			if [ "$HAVE_PNMTOPS" = "True" ]; then
				print_pnm
			else
				fault_filetype
			fi
			;;

		postscript*)
			print_ps
			;;

		sun*raster*|*rasterfile*)
			if [ "$HAVE_RAS2PS" = "True" ]; then
				print_sunraster
			elif [ "$HAVE_RASTTOPNM" = "True" ]; then
				print_sunraster2
			else
				fault_filetype
			fi
			;;

		*tiff*)
			if [ "$HAVE_TIFFTOPNM" = "True" \
			  -a "$HAVE_PNMTOPS"   = "True" ]; then
				print_tiff
			else
				fault_filetype
			fi
			;;

		*troff*)
			if [ "$HAVE_GROFF" = "True" \
			  -a "$HAVE_GROG"  = "True" ]; then
				print_troff	
			else
				fault_filetype
			fi
			;;

		*mail*|*news*)
			# a2ps has autodetect problems, so do it here
			# we checked presence of gs already...
			if [ -z "$USE_RECODE_NOT_A2PS" \
			     -a "$HAVE_A2PS" = "True" ]; then
				A2PS_LANGUAGE="-Email"
				print_ascii_a2ps
			elif [ ! -z "$USE_RECODE_NOT_A2PS" \
				 -a "$HAVE_RECODE" = "True" ]; then
				print_ascii_recode
			else
				fault_filetype
			fi
			;;

		*shell*script*)
			# a2ps has autodetect problems, so do it here
			# we checked presence of gs already...
			if [ -z "$USE_RECODE_NOT_A2PS" \
			     -a "$HAVE_A2PS" = "True" ]; then
				A2PS_LANGUAGE="-Esh"
				print_ascii_a2ps
			elif [ ! -z "$USE_RECODE_NOT_A2PS" \
				 -a "$HAVE_RECODE" = "True" ]; then
				print_ascii_recode
			else
				fault_filetype
			fi
			;;

		# these "wildcards" should be the last ones...
		*ascii*|*text*|*english*|*script*)
			# we checked presence of gs already...
			if [ -z "$USE_RECODE_NOT_A2PS" \
			  -a "$HAVE_A2PS" = "True" ]; then
				print_ascii_a2ps
			elif [ ! -z "$USE_RECODE_NOT_A2PS" \
			  -a "$HAVE_RECODE" = "True" ]; then
				print_ascii_recode
			else
				fault_filetype
			fi
			;;

		# these "wildcards" should be the last ones...
		*data*|*escape*|*pcl*|*pjl*|*printer*job*language*)
			# that's certainly not critical,
			# you're on your own ;-)
			print_data
			;;

 		*)		
			# data we - I'm so sorry - don't know
			fault_filetype
			;;
	esac
}

#===============================================================================
#
# UNKNOWN file or method type, too bad ;->
#
#===============================================================================

fault_filetype()
{
    echo "apsfilter: unsupported filetype 
\
	$FILE_TYPE from $LOGINNAME
\
	or missing filter ! 
\
	or perhaps you have to type lpr -Pascii to print an ascii 
\
	file containing control characters or lpr -Praw to print 
\
	a file in your printers native language, when printing data 
\
	files (pcl3, pcl5, ...) ?! " \
    >&2

    # mail to printer admin
    echo "apsfilter: unsupported filetype 
\
	$FILE_TYPE from $LOGINNAME
\
	or missing filter ! 
\
	or perhaps you have to type lpr -Pascii to print an ascii 
\
	file containing control characters or lpr -Praw to print 
\
	a file in your printers native language, when printing data 
\
	files (pcl3, pcl5, ...) ?! " \
    | $MAILX -s "apsfilter: printer fault" $NOTIFY \
    2> /dev/null
}

fault_method()
{
	echo "apsfilter: unknown print method $METHOD" >&2

	# mail to printer admin
	echo "apsfilter: unknown print method $METHOD" \
	| $MAILX -s "apsfilter: printer fault" $NOTIFY \
	2> /dev/null
}

fault_unpacker()
{
	echo "apsfilter: missing $UNPACKER utility to print file" >&2

	# mail to printer admin
	echo "apsfilter: missing $UNPACKER utility to print file" \
	| $MAILX -s "apsfilter: printer fault" $NOTIFY \
	2> /dev/null
}

#  / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
# / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
#  / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
#
#   M A I N  ( )
#
#  / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
# / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
#  / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /


if [ $METHOD = raw ]; then

	print_raw

else

	if [ -f $FILTERS_FOUND ]; then
	    . $FILTERS_FOUND
	fi

	# Use the file command to figure out what kind of file this is.
	# We cannot just call file on stdin because later we need the
	# whole file for printing. We could copy stdin to disk but this
	# might waste a lot of disk space for large files. Instead we
	# try to copy just enough for file to do its job, later we
	# cat this file header and the remaining stdin together again.
	# The file command may read up to 8k bytes, need to figure out
	# how to copy this much of stdin into a temporary file, try to
	# use head if possible, fallback is to copy the whole file using
	# cat.

	BYTES_NEEDED=8192

	if head -c -n 1 </dev/null >/dev/null 2>&1; then
		head -c -n $BYTES_NEEDED > ${APS_HEADER}
	elif head -c 1 </dev/null >/dev/null 2>&1; then
		head -c $BYTES_NEEDED > ${APS_HEADER}
	else
		cat - > ${APS_HEADER}
	fi

	set -- `file ${APS_HEADER}`
	shift
	FILE_TYPE=$*

	# if the file was compressed we simply decompress it and call
	# apsfilter again with the resulting uncompressed stream

        case `echo $FILE_TYPE | tr 'A-Z' 'a-z'` in

		*bzip*)
			if [ "$HAVE_BUNZIP2" = "True" ]; then
				cat ${APS_HEADER} - | bunzip2 | ${APS_CMD}
			else
				UNPACKER="bunzip2"
				fault_unpacker
			fi
			;;

		*gzip*)
			if [ "$HAVE_GZIP" = "True" ]; then
				cat ${APS_HEADER} - | gzip -dc | ${APS_CMD}
			else
				UNPACKER=gzip; fault_unpacker
			fi
			;;

		*compress*)
			if [ "$HAVE_COMPRESS" = "True" \
			    -o "$HAVE_GZIP" = "True" ]; then
				cat ${APS_HEADER} - | zcat | ${APS_CMD}
			else
				UNPACKER="compress or gzip"
				fault_unpacker
			fi
			;;

		*frozen*)
			if [ "$HAVE_MELT" = "True" ]; then
				cat ${APS_HEADER} - | fcat | ${APS_CMD}
			else
				UNPACKER=melt; fault_unpacker
			fi
			;;

		*packed*)
			if [ "$HAVE_GZIP" = "True" ]; then
				cat ${APS_HEADER} - | zcat | ${APS_CMD}
			else
				UNPACKER=gzip; fault_unpacker
			fi
			;;

		*)	# it's not compressed

			case $METHOD in

				ascii)	
					print_ascii_a2ps
					;;
				auto)
					print_auto
					;;
				*)
					fault_method 
					;;
			esac
			;;
	esac

	rm ${APS_HEADER}
fi