#! /bin/bash
# Last edited on 2013-10-14 19:26:49 by stolfilocal

vnamex="$1"; shift       # Variable to plot on X axis
vnamey="$1"; shift       # Variable to plot on Y axis
eps_file="$1"; shift
dat_files=( "$@" )

tmp=/tmp/$$
colors=( ff0000 008800 0033ff 883300 005522 )

function evformula(){
  # Convert a variable name to its gnuplot formula.
  vname="$1"; shift
  if [[ "/${vname}" == "/rungs" ]]; then
    echo "column(1)";
  elif [[ "/${vname}" == "/span" ]]; then
    echo "column(2)";
  elif [[ "/${vname}" == "/EQL" ]]; then
    echo "column(3)";
  elif [[ "/${vname}" == "/DIF" ]]; then
    echo "column(4)";
  elif [[ "/${vname}" == "/BRK" ]]; then
    echo "column(5)";
  elif [[ "/${vname}" == "/SKP" ]]; then
    echo "column(6)";
  elif [[ "/${vname}" == "/PctSKP" ]]; then
    echo "column(6)/(column(2)+0.0)";
  else
    "** invalid variabe name \"${vname}\"" 1>&2; exit 1
  fi
}

exprx="`evformula ${vnamex}`"
expry="`evformula ${vnamey}`"

gpl_file=${tmp}.gpl
echo "gnuplot commands file = ${gpl_file}" 1>&2
rm -f ${gpl_file}

printf "set terminal postscript eps color enhanced 'TimesRoman' 8\n" >> ${gpl_file}
printf "set output '%s'\n" "${eps_file}" >> ${gpl_file}
printf "set xlabel '%s'\n" "${vnamex}" >> ${gpl_file}
printf "set ylabel '%s'\n" "${vnamey}" >> ${gpl_file}
printf "valx(dummy) = %s\n" "${exprx}" >> ${gpl_file}
printf "valy(dummy) = %s\n" "${expry}" >> ${gpl_file}
printf "plot" >> ${gpl_file}
sep=""

kfile=1
icolor=0
for dat_file in ${dat_files[@]}; do
  printf "%s \\\\\n" "${sep}" >> ${gpl_file}
  printf "  '%s' using (valx(0)):(valy(0)) title '%s' with points pt 7 lc rgb '#%s'" "${dat_file}" "${kfile}" "${colors[icolor]}" >> ${gpl_file}
  kfile=$(( kfile + 1 ))
  icolor=$(( icolor + 1 ))
  if [[ ${icolor} -ge ${#colors[@]} ]]; then icolor=0; fi
  sep=","
done
printf "\n" >> ${gpl_file}
printf "quit\n" >> ${gpl_file}

gnuplot < ${gpl_file}

rm -f ${gpl_file}


