#!/bin/ksh
#-----------------------------------
CPL_Initialize ()
{
    IGCM_debug_PushStack "CPL_Initialize"
 
    echo INITIALIZE CPL !!!

    #D- MPI context used to launch the coupled model
    LIBMPI=$(cat ${SUBMIT_DIR}/../.libmpi)
    echo LIBMPI=${LIBMPI}

    #D- MPISUSPEND=ON required for MPMD mode used by oasis
    export MPISUSPEND=ON

    IGCM_sys_build_run_file ${LIBMPI}

    IGCM_debug_PopStack "CPL_Initialize"
}

#-----------------------------------
CPL_Update ()
{
    IGCM_debug_PushStack "CPL_Update"

    ############ Update Time and Counters ##############
    ##-- Calcul de la duree du job (en secondes)
    (( D_JOB_SEC = 3600 * 24 * PeriodLengthInDays ))

    ############ Update Other Parameters  ##############
    ## Read Output_mode option in ${compname}.card --> Put "y" to have coupling variables in ouptut files
    IGCM_card_DefineVariableFromOption ${SUBMIT_DIR}/COMP/${compname}.card UserChoices Output_mode 
    eval Output_mode=\${${compname}_UserChoices_Output_mode} > /dev/null 2>&1
    echo ${Output_mode}
    Output_var='EXPORTED'
    if [ ${Output_mode} = y ] ; then
	Output_var='EXPOUT'
    fi

    ############ Update Parameter Files   ##############
    sed -e "s/<initial_date>/${PeriodDateBegin}/" \
	-e "s/<total_time>/${D_JOB_SEC}/" \
	-e "s/<lib_mpi>/${LIBMPI}/" \
	-e "s/<nproc_atm>/${NUM_PROC_ATM}/g" \
	-e "s/<nproc_oce>/${NUM_PROC_OCE}/g" \
	-e "s/<output_mode>/${Output_var}/g" \
	namcouple > namcouple.tmp

    IGCM_sys_Mv namcouple.tmp namcouple
    # Unused files we want to remove
    eval FileToBeDeleted[${#FileToBeDeleted[@]}]=trace
    eval FileToBeDeleted[${#FileToBeDeleted[@]}]=gweights
    eval FileToBeDeleted[${#FileToBeDeleted[@]}]=mweights
    eval FileToBeDeleted[${#FileToBeDeleted[@]}]=anaisout

    IGCM_debug_PopStack "CPL_Update"
}

#-----------------------------------
CPL_Finalize ()
{
    IGCM_debug_PushStack "CPL_Finalize"

    DATE_OASIS=$(echo ${PeriodDateBegin} | sed -e "{ s/^\(.\{4\}\)/\1-/;s/\(-.\{2\}\)/\1-/; }");
    DATE_OASIS=${DATE_OASIS}"T00:00:00"

    echo FINALIZE CPL !!!

    IGCM_debug_PopStack "CPL_Finalize"
}
