#!/bin/bash
#
# $Id: lasergnu%v 3.50 1993/07/09 05:35:24 woo Exp $
#
# Print gnuplot output on an Imagen or Postscript laser printer.
#
# Rewritten for bash to avoid csh dependency by Guy Maor,
#       Guy Maor <maor@ece.utexas.edu> Thu May  9 21:11:41 1996

print_banner=on			# Print a banner page unless told otherwise.
input_files=			# the plot input command files
lpr_opts=			# options to lpr

# Default printer set by shell variable PRINTER.
printer="-P${PRINTER:-${LASER:-lw0}}"

# File for plot commands, and for plot output
TMP="/tmp/plot$$"
outfile="$TMP.out"		# the output file
trap "rm -f $TMP $outfile" 0

# default is Imagen mode for Imagen printer; see -p option
setterm="set terminal imagen"
LANG="-Limpress"

usage="Usage: lasergnu [-P printer] [-b] [-p] [-t title] [-f file] [plot_commands]..."

# Loop through the command-line arguments.
while getopts "bJf:t:P:Iph?" c ; do
    case "$c" in
	b|J)			# Do not print a banner page
	    print_banner=off
	    lpr_opts="$lpr_opts -h"
	    ;;
	f)			# Specify file containing plot commands
	    input_files="$input_files $OPTARG"
	    ;;
	t)			# Specify title of plot
	    title=$OPTARG
	    ;;
	P)			# set the printer, exactly as by itroff
	    printer="-P$OPTARG"
	    ;;
	I)			# use impress
	    echo Imagen is the default mode now
	    ;;
	p)			# use postscript instead of impress language
	    setterm="set term postscript"
	    LANG="-Lpostscript"
	    ;;
	h|?)
	    echo $usage 1>&2
	    exit 1
	    ;;
    esac
done

if [ "$OPTIND" -gt 1 ] ; then
    shift $[$OPTIND - 1]
elif [ -z "$input_files" ] ; then
    echo -e "lasergnu: Give me something to plot.\n$usage" 1>&2
    exit 1
fi

# try to divine the printer type
case $printer in
    -Plw)
	setterm="set term postscript"
	LANG="-Lpostscript"
	;;
    -Pim)
	setterm="set term imagen"
	LANG="-Limpress"
	;;
esac

# Set up input file
cat > $TMP <<EOF
$setterm
set output "$outfile"
EOF
if [ "$title" ] ; then echo "set title \"$title\"" >> $TMP ; fi
while [ "$1" ] ; do echo $1 >> $TMP ; shift ; done

# If input file is specified AND command line contains plot commands, then
#   do command line args first, then plot commands in input file.
gnuplot $TMP $input_files

if [ $? -eq 0 -a -s $outfile ] ; then
    # The printer is whatever printer was last specified,
    # or the default printer if none was specified.
    if [ "$LANG" = "-Limpress" ] ; then
	ipr $LANG $printer -D"jobheader $print_banner" -D"pagereversal on" \
	    -D"program lasergnu" $outfile
    elif [ "$LANG" = "-Lpostscript" ] ; then
	lpr $lpr_opts $printer $outfile
    fi
else
    echo "lasergnu: error in plotting or empty plot; nothing printed."
fi
