#!/bin/ksh

#-----------------------------------
function MBG_Initialize
{ 
    IGCM_debug_PushStack "MBG_Initialize"

# Local function to find namelists parameters
supergrep () {
    grep "^ *$1 *=" $2 | sed -e "s% *\!.*%%"
}

    ##--Variables used by OPA --


    ##--Variables used by MBG --

    # ln_rsttr  boolean term for tracer model restart (true or false)
    # nrsttr    control of the time step (0, 1 or 2)
    
    ##--Variables used by PISCES --
 
    PAT_TOP_LRSTTR=$( supergrep ln_rsttr          ${SUBMIT_DIR}/PARAM/namelist_top_${RESOL_OCE} )
    PAT_TOP_NRSTTR=$( supergrep nrsttr            ${SUBMIT_DIR}/PARAM/namelist_top_${RESOL_OCE} )
    PAT_PIS_ATCCO2=$( supergrep atcco2            ${SUBMIT_DIR}/PARAM/namelist_pisces_${RESOL_OCE} )
    PAT_PIS_LRIVER=$( supergrep ln_river          ${SUBMIT_DIR}/PARAM/namelist_pisces_${RESOL_OCE} )

    IGCM_debug_PopStack "MBG_Initialize"
}

#-----------------------------------
function MBG_Update
{
    IGCM_debug_PushStack "MBG_Update"

    ##-- Restart configuration
    if ( [ "${CumulPeriod}" -eq 1 ] && [ "${config_MBG_Restart}" = "n" ] ) ; then

        #echo "NO RESTART FOR TOP"
        TOP_LRSTTR=.FALSE.
        TOP_NRSTTR=0

        PISCES_LRIVER=.FALSE.

    elif ( [ "${CumulPeriod}" -eq 1 ] && [ "${config_MBG_Restart}" = "y" ] ) ; then

        #echo "RESTART TOP"
        TOP_LRSTTR=.TRUE.
        TOP_NRSTTR=0

        PISCES_LRIVER=.TRUE.

    else

        #echo "RESTART TOP"
        TOP_LRSTTR=.TRUE.
        TOP_NRSTTR=2

        PISCES_LRIVER=.TRUE.

    fi

    ##-- GHG forcing for the current year
    IPCC_PIS_CO2=`grep Annee_${year} CO2_1765_2005.txt | awk -F= '{print $2}'`

    ##-- Update namelist_top and namelist_pisces 

    sed -e "s%${PAT_TOP_LRSTTR}%          ln_rsttr=${TOP_LRSTTR}%"                   \
        -e "s%${PAT_TOP_NRSTTR}%          nrsttr=${TOP_NRSTTR}%"                   \
        namelist_top > namelist_top.tmp

    IGCM_sys_Mv namelist_top.tmp namelist_top

    sed -e "s%${PAT_PIS_LRIVER}%          ln_river=${PISCES_LRIVER}%"                \
        namelist_pisces > namelist_pisces.tmp

    IGCM_sys_Mv namelist_pisces.tmp namelist_pisces


    IGCM_debug_PopStack "MBG_Update"
}

#-----------------------------------
function MBG_Finalize
{
    IGCM_debug_PushStack "MBG_Finalize"

    echo FINALIZE MBG !!!

    IGCM_debug_PopStack "MBG_Finalize"
}

