#!/bin/ksh
#-----------------------------------------------------------------
function OCE_Initialize
{
    IGCM_debug_PushStack "OCE_Initialize"

    JOB_NAME=${config_UserChoices_JobName}

    RESOL_OCE_ICE=$( echo ${RESOL} | awk "-Fx" '{print $1}' )
    case ${RESOL_OCE_ICE} in
	( *LIM2* ) SEAICE_MODEL=LIM2 ; 	LIM_VERSION=2 ;;
	( *LIM3* ) SEAICE_MODEL=LIM3 ; 	LIM_VERSION=3 ;;
	( *CICE* ) SEAICE_MODEL=CICE                  ;;
	( *      ) SEAICE_MODEL=UNKNOWN               ;;
    esac
    RESOL_OCE=$( echo ${RESOL_OCE_ICE} | sed "s/${SEAICE_MODEL}//" )

    IGCM_debug_Print 1 "RESOL          : ${RESOL}"
    IGCM_debug_Print 1 "RESOL_OCE_ICE  : ${RESOL_OCE_ICE}"
    IGCM_debug_Print 1 "SEAICE_MODEL   : ${SEAICE_MODEL}"
    IGCM_debug_Print 1 "LIM_VERSION    : ${LIM_VERSION}"
    IGCM_debug_Print 1 "RESOL_OCE      : ${RESOL_OCE}"

    # Local function to find namelists parameters
    #supergrep () { grep "^ *$1 *=" $2 | sed -e "s% *\!.*%%" ; }
    supergrep () { grep "^ *$1 *=" $2 | sed -e "s% *\!.*%%" -e "s%^ *$1 *=%%" ; }
    ##--Variables used by OPA --
    NAMELIST_OPA_CFG=${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE}_cfg
    IGCM_debug_Print 1 "namelist_cfg : ${NAMELIST_OPA_CFG}"
    if [ ! -r ${NAMELIST_OPA_CFG} ] ; then
        IGCM_debug_Exit "${NAMELIST_OPA_CFG} not found"
	IGCM_debug_Verif_Exit
    fi
    OPA_RDT=$(       supergrep rn_rdt        ${NAMELIST_OPA_CFG} )
    OPA_NN_FSBC=$(   supergrep nn_fsbc       ${NAMELIST_OPA_CFG} )
    #
    # OPA_RDT=$(       supergrep rn_rdt        namelist_cfg )
    # OPA_NN_FSBC=$(   supergrep nn_fsbc       namelist_cfg )
    (( OPA_NPDT_JOUR  =  86400 / OPA_RDT        ))
    (( OPA_RDT_SBC    =  OPA_RDT * OPA_NN_FSBC ))
 
    # Period Length In Days between DateBegin and first day of calendar 0001 01 01
    # /!\ Needed by OPA namelist to compute file names /!\
    (( DaysSinceJC = $( IGCM_date_DaysSinceJC ${DateBegin} ) + 1 ))

    IGCM_debug_Print 1 " "
    IGCM_debug_Print 1 "OPA_RDT        ${OPA_RDT}"
    IGCM_debug_Print 1 "OPA_NN_FSBC    ${OPA_NN_FSBC}"
    IGCM_debug_Print 1 "OPA_RDT_SBC    ${OPA_RDT_SBC}"
    IGCM_debug_Print 1 "OPA_NPDT_JOUR  ${OPA_NPDT_JOUR}"
    IGCM_debug_Print 1 "DaysSinceJC    ${DaysSinceJC}"

    ## Check that nn_fsbc is correct compare to coupling frequency
    FreqCoupling=${oasis_UserChoices_FreqCoupling:-86400}
    
    ## This informations are used for diaptr, trends and diagap files
    ## only the first frequency is used for this files
    
    IGCM_debug_Print 1 "FreqCoupling    ${FreqCoupling}"
    IGCM_debug_Print 1 "OPA_NN_FSBC    ${OPA_NN_FSBC}"
    IGCM_debug_Print 1 "OPA_RDT        ${OPA_RDT}"
    IGCM_debug_Print 1 "OPA_RDT_SBC    ${OPA_RDT_SBC}"
    
    if [[ ${OPA_RDT_SBC} -gt ${FreqCoupling} ]] ; then
	IGCM_debug_Exit "OPA_RDT_SBC=${OPA_RDT_SBC} is greater than FreqCoupling=${FreqCoupling}"
     	IGCM_debug_Verif_Exit
    fi
    
    IGCM_debug_PopStack "OCE_Initialize"
   
}

#-----------------------------------------------------------------
function OCE_Update
{
    IGCM_debug_PushStack "OCE_Update"
  
    ##--Write Frequency for iomput
    ## Differents frequencies are allowed for grid_[TUVW] and icemod files

    V1D_ENABLE=".FALSE."
    V1M_ENABLE=".FALSE."
    V1Y_ENABLE=".FALSE."

    for frequency in ${config_OCE_WriteFrequency} ; do
        case ${frequency} in
            ( 1D|1d ) V1D_ENABLE=".TRUE." ;;
            ( 1M|1m ) V1M_ENABLE=".TRUE." ;;
            ( *[yY] ) V1Y_ENABLE=".TRUE." ;;
        esac
    done

    ##-- Output level : 3 for more 1D variables
    eval opa9_OUTPUT_LEVEL=\${opa9_UserChoices_OUTPUT_LEVEL} > /dev/null 2>&1
    OUTPUT_LEVEL=${opa9_OUTPUT_LEVEL}

    # Period Length In Days between DateBegin and first day of calendar 0001 01 01
    # Needed by OPA namelist to compute correct file names 
    (( PeriodDaysSinceJC =  $( IGCM_date_DaysSinceJC ${PeriodDateBegin} ) + 1  ))

    ##-- Number of time steps updated : the first, the last and the number of time steps
    (( OPA_NIT000 = ( PeriodDaysSinceJC - DaysSinceJC ) * OPA_NPDT_JOUR + 1 ))
    (( OPA_NPDT   = PeriodLengthInDays * OPA_NPDT_JOUR ))
    (( OPA_NITEND = OPA_NIT000 + OPA_NPDT - 1))

    ##-- We force one restart file at the end of the trunk
    OPA_NSTOCK="${OPA_NITEND}"

    ##-- Restart configuration
    if ( [ "${CumulPeriod}" -eq 1 ] && [ "${config_OCE_Restart}" = "n" ] ) ; then
	OPA_LRSTAR=.FALSE.
	OPA_NRSTDT=0
        # Put OPA_NMSH=0 when OPA running in parallel mode
	OPA_NMSH=1
	#echo "NO OPA RESTART"
    elif ( [ "${CumulPeriod}" -eq 1 ] && [ "${config_OCE_Restart}" = "y" ] ) ; then
	OPA_LRSTAR=.TRUE.
	OPA_NRSTDT=0
	OPA_NMSH=1
	#echo "OPA RESTART"
    else
	OPA_LRSTAR=.TRUE.
	OPA_NRSTDT=2
	OPA_NMSH=0
	#echo "OPA RESTART"
    fi

    ##-- Meshmask option
    IGCM_card_DefineVariableFromOption ${SUBMIT_DIR}/COMP/opa9.card UserChoices mesh_mask

    if [ "${opa9_UserChoices_mesh_mask}" = "y" ]; then
        OPA_NMSH=1
        IGCM_card_WriteOption ${SUBMIT_DIR}/COMP/opa9.card UserChoices mesh_mask "n"
    fi

    # nleapy configuration
    case ${config_UserChoices_CalendarType} in
        ( leap|gregorian) OPA_NLEAPY=1  ;;
        ( noleap        ) OPA_NLEAPY=0  ;;
        ( 360d          ) OPA_NLEAPY=30 ;;
        ( *             ) OPA_NLEAPY=30 ;;
    esac

    typeset -r PRECIS=8
    NEMO_END=$( echo $( awk "BEGIN { printf \"%0${PRECIS}d\",${OPA_NITEND} }" ) ) 

    IGCM_comp_modifyNamelist blocker    namelist_cfg cn_exp    ${config_UserChoices_JobName}
    IGCM_comp_modifyNamelist blocker    namelist_cfg nn_it000  ${OPA_NIT000}
    IGCM_comp_modifyNamelist blocker    namelist_cfg nn_itend  ${OPA_NITEND}
    IGCM_comp_modifyNamelist blocker    namelist_cfg ln_rstart ${OPA_LRSTAR}
    IGCM_comp_modifyNamelist blocker    namelist_cfg nn_stock  ${OPA_NSTOCK}
    IGCM_comp_modifyNamelist blocker    namelist_cfg nn_rstctl ${OPA_NRSTDT}
    IGCM_comp_modifyNamelist blocker    namelist_cfg nn_date0  ${PeriodDateBegin}
    IGCM_comp_modifyNamelist nonblocker namelist_cfg nn_msh    ${OPA_NMSH}
    IGCM_comp_modifyNamelist nonblocker namelist_cfg nn_rnf_depth_file  ${OPA_NMSH}
    IGCM_comp_modifyNamelist blocker    namelist_cfg nn_leapy  ${OPA_NLEAPY}
    
    # Update iodef.xml

    IGCM_debug_Print 1 'Informations into iodef.xml : V1D_ENABLE V1M_ENABLE V1Y_ENABLE OUTPUT_LEVEL'
    IGCM_debug_Print 1 ${V1D_ENABLE} ${V1M_ENABLE} ${V1Y_ENABLE} ${OUTPUT_LEVEL}

    IGCM_comp_modifyXmlFile nonblocker file_def_nemo.xml 1d enabled ${V1D_ENABLE}
    IGCM_comp_modifyXmlFile nonblocker file_def_nemo.xml 1m enabled ${V1M_ENABLE}
    IGCM_comp_modifyXmlFile nonblocker file_def_nemo.xml 1y enabled ${V1Y_ENABLE}
	
    # vargas/titane/MPP and switch from 1 proc to 5 procs. We need to suppres restartopa the second month, if restartopa_0000 exist
    # same thing for restart_trc and restart_ice_in

    for restartfilenemo in restartopa restart_trc restart_ice_in ; do
      [ -f ${restartfilenemo}.nc ] && [ -f ${restartfilenemo}_0000.nc ] && IGCM_sys_Rm -f ${restartfilenemo}.nc
    done

    # Add include of nemo context in iodef.xml
    # In iodef.xml add on next line after "COMPONENT CONTEXT"
    #  <context id="nemo" src="./context_nemo.xml"/>
    echo '<context id="nemo" src="./context_nemo.xml"/>' > add.tmp
    cp iodef.xml iodef.xml.tmp
    sed -e "/COMPONENT CONTEXT/r add.tmp" \
        iodef.xml.tmp > iodef.xml
    rm iodef.xml.tmp add.tmp

    IGCM_debug_PopStack "OCE_Update"
}

#-----------------------------------
function OCE_Finalize
{
    IGCM_debug_PushStack "OCE_Finalize"

    IGCM_debug_Print 1 FINALIZE OCE !!!

    IGCM_debug_PopStack "OCE_Finalize"
}
