#!/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
module load intel/17.0 openmpi/intel/2.0.1 hdf5/1.8.17 netcdf/4.4.0_fortran-4.4.2 nco/4.4.6

# cleanup
\rm -rf start.nc startphy.nc

nccopy -k 'classic' startphy_icosa.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,points_physiques \
ncrename -v lon,longitude -v lat,latitude -d cell,physical_points\
         startphy_icosa_nc3.nc startphy_nc3.nc
#Temporary added because program is not yet able to read topography
ncks -A -v albedodat,ZMEA,ZSTD,ZSIG,ZGAM,ZTHE \
         startphy_icosa_ref.nc startphy_nc3.nc
#Temporay soildepth array from Dynamico restartfi
ncks -A -v soildepth \
         ../lonlat_av_startfi/startfi0.nc startphy_nc3.nc

nccopy -k 'netCDF-4' startphy_nc3.nc startphy_new_rearrange.nc

#Temporary Time variable from start2archive; should be added with xios
ncks -A -v Time \
         start_archive_nc4.nc startphy_new_rearrange.nc

rearrange_startphy > rearrange_startphy.out 2>&1

# make a proper start.nc file based on start_icosa.nc
cp start_icosa.nc start.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.nc
#ncrename -v lon,lon_mesh -v lat,lat_mesh -v bounds_lon,bounds_lon_mesh -v bounds_lat,bounds_lat_mesh \
#         start.nc
ncrename -d cell,cell_mesh \
         start.nc
ncrename -d nvertex,nvertex_mesh \
         start.nc
ncks -A -v xcell,ycell,zcell \
     start_icosa_ref.nc start.nc
