#!/bin/bash
### ===========================================================================
###
### Creates initial state for coupler, atmosphere side
### Takes state from atmospheric hist file
###
### ===========================================================================
##
##  Warning, to install, configure, run, use any of Olivier Marti's
##  software or to read the associated documentation you'll need at least
##  one (1) brain in a reasonably working order. Lack of this implement
##  will void any warranties (either express or implied).
##  O. Marti assumes no responsability for errors, omissions,
##  data loss, or any other consequences caused directly or indirectly by
##  the usage of his software by incorrectly or partially configured
##  personal.
##
###
### Documentation : https://forge.ipsl.jussieu.fr/igcmg/wiki/IPSLCM6/MOSAIX
###
## SVN information
#  $Author: omamce $
#  $Date: 2018-03-12 11:17:59 +0100 (Mon, 12 Mar 2018) $
#  $Revision: 3625 $
#  $Id: CreateRestartAtm4Oasis.bash 3625 2018-03-12 10:17:59Z omamce $
#  $HeadURL$

# Usage exemples :
# CreateRestartAtm4Oasis.bash --oce ORCA2.3 /ccc/store/cont003/dsm/p25sepul/IGCM_OUT/IPSLCM5A2/PROD/piControl/CM5A2.1.pi.00/ATM/Output/MO/CM5A2.1.pi.00_40100101_40191231_1M_histmth.nc
# CreateRestartAtm4Oasis.bash --oce ORCA2.3 /ccc/work/cont003/gencmip6/bedidil/SAVE8_ORCA2/STORE1/dynamico_grid.nc
# CreateRestartAtm4Oasis.bash --oce ORCA2.3 /ccc/work/cont003/gencmip6/bedidil/SAVE9_ORCA2_DYN30_1MO/STORE1/histmth.nc

## ===========================================================================
##
## You should not change anything below this line ....
##
## ===========================================================================

##
## Command line parameters
## ===========================================================================
# Default values
Comment="Preliminary attempt - Do not trust !"
OCE="Unknown"

#
# Defines computer
# ================
if [[ $(hostname) = curie* ]] ; then arch=curie ; center=tgcc ; fi
if [[ $(hostname) = irene* ]] ; then arch=irene ; center=tgcc ; fi

case ${arch} in
    ( curie | irene )
    set +vx
    module unload cdo nco ferret
    module unload netcdf hdf5
    module load python # /2.7.12
    module load netcdf/4.3.3.1_hdf5_parallel # Version for XIOS
    module load nco
    R_IN=$(ccc_home -u igcmg --cccwork)/IGCM
    TMPDIR=${SCRATCHDIR}/TMP
    SUBMIT_DIR=${BRIDGE_MSUB_PWD:-${SUBMIT_DIR}}
    ;;
    ( * )
    exit -1
    ;;
esac
set -o verbose
set -o xtrace
set -e

while [[ ${1} = -* ]] ; do
    case ${1} in
	( -- ) shift ; break ;;
	( -o   | --oce      ) shift ; OCE=${1}     ;; # Just needed to add information in the file and file name
	( -c   | --comment  ) shift ; Comment=${1} ;; # Just needed to add information in the file
	( -v | --verbose    ) set -o verbose         ;;
	( -x | --xtrace     ) set -o xtrace          ;;
	( -xv | -vx         ) set -o xtrace verbose  ;;
	( -e                ) set -e                 ;;
	( -V | --noverbose  ) set +o verbose         ;;
	( -X | --noxtrace   ) set +o xtrace          ;;
	( -XV | -VX         ) set +o xtrace verbose  ;;
	( -E                ) set +e                 ;;
	( -* ) echo ${Bold}"Unknown option : ${1}"${Norm} ; return 1 ;;
    esac
    shift
done

#AtmFile=${1:-/ccc/store/cont003/dsm/p25sepul/IGCM_OUT/IPSLCM5A2/PROD/piControl/CM5A2.1.pi.00/ATM/Output/MO/CM5A2.1.pi.00_40100101_40191231_1M_histmth.nc}
#AtmFile=${1:-/ccc/work/cont003/gencmip6/bedidil/SAVE8_ORCA2/STORE1/dynamico_grid.nc}
AtmFile=${1:-/ccc/work/cont003/gencmip6/bedidil/SAVE9_ORCA2_DYN30_1MO/STORE1/histmth.nc}

#
# Format for OASIS files : should be NetCDF3 classic or NetCDF3 64 bits
# ---------------------------------------------------------------------------
FL_FMT=64bit

##
## Extract variables
## ===========================================================================
ncks --overwrite --fl_fmt=${FL_FMT} --history -d time_counter,0,0 -v lon,lat,sols,soll,fract_oce,fract_sic,precip,snow,evap_sic,evap_oce,wind10m,taux_oce,tauy_oce,taux_sic,tauy_sic ${AtmFile} flxat_fields.nc
ncwa --overwrite --fl_fmt=${FL_FMT} --history -a time_counter flxat_fields.nc flxat_fields_notime.nc # remove time dimension 
ncatted --history --attribute history,global,d,c,""  flxat_fields_notime.nc          # cleaning of history attributes

##
## Determines if the file is unstructured (Dynamico) or lon/lat (LMDZ)
## Set atmosphere name
## ===========================================================================
Count=$(ncdump -h flxat_fields_notime.nc | grep nvertex | wc -l)
if [[ ${Count} -gt 0 ]] ; then
    IsUnstructured=yes
    dim_cell=$(ncdump -h flxat_fields_notime.nc |& grep "cell *=" | awk '{print $3}' ) # Get nominal DYNAMICO resolution (nbp parameter)
    ico_nbp=$( echo "sqrt(($dim_cell-2)/10)+1" | bc -l | sed 's/\..*//' )
    ATM=ICO${ico_nbp}
    ncrename --history -d cell,y flxat_fields_notime.nc
cat <<EOF > add_dim.nco
defdim("x",1) ;
lon      [y,x] = lon       ;
lat      [y,x] = lat       ;
sols     [y,x] = sols      ;
soll     [y,x] = soll      ;
fract_oce[y,x] = fract_oce ;
fract_sic[y,x] = fract_sic ;
precip   [y,x] = precip    ;
snow     [y,x] = snow      ;
evap_sic [y,x] = evap_sic  ;
evap_oce [y,x] = evap_oce  ;
wind10m  [y,x] = wind10m   ;
taux_oce [y,x] = taux_oce  ;
tauy_oce [y,x] = tauy_oce  ;
taux_sic [y,x] = taux_sic  ;
tauy_sic [y,x] = tauy_sic  ;
EOF
    ncap2 --history --overwrite --fl_fmt=${FL_FMT} -S add_dim.nco flxat_fields_notime.nc tmp_flxat_fields_notime.nc
    mv tmp_flxat_fields_notime.nc flxat_fields_notime.nc

cat<<EOF > lonlat2xyz.nco
// Value at North Pole for DYNAMICO grid 
where ( lat(:,:) >= 90.0d ) COTAUXXU = double(-tau_y) ;
where ( lat(:,:) >= 90.0d ) COTAUYYU = double( tau_x) ;
// Value at South Pole for DYNAMICO grid ?
EOF
else
    # lat/lon
    IsUnstructured=no
    dim_lat=$(ncdump -h flxat_fields_notime.nc | grep "lat *=" | awk '{print $3}' )
    dim_lon=$(ncdump -h flxat_fields_notime.nc | grep "lon *=" | awk '{print $3}' )
    ncrename --history -d lon,x flxat_fields_notime.nc
    ncrename --history -d lat,y flxat_fields_notime.nc
cat <<EOF > add_dim.nco
lon[y,x] = lon ;
lat[y,x] = lat ;
EOF
    ncap2 --history --overwrite --fl_fmt=${FL_FMT} -S add_dim.nco flxat_fields_notime.nc tmp_flxat_fields_notime.nc
    mv tmp_flxat_fields_notime.nc flxat_fields_notime.nc
    (( dim_lat = dim_lat - 1 ))
    #ATM=lmdz${dim_lon}x${dim_lat}
    ATM=LMD${dim_lon}${dim_lat}
    (( n_lat = dim_lat-1 ))
cat<<EOF > lonlat2xyz.nco
// Value at North Pole for LMDZ lon/lat grid
COTAUXXU(0,:) = double( -tau_x (0, 0) ) ;
COTAUYYU(0,:) = double( -tau_y (0, 0) ) ;
COTAUZZU(0,:) =  0.0d ; 
// Value at south Pole for LMDZ lon/lat grid ?
COTAUXXU(${n_lat},:) = double( -tau_x (${n_lat}, 0) ) ;
COTAUYYU(${n_lat},:) = double( -tau_y (${n_lat}, 0) ) ;
COTAUZZU(${n_lat},:) =  0.0d ; 
EOF

fi

echo "Version atmosphere : " ${ATM}


##
## Creates flxat file
## ===========================================================================

cat <<EOF > create_flxat.nco
//
*fract_oce_plus_sic  = double(fract_oce + fract_sic) ; // ocean fraction
*fract_oce_norm[y,x] = 0.0d ; fract_sic_norm[y,x] = 0.0d ; 
where (fract_oce_plus_sic >  0.0d ) *fract_oce_norm = double(fract_oce)/fract_oce_plus_sic ; // free ocean vs. total ocen fraction
where (fract_oce_plus_sic >  0.0d ) *fract_sic_norm = double(fract_sic)/fract_oce_plus_sic ; // sea ice vs. total ocean fraction
//
COTOTRAI[y,x] = double(precip-snow)    ;  //  Liquid precip
COTOTSNO[y,x] = double(snow)           ;  //  Solid precipitation
COTOTEVA[y,x] = double(evap_oce*fract_oce_norm + evap_sic*fract_sic_norm) ;
COICEVAP[y,x] = double(evap_sic(:,:))  ; // Evaporation on sea ice
COQSRMIX[y,x] = double(sols(:,:))      ; // Heat flux short wave
COQNSMIX[y,x] = double(soll(:,:))      ; // Heat flux minus short wave
COSHFICE[y,x] = double(sols(:,:))      ; // Heat flux short wave over sea ice
CONSFICE[y,x] = double(soll(:,:))      ; // Heat flux minus short wave over sea ice
CODFLXDT[y,x] = -20.0d       ; // W/m2 - dQ/dt
COCALVIN[y,x] =   0.0d       ; // Calving of icebergs, solid
COLIQRUN[y,x] =   0.0d       ; // River run-off , liquid
COWINDSP[y,x] = double( wind10m(:,:) ) ; // Wind speed at 10m high
COTAUMOD[y,x] =   0.0d                 ; // Wind stress modulus
// Wind stress
*tau_x[y,x] = double(taux_oce*fract_oce_norm + taux_sic*fract_sic_norm) ; 
*tau_y[y,x] = double(tauy_oce*fract_oce_norm + tauy_sic*fract_sic_norm) ;
COTAUMOD[y,x] = sqrt ( double(tau_x*tau_x + tau_y*tau_y) )  ; 
// Wind stress, from east/north components to geocentric
*rpi = acos (-1.0d) ;  *rad = rpi / 180.0d  ; 
COTAUXXU[y,x] = double( -tau_x(:,:) * sin(rad * lon(:,:)) - tau_y(:,:) * sin(rad * lat(:,:)) * cos(rad * lon(:,:)) ); 
COTAUYYU[y,x] = double(  tau_x(:,:) * cos(rad * lon(:,:)) - tau_y(:,:) * sin(rad * lat(:,:)) * sin(rad * lon(:,:)) );
COTAUZZU[y,x] = double(  tau_y(:,:) * cos(rad * lat(:,:)) ) ;
// Value at North Pole
#include "lonlat2xyz.nco"
//
COTAUXXV[y,x] = COTAUXXU(:,:) ;
COTAUYYV[y,x] = COTAUYYU(:,:) ;
COTAUZZV[y,x] = COTAUZZU(:,:) ;
//
EOF
ncap2 --overwrite --fl_fmt=${FL_FMT} -h -S create_flxat.nco flxat_fields_notime.nc tmp_flxat.nc
 
ncks --fl_fmt=${FL_FMT} --overwrite -h -v lon,lat tmp_flxat.nc flxat.nc
[[ ${IsUnstructured} = yes ]] && ncks --fl_fmt=${FL_FMT} --append -v bounds_lon,bounds_lat tmp_flxat.nc flxat.nc
ncks --fl_fmt=${FL_FMT} --append  -h -v COTAUXXU,COTAUYYU,COTAUZZU,COTAUXXV,COTAUYYV,COTAUZZV,COTOTRAI,COTOTSNO,COTOTEVA,COICEVAP,COQSRMIX,COQNSMIX,COSHFICE,CONSFICE,CODFLXDT,COCALVIN,COLIQRUN,COWINDSP,COTAUMOD tmp_flxat.nc flxat.nc

##
## Add some information in file headers
## ===========================================================================

UUID=$(uuid)
NCO="$(ncks --version |& tail -1|sed 's/ncks //')"
ncatted --history \
	--attribute nco_openmp_thread_number,global,d,,                       \
	--attribute source,global,o,c,"IPSL Earth system model"               \
	--attribute group,global,o,c,"ICMC IPSL Climate Modelling Center"     \
	--attribute Institution,global,o,c,"IPSL https://www.ipsl.fr"         \
	--attribute Model,global,o,c,"${ATM} http://lmdz.lmd.jussieu.fr"      \
	--attribute Ocean,global,o,c,"${OCE} https://www.nemo-ocean.eu"       \
	--attribute production,global,o,c,"$(finger ${LOGNAME} | head -1 | awk '{print $4, $5}')" \
	--attribute originalFiles,global,o,c,"${AtmFile}"                     \
	--attribute directory,global,o,c,"$(pwd)"                             \
	--attribute description,global,o,c,"Fields needed by OASIS-MCT"       \
	--attribute timeStamp,global,o,c,"$(date)"                            \
	--attribute Program,global,o,c,"Generated by ${0}"                    \
	--attribute uuid,global,o,c,"${UUID}"                                 \
	--attribute HOSTNAME,global,o,c,"$(hostname)"                         \
	--attribute LOGNAME,global,o,c,"$(whoami)"                            \
	--attribute NCO,global,o,c,"NCO netCDF Operator ${NCO} http://nco.sourceforge.net" \
	--attribute OS,global,o,c,"$(uname -o)"                               \
	--attribute release,global,o,c,"$(uname -r)"                          \
	--attribute hardware,global,o,c,"$(uname -i)"                         \
	--attribute directory,global,o,c,"$(pwd)"                             \
	--attribute Comment,global,o,c,"${Comment}"                           \
        --attribute Comment,global,o,c,"Preliminary attempt - Do not trust !" \
	--attribute SVN_Author,global,o,c,"$Author: omamce $"                 \
        --attribute SVN_Date,global,o,c,"$Date: 2018-03-12 11:17:59 +0100 (Mon, 12 Mar 2018) $"                            \
	--attribute SVN_Revision,global,o,c,"$Revision: 3625 $"               \
	--attribute SVN_Id,global,o,c,"$Id: CreateRestartAtm4Oasis.bash 3625 2018-03-12 10:17:59Z omamce $"                                \
	flxat.nc


##
## Creates other files
## ===========================================================================
mv flxat.nc flxat_${ATM}_maskFrom_${OCE}.nc
ncks -v COCALVIN flxat_${ATM}_maskFrom_${OCE}.nc icbrg_${ATM}_maskFrom_${OCE}.nc
ncks -v COCALVIN flxat_${ATM}_maskFrom_${OCE}.nc icshf_${ATM}_maskFrom_${OCE}.nc

##
## Cleaning
## ===========================================================================
rm -f flxat_fields.nc flxat_fields_notime.nc tmp_flxat.nc

## ===========================================================================
##
##                               That's all folk's !!!
##
## ===========================================================================
