#!/bin/bash
set -e
set -x


InDir=.

ncks -h -O -4 ${InDir}/cerfacs_grids.nc cerfacs_grids_netcdf4.nc
ncks -4 -h -O -v nogh.lon,nogh.lat,nogh.clo,nogh.cla cerfacs_grids_netcdf4.nc ORCA025_coordinates_mask.nc
ncrename -h -v nogh.lon,nav_lon_grid_T    ORCA025_coordinates_mask.nc
ncrename -h -v nogh.lat,nav_lat_grid_T    ORCA025_coordinates_mask.nc
ncrename -h -v nogh.clo,bounds_lon_grid_T ORCA025_coordinates_mask.nc
ncrename -h -v nogh.cla,bounds_lat_grid_T ORCA025_coordinates_mask.nc

ncks -h -O -4 ${InDir}/cerfacs_masks.nc cerfacs_masks_netcdf4.nc
ncks -4 -h -A -v nogh.msk cerfacs_masks_netcdf4.nc ORCA025_coordinates_mask.nc
ncrename -h -v nogh.msk,mask_T    ORCA025_coordinates_mask.nc

ncks -h -O -4 ${InDir}/cerfacs_areas.nc cerfacs_areas_netcdf4.nc
ncks -4 -h -A -v nogh.srf cerfacs_areas_netcdf4.nc ORCA025_coordinates_mask.nc
ncrename -h -v nogh.srf,area      ORCA025_coordinates_mask.nc

ncatted -h \
	-a history,global,d,c,"" \
	-a history_of_appended_files,global,d,c,"" \
	ORCA025_coordinates_mask.nc

ncpdq -O -h --permute nj,ni,jpcr ORCA025_coordinates_mask.nc tmp_ORCA025_coordinates_mask.nc ; mv tmp_ORCA025_coordinates_mask.nc ORCA025_coordinates_mask.nc

ncrename -d jpcr,nvertex_grid_T ORCA025_coordinates_mask.nc
ncrename -d ni,x_grid_T         ORCA025_coordinates_mask.nc
ncrename -d nj,y_grid_T         ORCA025_coordinates_mask.nc

#ncks -4 -O -h ORCA025_coordinates_mask.nc tmp_ORCA025_coordinates_mask.nc ; mv tmp_ORCA025_coordinates_mask.nc ORCA025_coordinates_mask.nc

ncatted -h \
	-a bounds,nav_lon_grid_T,c,c,"bounds_lon_grid_T"  \
	-a bounds,nav_lat_grid_T,c,c,"bounds_lat_grid_T"  \
	-a units,nav_lon_grid_T,c,c,"degrees_east"        \
	-a standard_name,nav_lon_grid_T,c,c,"Longitude"   \
	-a long_name,nav_lon_grid_T,c,c,"Longitude"       \
	-a units,nav_lat_grid_T,c,c,"degrees_north"       \
	-a standard_name,nav_lat_grid_T,c,c,"Latitude"       \
	-a long_name,nav_lat_grid_T,c,c,"Latitude"           \
	-a long_name,area,c,c,"Grid area"                 \
	-a units,area,c,c,"m^2"                           \
	-a online_operation,area,c,c,"once"               \
	-a coordinates,area,c,c,"nav_lat_grid_T nav_lon_grid_T"     \
	ORCA025_coordinates_mask.nc

cat <<EOF > add_mask.nco
mask_T             = 1.0d - mask_T         ;
maskutil_T [y_grid_T,x_grid_T] = mask_T(:,:)           ;
maskutil_T  (   :  ,   0) = 0.0d           ;
maskutil_T  (   : , 1441) = 0.0d           ;
maskutil_T  ( 1049,  :  ) = 0.0d           ;
maskutil_T  ( 1048, 740:1441) = 0.0d       ;
EOF

ncap2 -O -h -S add_mask.nco ORCA025_coordinates_mask.nc tmp_ORCA025_coordinates_mask.nc  ; mv tmp_ORCA025_coordinates_mask.nc ORCA025_coordinates_mask.nc
ncatted -h \
	-a coordinates,mask_T,c,c,"nav_lat_grid_T nav_lon_grid_T"        \
	-a coordinates,maskutil_T,c,c,"nav_lat_grid_T nav_lon_grid_T"    \
	ORCA025_coordinates_mask.nc




