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

# Local function to find parameters in LMDZ .def files
    lmdzgrep () {
        grep $1 $2 |grep -v "#" | awk "-F=" '{print $2}'
    }

    RESOL_CPL=$( echo $RESOL | awk "-F-" '{print $1}' )

    #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}

    CPL_OkDay="n"
    CPL_OkMonth="n"

    for CPL_Frequency in ${config_CPL_WriteFrequency} ; do
	case ${CPL_Frequency} in
	    *D|*d) CPL_OkDay="y"   ;;
	    *M)    CPL_OkMonth="y" ;;
	esac
    done

    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 ))

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

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

    ## Calculate lag for transfer of fields from atmosphere -> ocean.
    ## LAG_ATM="1day in sec"/day_step * iphysiq/nsplit_phys
    ## First get day_step, iphyisq and nsplit_phys from LMDZ parameter files
    day_step=$( lmdzgrep day_step gcm.def )
    iphysiq=$( lmdzgrep iphysiq gcm.def )
    nsplit_phys=$( lmdzgrep nsplit_phys physiq.def )

    (( LAG_ATM = 86400 / day_step * iphysiq / nsplit_phys ))

    ############ Update Parameter Files   ##############
    sed -e "s/<initial_date>/${PeriodDateBegin}/" \
	-e "s/<calendar_type>/${CPL_calendar}/" \
	-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>/${CPL_OutputVar}/g" \
	-e "s/<lag_atm>/${LAG_ATM}/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_CPL=$(echo ${PeriodDateBegin} | sed -e "{ s/^\(.\{4\}\)/\1-/;s/\(-.\{2\}\)/\1-/; }");
    DATE_CPL=${DATE_CPL}"T00:00:00"
    
    echo ${DATE_CPL} ${CPL_OutputMode} ${CPL_OkDay} ${CPL_OkMonth}

    if [ "${CPL_OutputMode}" = "y" ] ; then

        [[ ${CPL_OkDay}   = "y" ]] && date >TEMPO_1D_cpl_atm.nc
        [[ ${CPL_OkMonth} = "y" ]] && date >TEMPO_1M_cpl_atm.nc
        [[ ${CPL_OkDay}   = "y" ]] && date >TEMPO_1D_cpl_oce.nc
        [[ ${CPL_OkMonth} = "y" ]] && date >TEMPO_1M_cpl_oce.nc

    fi

    echo FINALIZE CPL !!!

    IGCM_debug_PopStack "CPL_Finalize"
}
