#!/bin/ksh

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

    JOB_NAME=${config_UserChoices_JobName}

    OPA_NDT_DAY=${pisces_UserChoices_OPA_NDT_DAY:=4}


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

    ##--Variables used by OPA --

    # cexper experience name for vairmer format
    # nit000 number of the first time step
    # nitend number of the last time step
    # nleapy leap year calendar (0/1) (30 for 360d)
    # nwrite frequency of OUTPUT file
    # ln_rstart boolean term for restart (true or false)
    # nstock frequency of restart file
    # ndate0 initial calendar date aammjj
    # rdt time step in seconds (coming from namelist)


    PAT_CEXPER=$( supergrep cexper    ${SUBMIT_DIR}/PARAM/namelist )
    PAT_NIT000=$( supergrep nit000    ${SUBMIT_DIR}/PARAM/namelist )
    PAT_NITEND=$( supergrep nitend    ${SUBMIT_DIR}/PARAM/namelist )
    PAT_NLEAPY=$( supergrep nleapy    ${SUBMIT_DIR}/PARAM/namelist )
    PAT_NSTOCK=$( supergrep nstock    ${SUBMIT_DIR}/PARAM/namelist )
    PAT_NDATE0=$( supergrep ndate0    ${SUBMIT_DIR}/PARAM/namelist )


    OPA_RDT=$( supergrep rdt  ${SUBMIT_DIR}/PARAM/namelist | sed 's/ *rdt *=//' | sed 's/\. *,//' )

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

    ##--Variables used by MBG --

    # nwritetrc frequency of write in the tracer output file
    # lrsttr    boolean term for tracer model restart (true or false)
    # nrsttr    control of the time step (0, 1 or 2)
    # ntrd_trc   time step frequency of write in the trends file for tracers
    # ln_trdmld_trc_restart boolean term for trc trends restart (true or false)
    
    ##--Variables used by PISCES --
 
    # nwritedia frequency of write in the additional diag output file

    PAT_TOP_NWRITETRC=$( supergrep nwritetrc             ${SUBMIT_DIR}/PARAM/namelist_top )
    PAT_TOP_LRSTTR=$( supergrep ln_rsttr                 ${SUBMIT_DIR}/PARAM/namelist_top )
    PAT_TOP_NRSTTR=$( supergrep nrsttr                   ${SUBMIT_DIR}/PARAM/namelist_top )
    PAT_TOP_NWRITETRD=$( supergrep ntrd_trc              ${SUBMIT_DIR}/PARAM/namelist_top )
    PAT_TOP_RSTRTTRD=$( supergrep ln_trdmld_trc_restart  ${SUBMIT_DIR}/PARAM/namelist_top )

    PAT_PIS_NWRITEDIA=$( supergrep nwritedia             ${SUBMIT_DIR}/PARAM/namelist_pisces )
    PAT_PIS_LRIVER=$( supergrep ln_river                 ${SUBMIT_DIR}/PARAM/namelist_pisces )

    IGCM_debug_PopStack "MBG_Initialize"
}

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

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

    ## Count of number of time steps from begin of OPA job
    (( OPA_NIT000 = ( PeriodDaysSinceJC - DaysSinceJC ) * OPA_NDT_DAY + 1 ))
    (( OPA_NDT   = PeriodLengthInDays * OPA_NDT_DAY ))
    (( OPA_NITEND = OPA_NIT000 + OPA_NDT - 1))

    ## Forcing to write one restart file at the end of period
    OPA_NSTOCK="${OPA_NITEND}"

    ## Verification of number of time steps per day
    (( NB_SEC_DAY_MODEL = OPA_NDT_DAY * OPA_RDT ))
    (( NB_SEC_DAY = 60 * 60 * 24 ))

    if [ ${NB_SEC_DAY_MODEL} -ne ${NB_SEC_DAY} ]
        then
        echo " VERIFY OPA_NDT_DAY in opa9.card "
        exit
    fi

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


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

    sed -e "s%${PAT_CEXPER}%       cexper=\"${config_UserChoices_JobName}\"%" \
        -e "s%${PAT_NIT000}%       nit000=${OPA_NIT000}%"                    \
        -e "s%${PAT_NITEND}%       nitend=${OPA_NITEND}%"                    \
        -e "s%${PAT_NSTOCK}%       nstock=${OPA_NSTOCK}%"                    \
        -e "s%${PAT_NDATE0}%       ndate0=${PeriodDateBegin}%"                \
        -e "s%${PAT_NLEAPY}%       nleapy=${OPA_NLEAPY}%"                     \
        namelist > namelist.tmp

    IGCM_sys_Mv namelist.tmp namelist

    echo 'Variables automatically updated in namelists'
    grep AUTO namelist*

    ##--Write Frequency Purpose ....
    topfrequency=$( echo ${config_MBG_WriteFrequency} | awk "-F " '{print $1}' )
    topfactor=$( echo ${topfrequency} | sed -e "s/[yYmMdD]//" )
    case ${topfrequency} in
        1Y|1y)
            (( TOP_NWRITE = OPA_NDT_DAY * topfactor * $( IGCM_date_DaysInYear  ${year} ) ))          ;
            PREFIX_NWRITETRC=${config_UserChoices_JobName}_${topfactor}y ;
            R_OUT_MBG_NWRITE=${R_OUT_MBG_O_Y} ;
            WFT1=${topfactor}Y ;;
        1M|1m)
            (( TOP_NWRITE = OPA_NDT_DAY * topfactor * $( IGCM_date_DaysInMonth  ${year} ${month} ) ))          ;
            PREFIX_NWRITETRC=${config_UserChoices_JobName}_${topfactor}m ;
            R_OUT_MBG_NWRITE=${R_OUT_MBG_O_M} ;
            WFT1=${topfactor}M ;;
        *D|*d)
            (( TOP_NWRITE = OPA_NDT_DAY * topfactor  ))          ;
            PREFIX_NWRITETRC=${config_UserChoices_JobName}_${topfactor}d ;
            R_OUT_MBG_NWRITE=${R_OUT_MBG_O_D} ;
            WFT1=${topfactor}D ;;
        *)
    esac

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

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

        if ( [ "${pisces_UserChoices_OPA_dyn}" = "cpl" ] ) ; then
             PISCES_LRIVER=.FALSE.
        else
             PISCES_LRIVER=.TRUE.
        fi

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

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

        if ( [ "${pisces_UserChoices_OPA_dyn}" = "cpl" ] ) ; then
             PISCES_LRIVER=.TRUE.
        else
             PISCES_LRIVER=.TRUE.
        fi


    else

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

        if ( [ "${pisces_UserChoices_OPA_dyn}" = "cpl" ] ) ; then
             PISCES_LRIVER=.TRUE.
        else
             PISCES_LRIVER=.TRUE.
        fi

    fi

    sed -e "s%${PAT_TOP_NWRITETRC}%       nwritetrc=${TOP_NWRITE}%"               \
        -e "s%${PAT_TOP_NWRITETRD}%       ntrd_trc=${TOP_NWRITE}%"                \
        -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

# on force les sorties PISCES comme les sorties OPA

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

    IGCM_sys_Mv namelist_pisces.tmp namelist_pisces

    echo 'Variables automatically updated in namelists'
    grep AUTO namelist*

    IGCM_debug_PopStack "MBG_Update"
}

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

    if [ -f date.file ] ; then
        # Prefix use in opa.card AND in lim2.card :
        DATE_OPA=$( cat date.file | \
            sed "s/\ ${config_UserChoices_JobName}_[0-9]*[a-z]_\([0-9]*_[0-9]*\)_\ */\1/g" )
        ###DATE_OPA=$( $DATE_OPABF | cut -c1-30 )
        MainPrefix=${config_UserChoices_JobName}_1d_${DATE_OPA}
        SecondPrefix=${config_UserChoices_JobName}_5d_${DATE_OPA}
    fi

    echo FINALIZE MBG !!!

    IGCM_debug_PopStack "MBG_Finalize"
}

