#!/bin/bash

dom=o ; forcing=ERA-Interim  ; yb=1980 ; ye=1980
#dom=o ; forcing=ERA-40  ; yb=1971 ; ye=1978
MARv="3.9.5"

exeM=exeM
exeY=exeY

 opt="-ipo -traceback -mp1 -O3 -xSSE4.1"

 Dir=tmp_GR${dom}_${forcing}_${yb}_${ye}   

export OMP_NUM_THREADS=4
ulimit -s unlimited

##############################################################################

netcdf () {

for file in MARv*${1}*.nc ; do
if [ -f $file ] ; then
ferret <<EOF
use 1km-ISMIP6.nc	 
save/append/file=$file MAPPING
quit
EOF

 ncatted -h -a contact,global,o,c,"xavierfettweis@uliege.be" $file
 ncatted -h -a institute,global,o,c,"University of Liège (Belgium)" $file
 ncatted -h -a model,global,o,c,"regional climate model MARv$MARv" $file
 ncatted -h -a forcing,global,o,c,"$forcing" $file
 ncatted -h -a creation_date,global,o,c,`date "+%Y-%m-%d-T%H%M%SZ"`  ${file}
 ncatted -h -a project,global,o,c,"ISMIP6"  ${file}
 ncatted -h -a description,global,o,c,"Area scaling factor (af2) for ISMIP6 Greenland grid. Multiply with 2D data to correct the projection error. af2=(1/k)^2, where k is the map scale factor. Calculated after Snyder (1987) by Heiko Goelzer, IMAU, April 2018." ${file}
 nccopy  -k 4 -d 2 -s ${file}  ${file}4
 mv                   ${file}4 ${file}
 #scp ${file} climato.be:/ftp/fettweis/MARv3.9/
 fi
done

}

##############################################################################

compile=y

if [ $compile == "y" ] ; then

rm -f $exeM 

ifort -c -openmp $opt interpol_MARv3_to_1km_monthly.f90 -o interpol_MARv3_to_1km_monthly.o ; [ $? -ne 0 ] && exit
ifort -c -openmp $opt function.f90 -o function.o                                           ; [ $? -ne 0 ] && exit
ifort -c         $opt libUN.f -o libUN.o
ifort $opt -openmp interpol_MARv3_to_1km_monthly.o function.o libUN.o -lnetcdf_ifort -o  $exeM

rm -f *.o

fi


rm -rf "$Dir"
mkdir  "$Dir"
cd     "$Dir"

       
ln -sf ../$exeM        .
ln -sf ../index*.dat   .
ln -sf ../*.nc         .

for y in `seq $yb $ye` ; do
 echo "$y"        > interpol.dat
 echo "$dom"     >> interpol.dat
 echo "$forcing" >> interpol.dat
 export OMP_NUM_THREADS=4
 ./$exeM &
 wait
 netcdf $y &
done

wait
