#!/bin/bash
#######################################################################
#                          PLADPOP                                    #
# This shell script plots an adpop density file.                      #
# MRB 2005                                                            #
#######################################################################

#-----------------------------------------------------------------------
#  Definitions :
#-----------------------------------------------------------------------
if [ -d /tmpa ] && [ -w /tmpa ] ; then
   tmp="/tmpa"
elif [ -d /work ] && [ -w /work ] ; then
   tmp="/work"
elif [ -d /tmp ] && [ -w /tmp ] ; then
   tmp="/tmp"
elif [ -d "$HOME" ] && [ -w "$HOME" ] ; then
   tmp="$HOME"
else
   tmp="."
fi

n40='----------------------------------------'
gnuop=$tmp/gnu_options.${LOGNAME}_$$
gnuop2=$tmp/gnu_options2.${LOGNAME}_$$
gnuop3=$tmp/gnu_options3.${LOGNAME}_$$
gnupr=$tmp/gnu_print.${LOGNAME}_$$
lpr="no"
grid=0
logy=0
nomovie=-1
noweights=0
nw=""
state=1
xscale=0
yscale=0
not=0
inputl=$@

for option in $@; do
  if [ "$option" = "-P" ] ; then
    lpr="--"
  fi
done

purp="Purpose: Plot the data of an adpop file. (gnuplot wrapper)."
usage='Usage: pladpop [options] adpop-file [electronic state(s)]'
help1='-h     : print this help text.'
hlp1a='-a val : set lower range of x to val.'
help2='-x val : set upper range of x to val.'
help3='-y val : set upper range of y to val.'
hlp3a='-z val : set lower range of y to val.'
hlpsm='-s     : use smooth csplines (for 1D plot)'
hlpmo='-m     : graphs shown as movie (1 picture per second)'
hlpnw='-N     : plot without weights'
help4='-l     : use logarithmic y-scale (for 1D plots)'
help5='-G     : draw grid lines.'
hlp5a='-S     : surface on (only 2D plots)'
hlp6a='-n     : no titles, no keys.'
hlp6b='-t tit : title.'
hlp6c='-c     : copy gnuplot file to ./adp.pl, then run: gnuplot "adp.pl".'
hlp6d='-v     : verbose.'
help7='-p     : prompt for printing the plot at default printer lpr.'
help8='-P printer : specify alternative printer'
help9=' (e.g. -P "| lpr -Pps2"  or  -P file).'

#-----------------------------------------------------------------------
#  Read the options (if any).
#-----------------------------------------------------------------------

while getopts ":hlGSnscvNma:x:y:z:t:pP:" opt; do
    case $opt in
    h  ) echo "$purp"
         echo "$usage"
         echo "Options:"
         echo " $help1"
         echo " $hlp1a"
         echo " $help2"
         echo " $help3"
         echo " $hlp3a"
         echo " $hlpsm"
         echo " $hlpmo"
         echo " $hlpnw"
         echo " $help4"
         echo " $help5"
         echo " $hlp5a"
         echo " $hlp6a"
         echo " $hlp6b"
         echo " $hlp6c"
         echo " $hlp6d"
         echo " $help7"
         echo " $help8 $help9"
         echo ' Example: pladpop adp_dof'
         echo '          1D density of 1st electronic state is plotted,'
         echo '          dof must be replaced by the corresponding mode label.'
         echo '          The file adp_dof, created by adpop84, must exist.'
         echo "          ----------$n40"
         echo '          pladpop adp_dof 2 5'
         echo '          1D density of 2nd and 5th electronic states are plotted.'
         echo "          ----------$n40"
         echo '          pladpop -N adp_dof1_dof2 3'
         echo '          2D density for 3rd electronic state is shown without weights.'
         echo "$n40$n40"
         exit ;;
    a  ) ar=$OPTARG
         xscale=1;;
    m  ) nomovie=1 ;;
    N  ) noweights=1
         nw=" no weights" ;;
    n  ) not=1  ;;
    x  ) xr=$OPTARG
         xscale=1;;
    y  ) yr=`echo $OPTARG | tr 'd' 'e'`
         yscale=1;;
    z  ) zr=`echo $OPTARG | tr 'd' 'e'`
         yscale=1;;
    t  ) Title=$OPTARG ;;
    s  ) splines="smooth csplines" ;;
    l  ) logy=1 ;;
    G  ) grid=1 ;;
    S  ) surface=1 ;;
    c  ) copy=1 ;;
    v  ) verbose=1 ;;
    p  ) lpr="| lpr" ;;
    P  ) lpr=$OPTARG ;;
    \? ) echo ' Unkown option!'
         echo $usage
         echo ' -h provides a help text.'
         exit 1 ;;
  esac
done
shift $(($OPTIND - 1))

if [ -z "${lpr##-*}" ] ; then
  echo ' No printer specified with the -P option!'
  echo ' Example :  pladpop -P "| lpr -Pps2"  :  prints to ps2-printer.'
  echo ' Example :  pladpop -P prfile  :  writes postscript-output '\
                   'to the file "prfile".'
  echo
  echo "$usage "
  echo " $help1"
  echo " $hlp1b"
  echo " $hlp1a"
  echo " $help2"
  echo " $help3"
  echo " $hlp3a"
  echo " $hlpsm"
  echo " $hlpmo"
  echo " $hlpnw"
  echo " $help4"
  echo " $help5"
  echo " $hlp5a"
  echo " $hlp6a"
  echo " $hlp6b"
  echo " $hlp6c"
  echo " $hlp6d"
  echo " $help7"
  echo " $help8 $help9"
  exit 2
fi

if [ -z "$1" ] ; then
    echo "No argumets given! Try 'pladpop -h'."
    exit
fi

#-----------------------------------------------------------------------
#  Determine dimensionality of density file
#-----------------------------------------------------------------------
dimension=1

exec 4<&0 < $1
read line
read line
exec 0<&4 4<&-

modelabel1=`echo $line | cut -d " " -f2`
modelabel2=`echo $line | cut -d " " -f3`
modelabel3=`echo $line | cut -d " " -f4`

if [ $modelabel2 = "1" ] ; then
  if [ $modelabel2 = $modelabel3 ] ; then
    dimension=2
  fi
else
  dimension=2
fi

#-----------------------------------------------------------------------
#  Determine number of electronic states
#-----------------------------------------------------------------------

nstate=`echo $line | wc -w`
nstate=$(($nstate-1-$dimension))
nstate=$(($nstate/2))


if [ -n "$verbose" ]; then
   if [ $modelabel3 -eq 1 ]; then unset modelabel3; fi
   if [ $modelabel3 -eq 2 ]; then unset modelabel3; fi
   if [ $modelabel2 -eq 1 ]; then unset modelabel2; fi
   echo "$n40"
   echo "$0 $inputl"
   echo "Scratch file: $gnuop"
   echo "DOFs: $modelabel1  $modelabel2  $modelabel3"
   echo "Number of states = $nstate"
   echo "Dimension = $dimension"
fi

#-----------------------------------------------------------------------
#  Take adpop-file and shift to electronic states
#-----------------------------------------------------------------------
adpopfile=$1
shift 1

#-----------------------------------------------------------------------
#  Read the electronic states and create printline
#-----------------------------------------------------------------------
if [ $dimension -eq 1 ] ; then
  printline="plot"
  overlayplots=0
  while [ "$1" != "" ]
  do
   if [ $1 -gt $nstate ] ; then
     echo "Only $nstate electronic states, not $1!"
     exit 1
   fi
   state=$(($1+1))
   if [ -z "$nw" ] ; then
     state=$(($state+$nstate))
   fi
   overlayplots=$(($overlayplots+1))
   if [ $overlayplots -gt 1 ] ; then
     printline=`echo $printline,`
   fi
   if [ $not -eq 0 ] ; then
     title=`echo tit '"'State $1$nw'"'`
     printline=`echo $printline '"'-'"' using 1:$state $splines $title`
   else
     printline=`echo $printline '"'-'"' using 1:$state $splines notit`
   fi
   shift 1
  done

  if [ $overlayplots -eq 0 ] ; then
    overlayplots=1
    state=2
    if [ -z "$nw" ] ; then
      state=$(($state+$nstate))
    fi
    if [ $not -eq 0 ] ; then
      if [ "$title" = "" ] ; then
        title=`echo tit '"'State 1$nw'"'`
      fi
      printline=`echo $printline '"'-'"' using 1:$state $splines $title`
    else
      printline=`echo $printline '"'-'"' using 1:$state $splines notit`
    fi
  fi

  printline=`echo "$printline; pause $nomovie"`

  blockmul.pl $overlayplots $adpopfile > $gnuop3
else
  printline="splot"
  overlayplots=0
  while [ "$1" != "" ]
  do
   if [ $1 -gt $nstate ] ; then
     echo "Only $nstate electronic states, not $1!"
     exit 1
   fi
   state=$(($1+2))
   if [ -z "$nw" ] ; then
     state=$(($state+$nstate))
   fi
   overlayplots=$(($overlayplots+1))
   if [ $overlayplots -gt 1 ] ; then
     printline=`echo $printline,`
   fi
   if [ $not -eq 0 ] ; then
     title=`echo tit '"'State $1$nw'"'`
     printline=`echo $printline '"'-'"' using 1:2:$state $splines $title w l`
   else
     printline=`echo $printline '"'-'"' using 1:2:$state $splines notit w l`
   fi
   shift 1
  done

  if [ $overlayplots -eq 0 ] ; then
    overlayplots=1
    state=3
    if [ -z "$nw" ] ; then
      state=$(($state+$nstate))
    fi
    if [ $not -eq 0 ] ; then
      if [ "$title" = "" ] ; then
        title=`echo tit '"'State 1$nw'"'`
      fi
      printline=`echo $printline '"'-'"' using 1:2:$state $splines $title w l`
    else
      printline=`echo $printline '"'-'"' using 1:2:$state $splines notit w l`
    fi
  fi

  printline=`echo "$printline; pause $nomovie"`

  blockmul.pl $overlayplots $adpopfile > $gnuop3
fi

#-----------------------------------------------------------------------
#  Verbose, Plot warning
#-----------------------------------------------------------------------

if [ -n "$verbose" ]; then
   echo "$printline"
   echo "$n40"
fi
echo "Creating gnuplot file, this may take a while for large density files!"

#-----------------------------------------------------------------------
#  Write GNU options file.
#-----------------------------------------------------------------------
#  Dimension = 1
#-----------------------------------------------------------------------
if [ $dimension -eq 1 ] ; then
  unset surface
  echo 'set style data lines'      > $gnuop
  echo 'set xrange ['$ar':'$xr']' >> $gnuop
  echo 'set yrange ['$zr':'$yr']' >> $gnuop
  echo 'set xlabel "'$modelabel1'"' >> $gnuop

  if [ $not -eq 0 ] ; then
    if [ -n "$Title" ] ; then
      echo 'set title "'"$Title"'"' >> $gnuop
    else
      echo 'set title "1D density"' >> $gnuop
    fi
  fi

  if [ $logy -eq 1 ] ; then
    echo 'set logscale y'    >> $gnuop
  else
    echo 'set nologscale'    >> $gnuop
  fi

  if [ $grid -eq 1 ] ; then
    echo 'set grid'          >> $gnuop
  else
    echo 'set nogrid'        >> $gnuop
  fi

  cat $gnuop $gnuop3 > $gnuop2

  mv $gnuop2 $gnuop

if [ $not -eq 1 ]; then
  sed -e 's/\# Time step: *[0-9]*\.[0-9]* *$/set label "   &fs   " at graph 0\.90\,0\.95/' \
  -e 's/\# Time step: *//' $gnuop > $gnuop2
else
  sed -e 's/\# Time step: *[0-9]*\.[0-9]* *$/set label "   &fs   " at graph 0\.90\,1\.03/' \
  -e 's/\# Time step: *//' $gnuop > $gnuop2
fi
  sed '/#.*/d' $gnuop2 > $gnuop
  mv $gnuop $gnuop2
# changed, because sed of MAC-OS does not accept '\n' (newline)
# sed 's/^set label.*$/set nolabel\n&/' $gnuop2 > $gnuop
  sed 's/^set label.*$/set nolabel§&/' $gnuop2 | tr '§' '\n' > $gnuop
  mv $gnuop $gnuop2

# sed 's/^set label.*/&\n'"$printline"'/' $gnuop2 >$gnuop
  sed 's/^set label.*/&§'"$printline"'/' $gnuop2 | tr '§' '\n' >$gnuop

  /bin/rm -f $gnuop2
  /bin/rm -f $gnuop3

else

#-----------------------------------------------------------------------
#  Dimension = 2
#-----------------------------------------------------------------------
#  Determine minimum and maximum values for x and y
#-----------------------------------------------------------------------

  sed 's/^#.*//' $adpopfile > $gnuop
  sed 's/e .*/e/' $gnuop > $gnuop2
  sed '/^ *$/d' $gnuop2 > $gnuop

  exec 5<&0 < $gnuop
  read line1
  read line
  while [ "$line" != "e" ]
  do
    line2=$line
    read line
  done

  exec 0<&5 5<&-

  xmax=`echo $line1 | cut -d " " -f1`
  xmin=`echo $line2 | cut -d " " -f1`
  ymax=`echo $line1 | cut -d " " -f2`
  ymin=`echo $line2 | cut -d " " -f2`

  /bin/rm -f $gnuop
  /bin/rm -f $gnuop2

#-----------------------------------------------------------------------
#  writing file
#-----------------------------------------------------------------------

  echo 'set tics out'      > $gnuop

  if [ $not -eq 0 ] ; then
    if [ -n "$Title" ] ; then
      echo 'set title "'"$Title"'"' >> $gnuop
    else
      echo 'set title "2D density"' >> $gnuop
    fi
  fi

  if [ $grid -eq 1 ] ; then
    echo 'set grid'          >> $gnuop
  else
    echo 'set nogrid'        >> $gnuop
  fi

  echo 'set key top right outside'  >> $gnuop
  echo 'set contour'                >> $gnuop
  echo 'set clabel "%10.3e"'        >> $gnuop
  echo 'set size 0.9,1.09'          >> $gnuop
  echo 'set origin 0.,-0.05'        >> $gnuop

  if [ -n "$surface" ]; then
    echo 'set surface'              >> $gnuop
    echo 'set nohidden3d'           >> $gnuop
    echo 'set view 60.0, 30.0, 1.0, 1.0' >> $gnuop
    if [ $xscale -eq 1 ] ; then
      echo 'set xrange ['$ar':'$xr'] noreverse'       >> $gnuop
    else
      echo 'set xrange ['$xmin': '$xmax'] noreverse'  >> $gnuop
    fi
  else
    echo 'set nosurface'              >> $gnuop
    echo 'set view 180,180,1,1'       >> $gnuop
    if [ $xscale -eq 1 ] ; then
      echo 'set xrange ['$ar':'$xr'] reverse'       >> $gnuop
    else
      echo 'set xrange ['$xmin': '$xmax'] reverse'  >> $gnuop
    fi
  fi

  if [ $yscale -eq 1 ] ; then
    echo 'set yrange ['$zr':'$yr'] noreverse'       >> $gnuop
  else
    echo 'set yrange ['$ymin':'$ymax'] noreverse'   >> $gnuop
  fi

  echo 'set xlabel "'$modelabel1'"' >> $gnuop
  echo 'set ylabel "'$modelabel2'"' >> $gnuop
#  echo 'set zlabel "Density"'       >> $gnuop
  echo 'set cntrparam cubicspline'  >> $gnuop
  echo 'set cntrparam points 5'     >> $gnuop

  cat $gnuop $gnuop3 > $gnuop2

 if [ -n "$surface" ]; then
  sed -e 's/\# Time step: *[0-9]*\.[0-9]* *$/set label "   &fs   " at graph 0\.15\,2\.2/' \
  -e 's/\# Time step: *//' $gnuop2 > $gnuop
 else
  sed -e 's/\# Time step: *[0-9]*\.[0-9]* *$/set label "   &fs   " at graph 0\.5\,1\.1/' \
  -e 's/\# Time step: *//' $gnuop2 > $gnuop
 fi
  mv $gnuop $gnuop2

  sed '/#.*/d' $gnuop2 > $gnuop
  mv $gnuop $gnuop2
#  sed 's/^set label.*$/set nolabel\n&/' $gnuop2 > $gnuop
# changed, because sed of MAC-OS does not accept '\n' (newline)
  sed 's/^set label.*$/set nolabel§&/' $gnuop2 | tr '§' '\n' > $gnuop
  mv $gnuop $gnuop2

#  sed 's/^set label.*/&\n'"$printline"'/' $gnuop2 >$gnuop
  sed 's/^set label.*/&§'"$printline"'/' $gnuop2 | tr '§' '\n' >$gnuop

  /bin/rm -f $gnuop2
  /bin/rm -f $gnuop3

fi
#-----------------------------------------------------------------------
#  Call gnuplot.
#-----------------------------------------------------------------------
if [ -n "$copy" ]; then
   /bin/cp -f "$gnuop" $adpopfile.pl
   if [ -n "$verbose" ]; then
      echo "Plotdata written to file $adpopfile.pl"
   fi
fi
gnuplot -geometry +0+0 -persist "$gnuop"

if [ "$lpr" != "no" ] ; then
  echo ' Print the plot to "'$lpr'" ?   (y/n; return=no) '
  read print
  if [ ${print:-n} = 'y' ]  ; then
     echo 'set terminal postscript' >> $gnupr
     echo 'set output "'$lpr'" '    >> $gnupr
     gnuplot "$gnupr" "$gnuop"
     /bin/rm -f $gnupr
  fi
fi
/bin/rm -f $gnuop
/bin/rm -f $gnuop2
/bin/rm -f $gnuop3
exit

