#!/usr/bin/env bash

# set input/working/output folders
in=/Users/daniela/Desktop/scenario_001/files5s
work=/Users/daniela/Desktop/scenario_001/tmp
out=/Users/daniela/Desktop/scenario_001/out

# launching mirrors
mirror=( "USM" "LSM" )
r0=( 699.871 705.392 )
z0=( 441.441 417.821 )

# poloidal steering range
amin=20
amax=70

# check if working folder exists, otherwise create it
if [[ ! -e $work ]]; then
  mkdir $work
else
  if [[ ! -d $work ]]; then
    echo $work is not a folder.
    exit 1
  fi
fi
# move to working folder
cd $work
if [[ $? != 0 ]]; then
  echo Cannot move to $work
  exit 1
fi

# check if output folder exists, otherwise create it
if [[ ! -e $out ]]; then
  mkdir $out
else
  if [[ ! -d $out ]]; then
    echo $out is not a folder.
    exit 1
  fi
fi

#loop on USM/LSM mirrors
for i in 0 1; do
  #loop on beta
  for beta in 18 20 22; do
    # set output file names
    id="${mirror[i]}_${beta}"
    f7file=$out/f7_${id}.txt
    rm -f $out/log_${id}.txt
    # add header in output file
    echo "# =============================" > $f7file
    echo "# `date`" >> $f7file
    echo "# ${mirror[i]}: R0=${r0[i]} z0=${z0[i]}" >> $f7file
    echo "# beta=$beta" >> $f7file
    echo "# =============================" >> $f7file
    appendheader=0
    #loop on alpha
    for (( alpha=$amin; alpha<=$amax ; alpha=alpha+2 )); do
      #loop on time
      for eqfile in $in/*.eqdsk; do
        # look for time value in equil file
        base=`basename $eqfile .eqdsk`
        tstr=`echo $base | grep "[[:digit:]]\{5\}" -o`
        t=`echo "$tstr-10000" | bc`
        # copy input files in working folder
        cp $eqfile ${base}.eqdsk
        cp $in/${base}.prf ${base}.prf
        # replace dummy values in template for gray.data
        sed "s/-alfa-/$alpha/g; \
             s/-beta-/$beta/g; \
             s/-x0-/${r0[i]}/g; \
             s/-z0-/${z0[i]}/g; \
             s/-equil-/$base/g; \
             s/-prf-/$base/g" $in/gray0.data > gray.data
        # run gray
        gray >> $out/log_${id}.txt
        if (( $appendheader==0 )); then
          # append parameters to header if first run of the loop
          cat headers.txt >> $f7file
          echo "#t alpha`head -n 1 fort.7 | sed 's/#//'`" >> $f7file
          appendheader=1
        fi
        # add time and alpha values in first two columns
        awk 'NR>1 {print '$t','$alpha',$0}' fort.7 >> $f7file
        # remove files from working folder
        rm ${base}.eqdsk ${base}.prf fort.*
      done
      echo " " >> $f7file
    done
  done
done

#EOF