#!/bin/ksh

set -vx

###########################################################################################
# ajoute_bord.py
###########################################################################################
# usage : 
# prompt> script_regrid restart_file_to_keep_the_grid.nc restart_file_to_get_the_values.nc

# example in ksh shell : 
# > script_regrid CM1414A_20001231_sechiba_rest.nc CM5PIRC11_29901231_sechiba_rest.nc > shell_test_script_regrid_SECHIBA 2>&1
###########################################################################################


PATH_FILE_IN_TO_GRID=$1
FILE_IN_TO_GRID=$( basename $1 )
DIR_IN_TO_GRID=$( dirname $1 )

PATH_FILE_IN_VALUES=$2
FILE_IN_VALUES=$( basename $2 )
DIR_IN_VALUES=$( dirname $2 )

if [ X${DIR_IN_TO_GRID} != X. ] ; then
    cp ${1} .
fi
if [ X${DIR_IN_VALUES} != X. ] ; then
    cp ${2} .
fi

# Add true CF convention compatible with CDAT cdms library 
# --------------------------------------------------------
CF_restart.py ${FILE_IN_TO_GRID}
CF_FILE_IN_TO_GRID=CF_${FILE_IN_TO_GRID}

CF_restart.py ${FILE_IN_VALUES}
CF_FILE_IN_VALUES=CF_${FILE_IN_VALUES}



# Interpol the CF restart
# -----------------------
# For SECHIBA restart files, we delete routing variables :
# 1) with restget calls order in the code :
# routingcounter,routingarea,routetogrid,routetobasin,basinid,topoindex,fastres,slowres,streamres,lakeres,
# previous_outflow,lakeinflow,returnflow,riverflow,coastalflow,hydrographs,
# runoff_route,drainage_route,evapot_route,precip_route,humrel_route,totnobio_route,vegtot_route 
# 2) with alphabetic order :
# basinid, coastalflow,
# drainage_route, evapot_route, fastres, humrel_route, hydrographs, lakeinflow, lakeres,
# precip_route, previous_outflow, returnflow, riverflow, routetobasin, routetogrid, routingarea,
# runoff_route, slowres, streamres, topoindex, totnobio_route, vegtot_route

restart_interpol.py ${CF_FILE_IN_TO_GRID} ${CF_FILE_IN_VALUES}
regrid_FILE_OUT=regrid_${CF_FILE_IN_VALUES}

# Change CF convention to restcom axes
# ------------------------------------
ncrename -d lat,y -d lon,x -d lev,z ${regrid_FILE_OUT}
ncks -O -a -x -v lat,lon,lev,bounds_lat,bounds_lon ${regrid_FILE_OUT} ${regrid_FILE_OUT}

# Name of the output file
# -----------------------
FILE_OUT=grille_${regrid_FILE_OUT}

# Correct mask of the output file
# -------------------------------
ajoute_bords.py ${FILE_IN_TO_GRID} ${regrid_FILE_OUT} ${FILE_OUT}

