#!/usr/bin/bash
#
# Bash script to post-process files startphy_icosa.nc and start_icosa.nc
# generated by start_archive2icosa and create files
# start.nc and startphy.nc (usable as inputs for icosa_lmdz.exe)

# load nco module
module purge
# change to your LMDZ install dir or set "export LMDZ=/path/lmdz" in your .bashrc
LMDZ=${LMDZ:-../../..}
source $LMDZ/XIOS/arch.env
#module load nco/4.7.9-gcc-4.8.5-hdf5-1.8.18-openmpi-2.0.4 #Example of version of the module needed
module load nco


#conversion to netcdf 3 in order to rename and add variables, not properly done with netcdf4 files
nccopy -k 'classic' startfi_prefinalize.nc startphy_icosa_nc3.nc

# rename lat and lon variables as latitude and longitude and put result in
# file startphy.nc
ncrename -v lon,longitude -v lat,latitude -d cell,physical_points\
         startphy_icosa_nc3.nc startphy_nc3.nc
#Temporay soildepth array from Dynamico startphy_icosa_ref
ncks -A -v soildepth startphy_icosa_ref.nc startphy_nc3.nc #You have to adapt to your own path
# ncks -A -v subslope_dist startphy_icosa_ref.nc startphy_nc3.nc
# ncks -A -v def_slope startphy_icosa_ref.nc startphy_nc3.nc

nccopy -k 4 startphy_nc3.nc startfi.nc
#cp startfi.nc startfi_before_finalize.nc

#Temporary Time variable from start2archive; should be added with xios
ncks -O -x -v time_counter startfi.nc startfi.nc_tmp
#ncks -A -v Time start.nc startfi.nc_tmp
# ncks -A -v flux_geo startphy_icosa_ref.nc startfi.nc_tmp
# ncks -A -v wstar startphy_icosa_ref.nc startfi.nc_tmp
# ncks -A -v hmons startphy_icosa_ref.nc startfi.nc_tmp
# ncks -A -v summit startphy_icosa_ref.nc startfi.nc_tmp
# ncks -A -v base startphy_icosa_ref.nc startfi.nc_tmp
cp startfi.nc_tmp startfi.nc

#./rearrange_startphy.e > rearrange_startphy.out 2>&1

# make a proper start.nc file based on start_icosa.nc
cp start_icosa_prefinalize.nc start_icosa.nc

# add u,u_lat,u_lon,bounds_lat_u and bound_lon_u from start_icosa_ref.nc
ncks -A -v u,lon_u,lat_u,bounds_lon_u,bounds_lat_u \
     start_icosa_ref.nc start_icosa.nc
ncrename -d cell,cell_mesh \
         start_icosa.nc
ncrename -d nvertex,nvertex_mesh \
         start_icosa.nc
ncks -A -v xcell,ycell,zcell \
     start_icosa_ref.nc start_icosa.nc

#ncks -A -v q,nq start_icosa_ref.nc start_icosa.nc

#ncks -A -v latitude,longitude startphy_icosa_ref.nc startfi.nc
#ncks -A -v latitude,longitude startphy.nc startfi.nc
# In the current version of Dynamico, the variable q for tracer is needed but unused.
# To create this unused variable simply run this short python code

# cleanup
rm -rf startphy_icosa_nc3.nc startphy_nc3.nc startfi.nc_tmp

# copy icosa start files in icosa_starts folder
mkdir -p icosa_starts
mv start_icosa.nc icosa_starts/start.nc
mv startfi.nc icosa_starts/startfi.nc
