#!/bin/bash

dom=o ; forcing=ERA-Interim  ; yb=1980 ; ye=1980

exeM=exeM

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

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

export OMP_NUM_THREADS=2
ulimit -s unlimited

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

netcdf () {

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

 ncatted -h -a institute,global,o,c,"Colorado State University" $file
 ncatted -h -a contact,global,o,c,"glen.liston@colostate.edu" $file
 ncatted -h -a model,global,o,c,"SNOWMODEL 5km" $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 frequency,global,o,c,"mon"  ${file}
 nccopy  -k 4 -d 2 -s ${file}  ${file}4
 mv                   ${file}4 ${file}
 fi
done

}

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

compile=y

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

rm -f $exeM  $exeY

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 ../*.cdf       . 
ln -sf ../*.nc         .

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

wait
