#!/bin/sh
#
# tm_eukleides 
# ========== 
# bash script for interfacing eukleides from TeXmacs
# needs option --texmacs for compatibility with TeXmacs interface convention and user information
#
# usage within TeXmacs:
# =====================
# write eukleides-commands within the input line, use as many commands as necessary, 
# divide them by the ~ chararacter, because the ENTER key terminates the input and sends it to eukleides.
# output is the graph made via eukleides, tex, and dvips -E mode.
#
# Temporary file are made in ~/.TeXmacs/system/tmp
#

if [ "$1" != "--texmacs" ]
then
	echo tm_eukleides. This script should be started only from TeXmacs.
	exit
fi	

# control characters
tmp=`echo DATA_BEGIN=X DATA_END=Y DATA_ESCAPE=Z | tr "XYZ" "\002\005\027" `
eval $tmp

# defining pipe-eukleides binary path and name 
# for unix/linux environments
EUKLEIDES_PATH=
PIPE_EUKLEIDES=eukleides

# defining temporary files directory and make it is is doesn't exist
TEMP_DIR=~/.TeXmacs/system/tmp
if [ -d $TEMP_DIR ]
then
	cd $TEMP_DIR
else	
	mkdir -p $TEMP_DIR
	cd $TEMP_DIR
fi

# defining primary temp file name
TEMP_FILE=euktmp
	
# startup banner
echo -n $DATA_BEGIN
echo -n latex:'$E \Upsilon K \Lambda \tmop{EI} \Delta H \Sigma$'
echo $DATA_END
echo -n $DATA_BEGIN
echo verbatim:A Euclidean Geometry Drawing Language
echo -n $(eukleides -v)

# prompt-input-eukleides-output loop
while [ 1 ]; do
	# prompt
	echo -n $DATA_BEGIN
	echo -n channel:prompt
	echo -n $DATA_END 
	echo -n Eukleides'] '
	echo -n $DATA_END 
	 
	#read a line from stdin
	read input

	#create .euk file
	echo $input | tr  "~" "\n" | cat > $TEMP_FILE.euk

	#begin creation of TeX file
	echo "\input pst-eps\input pst-plot\input pst-node\TeXtoEPS" > $TEMP_FILE.tex

	#run eukleides on the .euk file and redirect into .tex and keep track of errors
	eukleides $TEMP_FILE.euk >>$TEMP_FILE.tex 2>$TEMP_FILE.err

	#finish TeX file
	echo "\endTeXtoEPS\nopagenumbers\end" >> $TEMP_FILE.tex

	#check if error occured, then cat .err else cat .eps to TeXmacs.
	if [ -s $TEMP_FILE.err ]
	then
	  echo -n $DATA_BEGIN
	  echo -n verbatim:
	  cat $TEMP_FILE.err
	  echo -n $DATA_BEGIN
	  echo -n ps:
	  echo -n $DATA_END
	  echo -ne "\n"
	  rm $TEMP_FILE.*
	else
	  tex --interaction=nonstopmode $TEMP_FILE.tex > /dev/null
	  dvips -q -f -E $TEMP_FILE.dvi -o $TEMP_FILE.eps > /dev/null
	  echo -n $DATA_BEGIN
	  echo -n verbatim:
	  echo -n $DATA_BEGIN
	  echo -n ps:
	  cat $TEMP_FILE.eps 
	  echo -n $DATA_END 
	  echo -ne "\n"	
	  rm $TEMP_FILE.*
    	fi
	
done
