#!/bin/bash
export LANG=C
if [ $# -lt 1 ]; then
 echo "Use: $0 File.out [PES] [T]"
 exit
fi
Fout=$1
ItMax=`grep MAXCYC $Fout | tail -1 | awk '{print $3}'`
Nom=`grep PATHNAME $Fout | tail -1 | awk '{print $3}'`
PES=$2
Tgt=$3

WDir=`dirname $0`

NomGplot=${Nom}_m.gplot
yr="[-0.50:-0.42]"

if [ ! -s list ]; then
 echo "File list is missing"
 exit
fi
awk -f $WDir/Dep_tgt.awk $Fout 
cat <<EOF > $NomGplot
#!/usr/bin/gnuplot -persist
 set pointsize 2
 unset key
EOF
let ItM=ItMax-2
for i in `seq 0 $ItM`
  do
 xyz2scan ${Nom}_cart.${i} > /dev/null
 mv Scan.dat ${Nom}_${i}.dat
 cat <<EOF >>  $NomGplot
 set multiplot
 set origin 0.,0.
 set size 0.5,1.
 clear
 set xrange [1.:2.5]
 set yrange [-10:190]
 plot "HCN_irc.dat" u 1:3 w l ls 1
EOF
 if [ "$PES" != "" ]; then
  echo "replot \"HCN_PES_2D.dat\" u 1:2 t \"\" w l ls 2, \"HCN_PES_2D.dat\" u 1:(-\$2) t \"\"  w l ls 2,\"HCN_PES_2D.dat\" u 1:(360-\$2) t \"\"  w l ls 2" >> $NomGplot
 fi
 if [ -s ${Nom}_spline.${i} ]; then
 echo "replot \"${Nom}_${i}.dat\" u 1:3 w p ls 5" >> $NomGplot
 echo "replot \"${Nom}_spline.${i}\" u 2:4 w l ls 5" >> $NomGplot
 elif [  -s ${Nom}_dbgtgt_${i}.dat ]; then
 echo "replot \"${Nom}_${i}.dat\" u 1:3 w lp 5" >> $NomGplot
 echo "replot \"${Nom}_dbgtgt_${i}.dat\" u 2:(\$4*180./pi) w l ls 4" >> $NomGplot
 else
 echo "replot \"${Nom}_${i}.dat\" u 1:3 w lp ls 5" >> $NomGplot
fi
 if [ "$Tgt" != "" ]; then
  echo "replot \"${Nom}_tgt_${i}.dat\" u 1:3 w l ls 4" >> $NomGplot
 fi
 cat <<EOF >>  $NomGplot
 set origin .505,0.
# set size 0.5,1.
 clear
 set yrange $yr
 set xrange [-10:190]
EOF
 echo "plot \"${Nom}_${i}.dat\" u 3:4 t \"E\" w lp ls 1" >> $NomGplot
 echo "unset multiplot" >> $NomGplot
 echo "pause -1" >> $NomGplot
 done
let i=ItMax-1
 xyz2scan ${Nom}_cart.${i} > /dev/null
 mv Scan.dat ${Nom}_${i}.dat
 cat <<EOF >>  $NomGplot
 set multiplot
 set origin 0.,0.
# set size 0.5,1.
 clear
 set xrange [1.:2.5]
 set yrange [-10:190]
 plot "HCN_irc.dat" u 1:3 t "IRC" w l ls 1
EOF
 if [ "$PES" != "" ]; then
  echo "replot \"HCN_PES_2D.dat\" u 1:2 t \"\" w l ls 2, \"HCN_PES_2D.dat\" u 1:(-\$2) t \"\" w l ls 2,\"HCN_PES_2D.dat\" u 1:(360-\$2) t \"\" w l ls 2" >> $NomGplot
 fi
 if [ -s ${Nom}_spline.${i} ]; then
 echo "replot \"${Nom}_${i}.dat\" u 1:3 w p ls 5" >> $NomGplot
 echo "replot \"${Nom}_spline.${i}\" u 2:4 w l ls 5" >> $NomGplot
 elif [  -s ${Nom}_dbgtgt_${i}.dat ]; then
 echo "replot \"${Nom}_${i}.dat\" u 1:3 w lp ls 5" >> $NomGplot
 echo "replot \"${Nom}_dbgtgt_${i}.dat\" u 2:(\$4*180./pi) w l ls 4" >> $NomGplot
 else
 echo "replot \"${Nom}_${i}.dat\" u 1:3 w lp ls 5" >> $NomGplot
fi
 cat <<EOF >>  $NomGplot
 set origin .505,0.
# set size  0.5,1.
 clear
 set yrange $yr
 set xrange [-10:190]
EOF
 echo "plot \"${Nom}_${i}.dat\" u 3:4 t \"E\" w lp ls 1" >> $NomGplot
 echo "unset multiplot" >> $NomGplot
 echo "pause -1" >> $NomGplot

chmod u+x ./$NomGplot
echo "./$NomGplot      to see the path"
