#!/bin/bash
#
#+
# NAME:
#	idlprint
# PURPOSE:
#	Spawned by IDL procedure spitplot to send plots to the HP LaserJet III
#	printer.
# CALLING SEQUENCE
#	idlprint plot_file
# INPUTS:
#	plot_file	name of a plot file created by IDL
# OUTPUTS:
#	(hardcopy on LaserJet III)
# SEE ALSO:
#	spitplot
# PROCEDURE:
#	A new file is written with the following content:
#	<ESC>E				(printer reset)
#	<ESC>%0B			(puts printer in graphics mode HP-GL2)
#	< content of 'plot_file' >	(appended using unix 'cat' command)
#	<ESC>%0A			(puts printer back into PCL mode)
#	<ESC>%0A			(repeat command to eject the page;
#					 don't know why we need it, but it works)
#	This file is then send to the printer using:
#		lpr -Pprint185 -r
#	(the -r switch deletes the file after printing)
#	'plot_file' is explicitly deleted with the 'rm' command.
# MODIFICATION HISTORY:
#	Kevin Nguyen, Paul Hick (UCSD/CASS)
#	    The procedure used here is essentially the same as used on VMS.
#	NOV-2005, Paul Hick (UCSD/CASS; pphick@ucsd.edu)
#	    Modified to print to the first queue that is ready to print
#	    (by looking at output of lpq command).
#-

touch $1'toprint'

echo -e "\033E\033%0B" > $1'toprint'
cat $1 >> $1'toprint'
echo -e "\033%0A\033E" >> $1'toprint'
echo -e "\033%0A\033E" >> $1'toprint'

submitted=0

lpq | grep "is ready" | gawk '{print $1}' |
while read line; do
	if [ $submitted == 0 ]; then
		echo "$(basename $0), send to queu $line"
		lpr -P$line -r $1'toprint'
		submitted=1
	fi
done

if [ "$2" == "" ]; then
	rm -f $1
fi

exit 0
