#!/bin/bash
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This script interpolates and rotates the 10m zonal and meridional wind
# component to the ORCA1 grid from the output.grib coming from 
# download_u10v10.py.
#
# History : Virginie Guemas - Initial version                         - 2012 
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#                                Arguments
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
year='2014'
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

cdo -r -f nc copy output.grib u10v10_eraint_T255l.nc
ncecat -O u10v10_eraint_T255l.nc u10v10_eraint_T255l_bis.nc
ncpdq -O -h -a time,record u10v10_eraint_T255l_bis.nc u10v10_eraint_T255l_bis.nc
ncrename -d record,y -d rgrid,x u10v10_eraint_T255l_bis.nc
ncrename -v var165,u10 -v var166,v10 u10v10_eraint_T255l_bis.nc 
ncatted -a normalization,global,m,c,"none" /cfu/pub/scripts/interpolation/weights/remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc
ncatted -O -a map_method,global,m,c,"Distance weighted avg of nearest neighbors" remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc
ncatted -O -a conventions,global,m,c,"SCRIP" remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc
ncks -O -x -v src_grid_dims remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc
ncks -A -v src_grid_dims /cfu/pub/scripts/interpolation/weights/rmp_EC-Earth_T255l_to_T106_conserv.nc remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc

cat > scrip_use_in <<EOF
&remap_inputs
    remap_wgt   = 'remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc'
    infile      = 'u10v10_eraint_T255l_bis.nc'
    invertlat   = FALSE
    var         = 'u10'
    fromregular = FALSE
    outfile     = 'u10_eraint_orca1t_unrotated.nc'
/
EOF
cp /cfu/pub/scripts/interpolation/scrip_use scrip_use
./scrip_use

cat > scrip_use_in <<EOF
&remap_inputs
    remap_wgt   = 'remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc'
    infile      = 'u10v10_eraint_T255l_bis.nc'
    invertlat   = FALSE
    var         = 'v10'
    fromregular = FALSE
    outfile     = 'v10_eraint_orca1t_unrotated.nc'
/
EOF
./scrip_use

cat > namelist_rotateUVorca <<EOF
&nam_rotUV
  Ufilein   =  'u10_eraint_orca1t_unrotated.nc'
  Uvarin    =  'u10'
  Vfilein   =  'v10_eraint_orca1t_unrotated.nc'
  Vvarin    =  'v10'
  meshmask  =  '/cfu/autosubmit/con_files/mesh_mask_nemo.N3.2_O1L42.nc'
  Ufileout   =  'u10_eraint_${year}.nc'
  Vfileout   =  'v10_eraint_${year}.nc'
/
EOF
cp /cfu/pub/scripts/interpolation/rotateUVorca_orca1 rotateUVorca 
./rotateUVorca
rm -f u10v10_eraint_T255l.nc u10v10_eraint_T255l_bis.nc scrip_use scrip_use_in remap_255l_2_mask_to_orca1_z42_nomask_T_L1.nc rotateUVorca namelist_rotateUVorca u10_eraint_orca1t_unrotated.nc v10_eraint_orca1t_unrotated.nc 
