#!/bin/bash



export LC_ALL=C



# Read parameters
datafile=./input/data.dat
Filepar=./input/param.par
{
read linecomment
read lc
read linecomment2
read icoordchange
read linecomment3
read ispec
read linecomment4
read ireg
read linecomment5
read xori
read linecomment6
read yori
read linecomment7
read dx
read linecomment8
read dy
read linecomment9
read nx
read linecomment10
read ny
read linecomment11
read valex
read linecomment12
read snr
read linecomment13
read varbak
} < $Filepar


# Save original input data and output
if [ -d ./workexerr ]
then
echo cleaning up workexerr
rm -R -f ./workexerr/*
else
mkdir -v ./workexerr
fi

# For the moment full copy  could be  more selective 
cp -R ./output ./workexerr

cp ./input/param.par ./input/param.par.nocpme


# Run diva with ireg=1; very high SN and no error calculation
# adapt param

echo $lc
lcerr=$(echo $lc | awk '{print $1/1.68537}')

echo $lcerr
# no new mesh until really need to be fine ?
# divamesh

echo $linecomment > ./input/param.par
echo $lcerr  >> ./input/param.par
echo $linecomment2 >> ./input/param.par
echo $icoordchange >> ./input/param.par
echo $linecomment3 >> ./input/param.par
echo 17 >> ./input/param.par
echo $linecomment4 >> ./input/param.par
echo $ireg >> ./input/param.par
echo $linecomment5 >> ./input/param.par
echo $xori >> ./input/param.par
echo $linecomment6 >> ./input/param.par
echo $yori >> ./input/param.par
echo $linecomment7 >> ./input/param.par
echo $dx >> ./input/param.par
echo $linecomment8 >> ./input/param.par
echo $dy >> ./input/param.par
echo $linecomment9 >> ./input/param.par
echo $nx >> ./input/param.par
echo $linecomment10 >> ./input/param.par
echo $ny >> ./input/param.par
echo $linecomment11 >> ./input/param.par
echo $valex >> ./input/param.par
echo $linecomment12 >> ./input/param.par
echo $snr >> ./input/param.par
echo $linecomment13 >> ./input/param.par
echo $varbak >> ./input/param.par

divacalc




# rename analysis related fields to error related fields and move them into the saved original ouput
cp ./output/errorfieldgher.anl ./workexerr/output/errorfieldgher.anl
cp ./output/errorfieldascii.anl ./workexerr/output/errorfieldascii.anl
cp ./output/erroratdatapoint.anl ./workexerr/output/erroratdatapoint.anl
cp ./output/erroratxyascii.anl ./workexerr/output/erroratxyascii.anl 

# Restore output and input and clean up the mess
rm -R ./output/*
cp -R ./workexerr/output/* ./output
mv ./input/param.par.nocpme ./input/param.par
rm -R ./workexerr/*


echo Merging into netcdf file
cp ./output/fieldgher.anl ./output/ghertonetcdf/fort.84
cp ./output/errorfieldgher.anl ./output/ghertonetcdf/fort.87
cd ./output/ghertonetcdf
../../../bin/netcdfoutput.a 
cd ../..
echo  ===== Finished divaexerr ======

#--------------------------------------------------