#!/bin/bash
export LC_ALL=C
echo ///////////////////////////////////////////
echo        Guessing S/N
echo ///////////////////////////////////////////
echo ' '
nsteps=10
repl=0
if [ "$#" -eq "1" ]
then
if [ "$1" != "-r" ]
then
nsteps=$1
else
repl=1
fi
fi
if [ "$#" -eq "2" ]
then
if [ "$1" != "-r" ]
then
nsteps=$1
repl=1
else
repl=1
nsteps=$2
fi
fi
cp ./input/param.par  ./input/param.par.ori
rm -f ./input/valatxy.coord.ori
mv -f ./input/valatxy.coord ./input/valatxy.coord.ori
rm -f ./output/gcv.dat
if [ -f ./meshgenwork/fort.22 ]
then 
echo ===========================================================================
echo Mesh files aready exist, hope they are correct: otherwise exectute divamesh
echo ===========================================================================
else
divamesh
fi
icont=1
ijm=0
gcv=$(head -24 ./input/param.par | tail -1 | awk '{print $1}')
while [ "$icont" -eq "1" ]
do
echo ' '
echo =============================================
echo Trying $gcv
echo =============================================
let ijm=$ijm+1
head -17 ./input/param.par.ori > bidon
echo 1 >> bidon
echo   >> bidon
echo 1 >> bidon
echo   >> bidon
echo -99 >> bidon
echo >> bidon
echo $gcv >> bidon
echo >> bidon
echo 0 >> bidon
mv bidon ./input/param.par
divacalc
FILENAME=./divawork/fort.27
{ 
read gcvval 
read snguess
read bb
read vbguess
read uu
read qguess
} < $FILENAME
########end testing
echo =============================================
echo New guess $snguess
echo =============================================
echo ' '
gcv=$snguess
if [ "$ijm" -ge "$nsteps" ]
then
icont=0
fi
ic=$(echo $qguess | awk '{if (($1-1)*($1-1) < 0.005) {print 0} else {print 1} }')
echo quality $qguess $ic
if [ "$ic" -eq "0" ]
then
icont=0
fi
if [ "$ijm" -ge "$nsteps" ]
then
icont=0
fi
if [ "$ijm" -le "2" ]
then
icont=1
fi
done
mv -f ./input/param.par.ori ./input/param.par
if [ -f ./input/valatxy.coord.ori ]
then
mv -f ./input/valatxy.coord.ori ./input/valatxy.coord
fi
echo -----------------------------------------------------
echo 'Creating adapted param.par in ./output/param.par.guess'
echo -----------------------------------------------------
head -23 ./input/param.par  > ./output/param.par.guess
head -2 ./divawork/fort.27 | tail -1 >> ./output/param.par.guess
head -25 ./input/param.par | tail -1 >> ./output/param.par.guess
head -4 ./divawork/fort.27  | tail -1 >> ./output/param.par.guess
if [ "$repl" == "1" ]
then
echo =======================================================
echo Replacing  param file with fit
cp -v ./input/param.par ./input/param.par.old
cp -v ./output/param.par.guess ./input/param.par
echo =======================================================
fi
