#!/bin/bash
#
# This script creates a 2D visualisation of the calculation results of INVERT.
#
# The required AWK scripts "obsrange.awk", "splitcodes.awk", "plt2dat.awk" are
# expected to be found in the actual working directory or in the directory
# defined in the environment variable INVERTDIR. If INVERTDIR is not set or
# empty it defaults to "./invert".
#
# Dependencies on external programs:
#   bash
#   basename
#   cat
#   gawk
#   gnuplot (>= 4.0)
#   mkdir
#   sed
#
# (C) 2008 Peter L. Smilde
#

if [ -z "${INVERTDIR}" ] ; then
		INVERTDIR="./invert"
fi

#==============================================================================

function usage()
{
		echo "Usage: `basename $0` [-g gnuplot_gridding_comands] [-d gnuplot_data_commands] "
		echo "       [-m gnuplot_model_commands] [-x center | -y center] [-e]"
		echo "       [-s label_shuffle_seed] [-p] [-w] [-h] <def-file>"
}

function showhelp()
{
		usage
		echo
		echo " - The options -g, -d and -m allow the user to enter gnuplot commands which"
		echo "     are inserted just before the splot command (for gridding, e.g."
		echo "     -g \"set dgrid3d 81,81,\" or -g \"set dgrid3d ,,4\") or just before the"
		echo "     plot command (-d for the upper panel, -m for the lower panel, e.g."
		echo "     -d \"set size 1,0.25; set origin 0,0.75\" -m \"set size 1,0.75\")."
		echo
    echo " - If the observation points are not a profile in x or y direction, then "
		echo "     the options -x or -y define the coordinate value of a selected profile"
		echo "     prependicular to the plotting plane."
		echo
		echo " - With option -e the a-priori and a-posteriori standard deviations are"
		echo "     plotted." 
		echo
		echo " - With different values of the seed for option -s the location of density"
		echo "     labels will be shuffled. Useful in case they are not well identifiable."
		echo
		echo " - Option -p creates a printable postscript file (extension: .ps)."
		echo
		echo " - With option -w the windows version of gnuplot (pgnuplot) will be called."
		echo
}

#==============================================================================

function isequal()
{
		[ $(echo "$1 $2" | (LANG=C;gawk '{ print $1==$2; }' -)) -eq 1 ]
}

#==============================================================================

MINXMESH=40
MINYMESH=40
NORM=4
GRIDCMD=""
DATACMD=""
MODELCMD=""
X=""
Y=""
STDEV=0;
SEED=0
PRINT=0
SHOWBIND=0
ISWGNUPLOT=0
OUTDIR="./inverttmp"

#-------------------------
# Get commandline options
#-------------------------

while getopts "x:y:es:g:d:m:pbwh" OPTIONS ; do
		case $OPTIONS in
				x ) X=$OPTARG; Y="";;
				y ) Y=$OPTARG; X="";;
				e ) STDEV=1;;
				s ) SEED=$OPTARG;;
				g ) GRIDCMD=$OPTARG;;
				d ) DATACMD=$OPTARG;;
				m ) MODELCMD=$OPTARG;;
        p ) PRINT=1;;
				b ) SHOWBIND=1;;
				w ) ISWGNUPLOT=1;;
				h ) showhelp; exit 0;;
				\? ) usage; exit 1;;
				* ) usage; exit 0;;
		esac
 
done
shift $(($OPTIND-1))

if [ ${PRINT} -eq 1 ] ; then
		SHOWBIND=0
fi

if [ ${ISWGNUPLOT} -eq 0 ] ; then
		GNUPLOT="gnuplot"
		X11TERM=$(${GNUPLOT} --help | gawk '/X11/ { print "yes" ; exit }')
else
		GNUPLOT="pgnuplot"
fi

GNUPLOTVERSION=($(${GNUPLOT} --version | gawk '{ if (match($2,/[^.]*/)) { major=substr($2,RSTART,RSTART+RLENGHTH) } if (match($2,/[^.]*$/)) { minor=substr($2,RSTART,RSTART+RLENGHTH) } print major,minor }'))

#------------------------
# Check script directory
#------------------------

SCRIPTDIR=""
for DIR in "." "$INVERTDIR" ; do
		if [ -d "$DIR" -a -f "$DIR/obsrange.awk" -a -f "$DIR/splitcodes.awk" -a -f "$DIR/plt2dat.awk" ] ; then
				SCRIPTDIR="$DIR"
				break;
		fi
done

if [ -z "${SCRIPTDIR}" ] ; then
		echo "ERROR: Required AWK scripts not found in \".\" or \"$INVERTDIR\" (\$INVERTDIR)."
		exit 1;
fi


#-------------------
# Check input files
#-------------------

if [ "$1" = "" ] ; then
		usage
		exit 0;
elif [ ! -f "$1" ] ; then
		echo "ERROR: Definitions file \"$1\" not found."
		exit 1;
fi

DEFFILE="$1"

MODELNAME=$(echo ${DEFFILE} | sed -e 's/\.[^.]*$//')


#------------------
# Observation file
#------------------

OBSFILE=$(gawk '/^ Observations file/ {	obsfile = $4; next }; END { print obsfile }' ${DEFFILE})

if [ ! -f "${OBSFILE}" ] ; then
		echo "ERROR: Observations file \"${OBSFILE}\" not found."
		exit 1;
fi

if [ ! -d "$OUTDIR" ]  ; then
		mkdir "$OUTDIR" || OUTDIR="."
fi

GPFILE="$OUTDIR/invert.plt"

#--------------------------
# Get range and data codes
#--------------------------

RANGE=($(LANG=C;gawk -f "$INVERTDIR/obsrange.awk" -v nxmin=${MINXMESH} -v nymin=${MINYMESH} ${OBSFILE}))

ICODE=0
while [ ${ICODE} -lt $((${#RANGE[*]} - 14)) ] ; do
		DATACODES[${ICODE}]=${RANGE[$((${ICODE}+14))]}
		ICODE=$((${ICODE}+1))
done

if [ ${#DATACODES[*]} -gt 1 ] ; then
		gawk -f "$INVERTDIR/splitcodes.awk" -v name="$OUTDIR/observations" ${OBSFILE}
fi


#-------------------
# Model effect file
#-------------------

MODFILE="${MODELNAME}.mod"
if [ ! -f "${MODELNAME}.mod" ] ; then
		echo "NOTE: Model file \"${MODELNAME}.mod\" not found."
		echo "      Append option \"o\" to \"Output of observation results\" to plot the model"
		echo "      effect."
		echo

		NOMODFILE=1

elif [ "${MODELNAME}.mod" -ot "${DEFFILE}" ] ; then
		echo "WARNING: Model file \"${MODELNAME}.mod\" older than \"${DEFFILE}\"."
		echo

fi

# Range and datacodes
if [ -z "${NOMODFILE}" ] ; then
		MODRANGE=($(LANG=C;gawk -f "$INVERTDIR/obsrange.awk" -v nxmin=${MINXMESH} -v nymin=${MINYMESH} "${MODELNAME}.mod"))

		if [ ${#DATACODES[*]} -gt 1 ] ; then
				gawk -f "$INVERTDIR/splitcodes.awk" -v name="$OUTDIR/modeleffect" "${MODELNAME}.mod"
		fi
fi


#----------------
# Residuals file
#----------------

RESFILE="${MODELNAME}.res"
if [ ! -f "${RESFILE}" ] ; then
		echo "NOTE: Residuals file \"${RESFILE}\" not found."
		echo "      Append option \"r\" to \"Output of observation results\" to plot residuals."
		echo

		NORESFILE=1

elif [ "${RESFILE}" -ot "${DEFFILE}" ] ; then
		echo "WARNING: Residuals file \"${RESFILE}\" older than \"${DEFFILE}\"."
		echo

fi

# Range and datacodes
if [ -z "${NORESFILE}" ] ; then
		RESRANGE=($(LANG=C;gawk -f "$INVERTDIR/obsrange.awk" -v nxmin=${MINXMESH} -v nymin=${MINYMESH} "${RESFILE}"))

		if [ ${#DATACODES[*]} -gt 1 ] ; then
				gawk -f "$INVERTDIR/splitcodes.awk" -v name="$OUTDIR/residuals" "${RESFILE}"
		fi
fi

#-----------
# Plot file
#-----------

PLTFILE="${MODELNAME}.plt"
if [ ! -f "${PLTFILE}" ] ; then
		echo "NOTE: Plot file \"${PLTFILE}\" not found."
		echo "      Append option \"M\" or \"m\" to \"Output in separate file\" to plot the model."
		echo

		NOPLTFILE=1

else
		if [ "${PLTFILE}" -ot "${DEFFILE}" ] ; then
				echo "WARNING: Plot file \"${PLTFILE}\" older than \"${DEFFILE}\"."
				echo
		fi


#----------------
# Parse plt-file
#----------------

		CONFIG=($(LANG=C;gawk -f "$INVERTDIR/plt2dat.awk" -v outdir="${OUTDIR}" -v dim=2 -v xmin=${RANGE[0]} -v xmax=${RANGE[1]} -v ymin=${RANGE[2]} -v ymax=${RANGE[3]} -v seed=${SEED} "${PLTFILE}"))

		LABELINCOUNT=${CONFIG[0]}
		LABELOUTCOUNT=${CONFIG[1]}
		SPHEREINCOUNT=${CONFIG[2]}
		SPHEREOUTCOUNT=${CONFIG[3]}
		PLATEINCOUNT=${CONFIG[4]}
		PLATEOUTCOUNT=${CONFIG[5]}
		PROFILEINCOUNT=${CONFIG[6]}
		PROFILEOUTCOUNT=${CONFIG[7]}
fi



#----------------------
# Loop over data codes
#----------------------

for CODE in ${DATACODES[*]} ; do


#-----------------
# Extract profile
#-----------------

#-------------------------
# Data is already profile
#-------------------------

		if [ ${#DATACODES[*]} -gt 1 ] ; then
				OBSFILE="${OUTDIR}/observations${CODE}.dat"
				MODFILE="${OUTDIR}/modeleffect${CODE}.dat"
				RESFILE="${OUTDIR}/residuals${CODE}.dat"

				if [ ! -f ${OBSFILE} ] ; then
						echo "ERROR: Incorrect data code splitting of observations."
						echo
						exit 1;
				fi

				if [ ! -f ${MODFILE} -o ${MODFILE} -ot ${OBSFILE} ] ; then
						echo "ERROR: Incorrect data code splitting of model effect."
						echo
						exit 1;
				fi

				if [ ! -f ${RESFILE} -o ${RESFILE} -ot ${OBSFILE} ] ; then
						echo "ERROR: Incorrect data code splitting of residuals."
						echo
						exit 1;
				fi
		fi

		TOPPROFFILE="${OBSFILE}"
		if [ -n "${NORESFILE}" ] ; then
				SPRIOPROFFILE="${OBSFILE}"
#   Account for possibly modified a-priori stdev.
		else
				SPRIOPROFFILE="${RESFILE}"
		fi
		SPOSTPROFFILE="${RESFILE}"
		OBSPROFFILE="${OBSFILE}"
		MODPROFFILE="${MODFILE}"
		RESPROFFILE="${RESFILE}"

		GINDEX=4
		SPRIOINDEX="(abs(\$5))"
		TINDEX=6
		SPOSTINDEX="(abs(\$8))"
		CHECK=""
		ISGRIDDED=0

		if isequal "${RANGE[2]}" "${RANGE[3]}" ; then
				INDEX=1
				OINDEX=2
		elif isequal "${RANGE[0]}" "${RANGE[1]}" ; then
				INDEX=2
				OINDEX=3

		else

#-------------------------------------------------------------------
# Data is map: perform gridding and prepare adapted "using" indexes
#-------------------------------------------------------------------

				ISGRIDDED=1

# Profile at given y-coordinate
				if [ "${Y}" != "" ] ; then
						INDEX=1
						OINDEX=2
						R=($(LANG=C;echo "${Y} ${RANGE[2]} ${RANGE[3]} ${RANGE[13]}" | gawk '{ d=($3-$2)/($4-1)/2; print $1-d,$1+d }' -))
						CHECK="check(a,b) = (a>=${R[0]} && a<${R[1]}) ? b : 1/0"
						GINDEX="(check(\$1,\$3))"
						SPRIOINDEX="(abs(check(\$1,\$3)))"
						TINDEX="(check(\$1,\$3))"
						SPOSTINDEX="(check(\$1,\$3))"
						DINDEX1=3
						DINDEX2=2

# Profile at given x-coordinate
				elif [ "${X}" != "" ] ; then
						INDEX=2
						OINDEX=2
						R=($(LANG=C;echo "${X} ${RANGE[0]} ${RANGE[1]} ${RANGE[12]}" | gawk '{ d=($3-$2)/($4-1)/2; print $1-d,$1+d }' -))
						CHECK="check(a,b) = (a>=${R[0]} && a<${R[1]}) ? b : 1/0"
						GINDEX="(check(\$1,\$3))"
						SPRIOINDEX="(abs(check(\$1,\$3)))"
						TINDEX="(check(\$1,\$3))"
						SPOSTINDEX="(check(\$1,\$3))"
						DINDEX1=2
						DINDEX2=3

# Profiles direction of longest extension
				else
						INDEX=($(LANG=C;echo "${RANGE[@]}" | gawk '{ dx= $2-$1; dy=$3-$2; print dx>=dy?1:2 }' -))
						OINDEX=2
						GINDEX=3
						SPRIOINDEX="(abs(\$3))"
						TINDEX=3
						SPOSTINDEX="(abs(\$3))"
						DINDEX1=$((4-${INDEX}))
						DINDEX2=$((${INDEX}+1))
				fi


				for TYPE in 6 5 4 3 2 1 ; do

# Topography
						if [ ${TYPE} -eq 6 ] ; then
								SCATFILE="${OBSFILE}"
								GRIDFILE="$OUTDIR/topprofile.dat"
								TOPPROFFILE="${GRIDFILE}"
								DINDEX3=6
								DRANGE=(${RANGE[8]} ${RANGE[9]})

# A-prio stdev
						elif [ ${TYPE} -eq 5 -a ${STDEV} -eq 1 ] ; then
								if [ -n "${NORESFILE}" ] ; then
										SCATFILE="${OBSFILE}"
#               Account for possibly modified a-priori stdev. 
								else
										SCATFILE="${RESFILE}" 
								fi
								GRIDFILE="$OUTDIR/sprioprofile.dat"
								SPRIOPROFFILE="${GRIDFILE}"
								DINDEX3="(abs(\$5))"
								DRANGE=(${RANGE[6]} ${RANGE[7]})

# A-post stdev
						elif [ ${TYPE} -eq 4 -a -z "${NORESFILE}" -a ${STDEV} -eq 1 ] ; then
								SCATFILE="${RESFILE}"
								GRIDFILE="$OUTDIR/spostprofile.dat"
								SPOSTPROFFILE="${GRIDFILE}"
								DINDEX3=8
								DRANGE=(${RESRANGE[10]} ${RESRANGE[11]})

# Observations
						elif [ ${TYPE} -eq 3 ] ; then
								SCATFILE="${OBSFILE}"
								GRIDFILE="$OUTDIR/obsprofile.dat"
								OBSPROFFILE="${GRIDFILE}"
								DINDEX3=4
								DRANGE=(${RANGE[4]} ${RANGE[5]})

# Model effect
						elif [ ${TYPE} -eq 2 -a -z "${NOMODFILE}" ] ; then
								SCATFILE="${MODFILE}"
								GRIDFILE="$OUTDIR/modprofile.dat"
								MODPROFFILE="${GRIDFILE}"
								DINDEX3=4
								DRANGE=(${MODRANGE[4]} ${MODRANGE[5]})

# Residuals
						elif [ ${TYPE} -eq 1 -a -z "${NORESFILE}" ] ; then
								SCATFILE="${RESFILE}"
								GRIDFILE="$OUTDIR/resprofile.dat"
								RESPROFFILE="${GRIDFILE}"
								DINDEX3=4
								DRANGE=(${MODRANGE[4]} ${MODRANGE[5]})
						else
								continue
						fi

						cat <<EOF > ${GPFILE}
set term table
set output "${GRIDFILE}"
set zrange [${DRANGE[0]}:${DRANGE[1]}]
set dgrid3d ${RANGE[13]},${RANGE[12]},${NORM}
EOF


#------------------------------
# Insert command line settings
#------------------------------

						if [ -n "${GRIDCMD}" ] ; then
								cat <<EOF >> ${GPFILE}
${GRIDCMD}
EOF
						fi

						cat <<EOF >> ${GPFILE}
splot "${SCATFILE}" using ${DINDEX1}:${DINDEX2}:${DINDEX3}
EOF


#------------------
# Perform gridding
#------------------

						if [ $ISWGNUPLOT == 0 ] ; then
								${GNUPLOT} ${GPFILE}
								FAILED=$?
						else
								${GNUPLOT} ${GPFILE} 2>"$OUTDIR/stderr.txt"
								FAILED=$?

# Ignore "Can't find the gnuplot window" warning of wgnuplot:
								if [ ${FAILED} -ne 0 ] ; then
										if [ -f "$OUTDIR/stderr.txt" ] && gawk "{ if (\$0 != \"Can't find the gnuplot window\") { exit 1 } }" "$OUTDIR/stderr.txt" ; then
												FAILED=0;
										fi
								fi
						fi

						if [ ${FAILED} -eq 1 ] ; then
								echo
								echo "ERROR: gridding failed."
								exit 1
						fi

				done

		fi


#--------------------
# Create plot script 
#--------------------

		cat <<EOF > ${GPFILE}
EOF

		if [ ${#DATACODES[*]} -gt 1 ] ; then
				DCEXT="_dc${CODE}"
				DCTITLE=" with data code ${CODE}"
		fi

		if [ ${PRINT} -eq 1 ] ; then
				cat <<EOF >> ${GPFILE}
set term postscript landscape enhanced color solid 10
set output "${MODELNAME}${DCEXT}_prf.ps"

EOF
		fi

		if [ "${Y}" != "" ] ; then
				cat <<EOF >> ${GPFILE}
set title "Model \"${MODELNAME}\"${DCTITLE} at Y=${Y}"

EOF
		elif [ "${X}" != "" ] ; then
				cat <<EOF >> ${GPFILE}
set title "Model \"${MODELNAME}\"${DCTITLE} at X=${X}"

EOF
		else
				cat <<EOF >> ${GPFILE}
set title "Model \"${MODELNAME}\"${DCTITLE}"

EOF
		fi


#--------------
# Gravity plot
#--------------

		if [ -z "${NOPLTFILE}" ] ; then
				cat <<EOF >> ${GPFILE}
set multiplot

set origin 0,0.48
set size 1,0.48

EOF
		fi


#------------------
# General settings 
#------------------

		if [ "${X11TERM}" = "yes" -a ${PRINT} -eq 0 ] ; then
				POINTSIZE="1"
		else
				POINTSIZE="0.5"
		fi

		if [ ${GNUPLOTVERSION[0]} -ge 4 -a ${GNUPLOTVERSION[1]} -ge 2 ] ; then
				LS4="lt 1 lw 1 lc rgb \"cyan\""
				LS5="lt 1 lw 1 lc rgb \"orange\""
		elif [ ${PRINT} -eq 1 ] ; then
				LS4="lt 5 lw 1"
				LS5="lt 8 lw 1"
		elif [ "${X11TERM}" = "yes" ] ; then
				LS4="lt 5 lw 1"
				LS5="lt 7 lw 1"
				LS5COLOR="-xrm gnuplot*line6Color:grey"
		elif [ ${ISWGNUPLOT} -eq 1 ] ; then
				LS4="lt 5"
				LS5="lt 6"
		else
				LS4="lt 5"
				LS5="lt 6"
		fi

		cat <<EOF >> ${GPFILE}
set xrange [] writeback
set lmargin 10
set rmargin 10
set xzeroaxis lt -1
set x2zeroaxis lt -1
set format x ""
set ytics nomirror
set ylabel "dg (obs,calc) [mGal]"
set y2tics
set y2label "dg (resid, st.dev) [mGal]"
set grid
EOF

		if [ ${ISWGNUPLOT} -eq 0 -o ${PRINT} -eq 1 ] ; then
				cat <<EOF >> ${GPFILE}
set key bottom

EOF
		else
				cat <<EOF >> ${GPFILE}
set key bottom outside

EOF
		fi


		cat <<EOF >> ${GPFILE}
set style line 1 lt 3 lw 1 pt 2 ps ${POINTSIZE}
set style line 2 lt 1 lw 3 pt 6 ps ${POINTSIZE}
set style line 3 lt 2 lw 1 pt 1 ps ${POINTSIZE}
set style line 4 ${LS4}
set style line 5 ${LS5}
set style line 6 lt 2 lw 1 pt 7 ps ${POINTSIZE}

${CHECK}

EOF


#------------------------------
# Insert command line settings
#------------------------------

		if [ -n "${DATACMD}" ] ; then
				cat <<EOF >> ${GPFILE}
${DATACMD}
EOF
		fi


#--------------------------------
# Compose curve plotting command
#--------------------------------

		if [ ${ISGRIDDED} -eq 0 ] ; then
				CURVEWITH="linespoints"
		else
				CURVEWITH="lines"
		fi

		cat <<EOF >> ${GPFILE}
plot \\
  1/0 with linespoints notitle, \\
EOF

		if [ ${STDEV} -eq 1 ] ; then
				if [ -z "${NORESFILE}" -a ${STDEV} -eq 1 ] ; then
						cat <<EOF >> ${GPFILE}
  "${SPRIOPROFFILE}" using ${OINDEX}:${SPRIOINDEX} axis x1y2 with lines ls 4 notitle, \\
  "${SPRIOPROFFILE}" using ${OINDEX}:(-${SPRIOINDEX}) axis x1y2 with lines ls 4 notitle, \\
EOF
						cat <<EOF >> ${GPFILE}
  "${SPOSTPROFFILE}" using ${OINDEX}:${SPOSTINDEX} axis x1y2 with lines ls 5 notitle, \\
  "${SPOSTPROFFILE}" using ${OINDEX}:(-${SPOSTINDEX}) axis x1y2 with lines ls 5 notitle, \\
EOF
				else
						cat <<EOF >> ${GPFILE}
  "${SPRIOPROFFILE}" using ${OINDEX}:(\$$GINDEX+${SPRIOINDEX}) with lines ls 4 notitle, \\
  "${SPRIOPROFFILE}" using ${OINDEX}:(\$$GINDEX-${SPRIOINDEX}) with lines ls 4 notitle, \\
EOF
				fi
		fi

		if [ -z "${NOMODFILE}" ] ; then
				cat <<EOF >> ${GPFILE}
  "${MODPROFFILE}" using ${OINDEX}:${GINDEX} with ${CURVEWITH} ls 2 notitle, \\
EOF
		fi

		cat <<EOF >> ${GPFILE}
  "${OBSPROFFILE}" using ${OINDEX}:${GINDEX} with ${CURVEWITH} ls 1 notitle, \\
EOF

		if [ -z "${NORESFILE}" ] ; then
				cat <<EOF >> ${GPFILE}
  "${RESPROFFILE}" using ${OINDEX}:${GINDEX} axis x1y2 with ${CURVEWITH} ls 3 notitle, \\
EOF
		fi

		cat <<EOF >> ${GPFILE}
  1/0 with lines ls 1 title "observed", \\
EOF

		if [ -z "${NOMODFILE}" ] ; then
				cat <<EOF >> ${GPFILE}
  1/0 with lines ls 2 title "calculated", \\
EOF
		fi

		if [ -z "${NORESFILE}" ] ; then
				cat <<EOF >> ${GPFILE}
  1/0 with lines ls 3 title "residuals", \\
EOF
		fi

		if [ ${STDEV} -eq 1 ] ; then
				cat <<EOF >> ${GPFILE}
  1/0 with lines ls 4 title "a-prio std.dev.", \\
  1/0 with lines ls 5 title "a-post std.dev.", \\
EOF
		fi 

		cat <<EOF >> ${GPFILE}
  1/0 notitle
EOF


#------------
# Model plot
#------------

#------------------
# General settings 
#------------------

		if [ -z "${NOPLTFILE}" ] ; then
				cat <<EOF >> ${GPFILE}

unset title
set origin 0,0
set xrange restore
set tmargin 0
set lmargin 10
set rmargin 10
set xzeroaxis lt -1
set x2zeroaxis lt -1
set format x "%g"
EOF

				if [ ${INDEX} -eq 1 ] ; then
						cat <<EOF >> ${GPFILE}
set xlabel "X [km]"
EOF
				else
						cat <<EOF >> ${GPFILE}
set xlabel "Y [km]"
EOF
				fi


				cat <<EOF >> ${GPFILE}
set ylabel "Z [km]"
set ytics mirror
unset y2tics
set y2label

xyselector=${INDEX}

EOF


#------------------------
# Load labeling commands
#------------------------

				if [ ${LABELINCOUNT} -gt 0 -a -f "$OUTDIR/labels_in.dat" ] ; then
						cat <<EOF >> ${GPFILE}
load "$OUTDIR/labels_in.dat"
EOF
				fi
				if [ ${LABELOUTCOUNT} -gt 0 -a -f "$OUTDIR/labels_out.dat" ] ; then
						cat <<EOF >> ${GPFILE}
load "$OUTDIR/labels_out.dat"
EOF
				fi


#------------------------------
# Insert command line settings
#------------------------------

				if [ -n "${MODELCMD}" ] ; then
						cat <<EOF >> ${GPFILE}
${MODELCMD}
EOF
				fi


#--------------------------------
# Compose curve plotting command
#--------------------------------

				cat <<EOF >> ${GPFILE}

plot \\
EOF


#--------------------
# Observation points
#--------------------

				cat <<EOF >> ${GPFILE}
  "${TOPPROFFILE}" using ${OINDEX}:${TINDEX} with ${CURVEWITH} ls 6 notitle, \\
EOF


#--------------
# Model bodies
#--------------

				if [ ${SPHEREOUTCOUNT} -gt 0 -a -f "$OUTDIR/spheres_out.dat" ] ; then
						cat <<EOF >> ${GPFILE}
  "$OUTDIR/spheres_out.dat" using ${INDEX}:3 with points pt 7 ps 2*${POINTSIZE} lt 1 notitle, \\
EOF
				fi
				if [ ${SPHEREINCOUNT} -gt 0 -a -f "$OUTDIR/spheres_in.dat" ] ; then
						cat <<EOF >> ${GPFILE}
  "$OUTDIR/spheres_in.dat" using ${INDEX}:3 with points pt 7 ps ${POINTSIZE} lt 3 notitle, \\
EOF
				fi

				if [ ${PLATEOUTCOUNT} -gt 0 -a -f "$OUTDIR/plates_in.dat" ] ; then
						cat <<EOF >> ${GPFILE}
  "$OUTDIR/plates_out.dat" using ${INDEX}:3 with lines lt 1 lw 3 notitle, \\
EOF
				fi
				if [ ${PLATEINCOUNT} -gt 0 -a -f "$OUTDIR/plates_in.dat" ] ; then
						cat <<EOF >> ${GPFILE}
  "$OUTDIR/plates_in.dat" using ${INDEX}:3 with lines lt 3 lw 1 notitle, \\
EOF
				fi

				if [ ${PROFILEOUTCOUNT} -gt 0 -a -f "$OUTDIR/profiles_in.dat" ] ; then
						cat <<EOF >> ${GPFILE}
  "$OUTDIR/profiles_out.dat" using ${INDEX}:3 with lines lt 1 lw 3 notitle, \\
EOF
				fi
				if [ ${PROFILEINCOUNT} -gt 0 -a -f "$OUTDIR/profiles_in.dat" ] ; then
						cat <<EOF >> ${GPFILE}
  "$OUTDIR/profiles_in.dat" using ${INDEX}:3 with lines lt 3 lw 1 notitle, \\
EOF
				fi


#---------------
# Create legend
#---------------

				if [ $((${SPHEREINCOUNT} + ${PLATEINCOUNT} + ${PROFILEINCOUNT})) -gt 0 ] ; then
						cat <<EOF >> ${GPFILE}
  1/0 with lines lt 3 lw 1 title "a-priori", \\
EOF
				fi
				if [ $((${SPHEREOUTCOUNT} + ${PLATEOUTCOUNT} + ${PROFILEOUTCOUNT})) -gt 0 ] ; then
						cat <<EOF >> ${GPFILE}
  1/0 with lines lt 1 lw 3 title "a-posteriori", \\
EOF
				fi

				if [ ${ISGRIDDED} -eq 0 ] ; then
						cat <<EOF >> ${GPFILE}
  1/0 with ${CURVEWITH} ls 6 title "data points", \\
EOF
				else
						cat <<EOF >> ${GPFILE}
  1/0 with ${CURVEWITH} ls 6 title "gridded data points", \\
EOF
				fi

				cat <<EOF >> ${GPFILE}
  1/0 notitle
EOF
		fi


#----------------------------------
# Finalize script and call gnuplot
#----------------------------------


		cat <<EOF >> ${GPFILE}

unset multiplot

EOF


#---------------------------------------
# Define shut down of gnuplot by hotkey
#---------------------------------------

# By gnuplot exit command
		if [ ${GNUPLOTVERSION[0]} -ge 4 -a ${GNUPLOTVERSION[1]} -ge 2 ] ; then
				cat <<EOF >> ${GPFILE}
bind x "exit gnuplot"
EOF

# By killing PPID from shell variable
		elif [ $($SHELL -c "echo $PPID") -eq $PPID ] 1>/dev/null 2>&1 ; then
				cat <<EOF >> ${GPFILE}
bind x "system \"kill \$PPID\" # (i.e. exit gnuplot)"
EOF

# By killing PPID from ps command
		elif [ $(ps -p $$ -o %P --no-header) -eq $PPID ] 1>/dev/null 2>&1 ; then
				cat <<EOF >> ${GPFILE}
bind x "system \"kill \`ps -p \$\$ -o %P --no-header\`\" # (i.e. exit gnuplot)"
EOF
		fi


		if [ ${SHOWBIND} -eq 1 ] ; then
				cat <<EOF >> ${GPFILE}
bind
EOF
		fi

		if [ ${PRINT} -eq 0 ] ; then
				cat <<EOF >> ${GPFILE}

print "This gnuplot instance controls the plot of:
print ""
print "     Profile of model \"${MODELNAME}\""
print ""
print "Press \"x\" in plot window or \"q\" here to close both windows."
print ""
EOF
		fi


#--------------
# Call gnuplot
#--------------

		if [ ${ISWGNUPLOT} -eq 0 ] ; then
				if [ ${PRINT} -eq 0 ] ; then
						cat <<EOF >> ${GPFILE}
pause -1
EOF

						if [ ${SHOWBIND} -eq 0 ] ; then
								xterm -iconic -e ${GNUPLOT} ${LS4COLOR} -persist ${GPFILE} &
						else
								xterm -e ${GNUPLOT} ${LS4COLOR} -persist ${GPFILE} &
						fi

				else
						${GNUPLOT} ${GPFILE}

				fi

		else
				if [ ${PRINT} -eq 0 ] ; then
						${GNUPLOT} -persist ${GPFILE} &

				else
						${GNUPLOT} ${GPFILE} &

				fi

		fi

		read -t 1 ANS  # necessary to avoid premature shut down of gnuplot.

done  # data codes