#!/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

if [ -s ${Nom}_cart.0 ]; then
 Ext=_cart
elif [ -s ${Nom}.0 ]; then
 Ext=""
else
 echo "Cannot find ${Nom}.0 nor ${Nom}_cart.0 -- ERROR"
 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-1
for i in `seq 0 $ItM`
  do
 xyz2scan ${Nom}${Ext}.${i} > /dev/null
 mv Scan.dat ${Nom}_${i}.dat

if [ "$Ext" = "" ]; then
# We are analysing a calculation done in cartesian. 
# We have to  analyse the spline file and maybe also the tangent file.
 if [ -s ${Nom}_spline.${i} ]; then
   xyz2scan ${Nom}_spline.${i}  > /dev/null
   mv Scan.dat  ${Nom}_spline_${i}.dat
 fi
 if [  -s ${Nom}_dbgtgt.${i} ]; then
   xyz2scan ${Nom}_dbgtgt.${i}  > /dev/null
   mv Scan.dat  ${Nom}_dbgtgt_${i}.dat
 fi
fi
  
 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
cat <<EOF  >>  $NomGplot
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
EOF
 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 [-5:185]
 plot "HCN_irc.dat" u 3:4 t "IRC" w l ls 1
EOF
 echo "plot \"${Nom}_${i}.dat\" u 3:4 t \"E\" w lp ls 5" >> $NomGplot
 echo "unset multiplot" >> $NomGplot
 echo "pause -1" >> $NomGplot
 done

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


