#!/bin/sh
#
# tm_pyx
# ========== 
# Shell script for interfacing python-PyX from TeXmacs
# needs option --texmacs for compatibility with TeXmacs interface convention and user information
#
# usage within TeXmacs:
# =====================
# write python-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 python.
#
# Output is the graph made via python.
#
# Temporary file are made in ~/.TeXmacs/system/tmp
#

if [ "$1" != "--texmacs" ]
then
	echo tm_pyx. 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-python binary path and name 
# for unix/linux environments
PYTHON_PATH=
PIPE_PYTHON=python

# 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=pyxtmp
	
# startup banner
echo -n $DATA_BEGIN
echo verbatim:TeXmacs inteface to PyX.

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

	#create .py file
	echo -E "$input" | tr "~" "\n" > $TEMP_FILE.py

	#run python on the .py file
	$PYTHON_PATH$PIPE_PYTHON $TEMP_FILE.py 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
