#!/bin/bash 
#
# This script runs the gaussian 1d pulse test case including and without
# refinement.
# It generates a reference solution on a fine level and fits the 
# two gaussian pulses to a reference function.
# This function is later used in runs as a reference to compare 
# against and to extract a l2norm
#
#

maxLevel=7  # up to which level?
minLevel=6 # minimum level
run=0      # actually perform runs?
run_reference=0 # run the reference run
run_comparison=1 # run the reference run
checkSchemes='singleLevel' # eqneq quadraticCompact'
simname=channel
clean=1
export OBSTACLE=0

seeder=$SEEDER
musubi="mpirun -np 1 $MUSUBI"

tmpfile='tmp.res'
rm $tmpfile

if [ $run -eq 1 ]; then
  # first clean up
  if [ $clean -eq 1 && $run -eq 1]; then
    echo '################## cleaning tracking folder'
    rm tracking/*
    mkdir tracking
    rm output/*
  fi

  if [ $run_reference -eq 1 ]; then
    # first set level to highest
    refinement=0
    export REFINEMENT=$refinement
    level=$maxLevel
    export LEVEL=$level
    echo '################## setting level to' $level
    # run seeder to generate the finest mesh
    $seeder
    # run musubi to get reference results 
    echo '################## running musubi  '
    $musubi

    # Get the reference file
    resFile=`ls tracking/*reference*pressCutX*.res`
    echo '################## getting reference file' $resFile
    echo '################## copying ' $resFile ' to refData.res'
    # Merge all results (of multiple processes) into one file
    cat $resFile > refData.res
    # and remove the commentary lines
    sed -i '/#/d' refData.res 

    # Fit the values from the reference run to a polynomial
    echo '################## Fit values '
    res="$(python ref/fitPoly.py)"
    echo '################## Result    ' $res
  fi
fi

if [ $run_comparison -eq 1 ]; then
  count=0
  for scheme in $checkSchemes; do
    count=$(($count+1))
    export INTERPOLATION_METHOD=$scheme
    echo '################## Setting interpolation method to' $scheme
    echo `echo $INTERPOLATION_METHOD`
      if [ $run -eq 1 ]; then
      # and now run the comparison runs with single Level
      echo '##################   ' 
      echo '################## Now do comparison runs for ' $scheme
      if [ "$scheme" = "singleLevel" ]; then
        refinement=0
      else 
        refinement=1
      fi
      export REFINEMENT=$refinement
      echo '################## Setting refinement globally to' $refinement
      echo `echo $REFINEMENT`

      level=$minLevel
      while [ $level -le $maxLevel ]
        do
          export LEVEL=$level
          echo '################## Running comparison runs with level' $level 'and scheme' $scheme
          echo `echo $LEVEL`
          $seeder
          $musubi
          level=$(($level+1))
        done
    fi

    for analysis in press vel; do
      if [ "$analysis" = "press" ]; then
        string='pressCutX'
        pos=1
      elif [ "$analysis" = "vel" ]; then
        string='velX'
        pos=2
      fi
      gnuplotfile="plot_${analysis}_${scheme}.gpl"
      echo '##################                 '
      echo '################## Spatial analysis                  '
      ############## Spatial analysis
      CMD="ls tracking/*${scheme}*${string}*.res"
      # assemble ls command
      echo command is $CMD
      # execute ls command and store into files
      files=$($CMD)
      echo Files $files
      echo 'set title "refinement study"' > $gnuplotfile
      echo 'plot \' >>$gnuplotfile

      nFiles=$($CMD | wc -l)
      echo '################## On files ' $nFiles
      iFile=0
      # Create GNUplot files
      for file in $files; do
        iFile=$((iFile+1))

        echo '################## current file ' $file
        level=`echo $file | awk 'gsub(/.*_l|_p000.*/,"")' `
        label=`echo $file | awk "gsub(/.*${simname}_|_${string}.*/,\"\")" `

        echo $file $level
        if [ $iFile -eq $nFiles ]; then
          suffix=''
        else
          suffix=', \'
        fi
        echo "\"$file\" u $pos:4 t \"$label L$level \"${suffix}" >> $gnuplotfile
      done

      echo 'pause -1' >>$gnuplotfile
    done
    echo '##################  Done writing gnuplot for spatial analysis.'
    echo '##################                 '
    echo '################## Error analysis                  '

    ############## Error analysis
    CMD="ls tracking/*$scheme*error*.res"
    files=$($CMD)
    ErrorData="plot_error_${scheme}.res"
    echo '# Error data          ' > $ErrorData
    # Create GNUplot files
    for file in $files; do
      level=`echo $file | awk 'gsub(/.*_l|_p000.*/,"")' `
      label=`echo $file | awk "gsub(/.*${simname}_|_error.*/,\"\")" `
      column=`awk '
      /^#      /{ for(i=1;i<=NF;i++){
        if ($i ~ "difference_red")
        {print i-1} }
      }' $file`
      error=`tail -n 1 $file | awk "{print \$ $column}" `
      echo file $file level $level in column $column found error $error
      # calculate the reference error
      refError=`echo 2^-$level | bc -l`
      echo $level     $error     $refError >> $ErrorData
    done

    # Generate reference solution
    if [ $count -eq 1 ]; then
      echo "\"$ErrorData\" u (2**\$1):(\$3/50) w lp t \"reference slope -2\"" >> $tmpfile
    fi  
    # and write line into the temp file 
    echo "\"$ErrorData\" u (2**\$1):2 w lp t \"${scheme}\"" >> $tmpfile
  done # Loop over comparison runs with refinement schemes


  nLines=$(wc -l < $tmpfile)
  ErrorGPL='plot_error.gpl'
  # Assemble the error plot
  echo 'set title "Error plot "' > $ErrorGPL
  echo 'set logscale x' >> $ErrorGPL
  echo 'set logscale y' >> $ErrorGPL
  echo 'set xlabel \"number of elements, resolution level\"' >> $ErrorGPL
  echo 'set ylabel \"absolute error\"' >> $ErrorGPL

  echo 'plot \' >> $ErrorGPL
  N=0
  while read LINE ; do
    N=$((N+1))
    if [ $N -eq $nLines ]; then
      suffix=''
    else
      suffix=', \'
    fi
    echo "$LINE" $suffix >> $ErrorGPL
  done < $tmpfile

  #finish the error plot
  echo 'pause -1' >>$ErrorGPL
  echo 'set terminal png' >>$ErrorGPL
  echo "'set output \"${ErrorGPL}.png\"" >>$ErrorGPL
  echo 'replot  ' >>$ErrorGPL
  rm $tmpfile
fi # run comparison

echo '################## FINISHED                        '
