#!/bin/bash
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This script interpolates the erainterim forcing fields from the 1.5*1.5 grid
# to the ORCA1 grid.
# 
# History : Virginie Guemas - Initial version                         - 2012 
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#                                Arguments
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
year0=2012
yearf=2014
lstvars=( 't2' 'q2' 'precip' 'snow' 'qsw' 'qlw' )
lstmembs=( 0 )
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

set -evx

cp /cfu/pub/scripts/interpolation/scrip_use_extrap .

for ((year=${year0};year<=${yearf};year++)) ; do 

for memb in ${lstmembs[@]} ; do

for var in ${lstvars[@]} ; do

  case $var in
    'u10'|'v10') mid='_fc$'${memb}'_' ;;
    *) mid='_' ;;
  esac

  cp /cfu/scratch/vguemas/ERAint/${var}${mid}eraint_${year}.nc ${var}_eraint_${year}.nc
  case $var in 
    'u10'|'v10') ncpdq -O -U ${var}_eraint_${year}.nc ${var}_eraint_${year}.nc ;;
  esac
  case $var in
    't2'|'q2') nstep=1460 ; method='bicubic' ; filewgts='/cfu/pub/scripts/interpolation/weigths/rmp_ERAint_ocean_to_ORCA1t_v3.2_bicubic.nc' ;;
    'precip'|'snow') nstep=12; method='bicubic' ; filewgts='/cfu/pub/scripts/interpolation/weigths/rmp_ERAint_ocean_to_ORCA1t_v3.2_bicubic.nc' ;;
    'qsw'|'qlw') nstep=365; method='bicubic' ; filewgts='/cfu/pub/scripts/interpolation/weigths/rmp_ERAint_ocean_to_ORCA1t_v3.2_bicubic.nc' ;;
  esac
    
  cat > scrip_use_in <<EOF
&remap_inputs
    remap_wgt   = '${filewgts}'
    infile      = '${var}_eraint_${year}.nc'
    invertlat   = TRUE 
    var         = '${var}'
    fromregular = TRUE
    outfile     = '${var}_eraint_${year}_orca1.nc'
/
EOF
./scrip_use_extrap

rm -f ${var}_eraint_${year}.nc
ncks -O -v ${var} ${var}_eraint_${year}_orca1.nc ${var}_eraint_${year}_orca1.nc

done

done

done
rm -f scrip_use_in scrip_use_extrap
