#!/bin/bash

# Convert a PS file to a GCODE file
#
# (C) January 2003, Alan Bain
# Improved Feb 2003 
# Usage ps2gcode [infile.ps [outfile.gcode]]
# if outfile.gcode is omitted then output goes to standard
# out.  If infile.ps and outfile.gcode are omitted then 
# ps2gcode acts as a filter reading from stdin and writing
# to stdout

# Location of Ghostscript Binary

GS="/usr/bin/gs"

# Location of GCODE Binary

GCODE="./gcode"

# Options

OPTIONS="-dSAFER"

#################################################
# No changes beyond this point

TMPFILEA=/tmp/ps2gcodea$$

TMPFILE=/tmp/ps2gcode$$

infile=$1;

# Add the necessary commands just after the comments which
# convert the text drawn via show into paths.  Possibly 
# also should deal with ashow, cshow, xshow, yshow etc.
awk ' /^%!/	{print $0; next;}
      F==1 && !/^%/	{
		print "/show {false charpath currentpoint stroke moveto} bind def matrix setmatrix";
		print $0;
		F=2;
		}
	
	{print }
	' F=1 ${infile} >$TMPFILEA


if [ $# -lt 1 -o $# -gt 2 ]; then
	echo "Usage: `basename $0` infile.ps [outfile.gcode]" 1>&2
	exit 1
fi


if [ $# -eq 1 ]; then
	echo "1 arg"
	$GS -sDEVICE=pswrite -sOutputFile=$TMPFILE -q -dNOPAUSE -dBATCH $OPTIONS $TMPFILEA 
	$GCODE $TMPFILE
else
	echo "2args"
	$GS -sDEVICE=pswrite -sOutputFile=$TMPFILE -q -dNOPAUSE -dBATCH $OPTIONS $TMPFILEA
	$GCODE $TMPFILE $2
fi

