#!/bin/sh
#
# tm_gnuplot 
# ========== 
# bash script for interfacing gnuplot from TeXmacs
# needs option --texmacs for compatibility with TeXmacs interface convention and user information
#
# usage within TeXmacs:
# =====================
# write gnuplot-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 gnuplot.
# output is the graph made by gnuplot.

#ECHO=echo
ECHO=/bin/echo

if [ "$1" != "--texmacs" ]
then
	$ECHO tm_gnuplot. 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-gnuplot binary path and name 
# for unix/linux environments
GNUPLOT_PATH=
PIPE_GNUPLOT=gnuplot
# for windows/cygwin environment
# GNUPLOT_PATH=/cygdrive/w/tex_cd/programme/gnuplot/
# PIPE_GNUPLOT=pgnuplot.exe

# defining temporary postscript file directory
TEMP_DIR=/tmp
if [ -d $TEMP_DIR ]
then
	:
else	
	mkdir $TEMP_DIR
fi

# defining temporary postscript file name
TEMP_PS_NAME=temp.eps

# standard initialization of GNUplot
init='reset~set terminal postscript eps enhanced ~set output "'$TEMP_DIR/$TEMP_PS_NAME'"~set size 1,1~set autoscale~'
	
# startup banner
$ECHO -n $DATA_BEGIN
$ECHO verbatim:This is a TeXmacs interface for GNUplot.

# prompt-input-gnuplot-output loop
while [ 1 ]; do
	# prompt
	$ECHO -n $DATA_BEGIN
	$ECHO -n channel:prompt
	$ECHO -n $DATA_END
	$ECHO -n GNUplot'] '
	$ECHO -n $DATA_END
	 
	#read a line from stdin
	read input
	
	#concat init string and input string
	input=$init$input
	
	#for debugging purposes
	#$ECHO $input | tr  "~" "\n" | tee tm_gnuplot.log | $GNUPLOT_PATH$PIPE_GNUPLOT 
	#$ECHO -E "$input" | tr  "~" "\n" | $GNUPLOT_PATH$PIPE_GNUPLOT
	$ECHO "$input" | tr  "~" "\n" | $GNUPLOT_PATH$PIPE_GNUPLOT
	
	$ECHO -n $DATA_BEGIN
	$ECHO -n verbatim:
	
	$ECHO -n $DATA_BEGIN
	$ECHO -n ps:
	cat $TEMP_DIR/$TEMP_PS_NAME
	$ECHO -n $DATA_END
	#$ECHO -ne "\n"	
	$ECHO ""
	
	rm $TEMP_DIR/$TEMP_PS_NAME
done
