#!/bin/bash
#
# 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
#
# This software falls under the GNU general public license version 3 or later.
# It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE
# in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>.
#
###############################################################################

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 1. Angles are followed by \"\:\" \for degrees and \"\<\" \for radians.
echo 2. Use \"\%\" to comment a line.echo $(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#; Is this needed?
	#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.eps 2>$TEMP_FILE.err

	#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
	  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
