#!/bin/ksh

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

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

    if [ X"${pisces_UserChoices_Offline_Mode}" = X"y" ] ; then
       RESOL_OCE=$( echo ${config_UserChoices_ExperimentName} | cut -c1-5 )
       EXPTYPE=$( echo ${config_UserChoices_ExperimentName} | cut -c6- )
       OPA_RDT=$( supergrep rn_rdt  ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE}${EXPTYPE}_offline_cfg | sed 's/ *rn_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 ))

       (( OPA_NPDT_DAY  =  86400 / OPA_RDT ))
       (( OPA_NPDT_YEAR  =  OPA_NPDT_DAY * 365     ))


       IGCM_debug_Print 1 " "
       IGCM_debug_Print 1 "OPA_RDT        ${OPA_RDT}"
       IGCM_debug_Print 1 "OPA_NPDT_DAY   ${OPA_NPDT_DAY}"
       IGCM_debug_Print 1 "OPA_NPDT_YEAR  ${OPA_NPDT_YEAR}"

     fi

    IGCM_debug_PopStack "MBG_Initialize"
}

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


    ##--Write Frequency Purpose
    Nbfreq=$( echo ${config_MBG_WriteFrequency} | wc -w )
    typeset -Z1 i=1
    while [ $i -le ${Nbfreq} ]; do
       topfrequency=$( echo ${config_MBG_WriteFrequency} | awk -v var="$i" "-F " '{print $var}' )
       topfactor=$( echo ${topfrequency} | sed -e "s/[yYmMdD]//" )
       case ${topfrequency} in
         *Y|*y)
            eval PREFIX_WFT${i}=${config_UserChoices_JobName}_${topfactor}y_${DatesPeriod} ;
            eval R_OUT_MBG_WFT${i}=${R_OUT_MBG_O_Y} ;
            eval WFT${i}=${topfactor}Y ;;
         *M|*m)
            eval PREFIX_WFT${i}=${config_UserChoices_JobName}_${topfactor}m_${DatesPeriod} ;
            eval R_OUT_MBG_WFT${i}=${R_OUT_MBG_O_M} ;
            eval WFT${i}=${topfactor}M ;;
         *D|*d)
            eval PREFIX_WFT${i}=${config_UserChoices_JobName}_${topfactor}d_${DatesPeriod} ;
            eval R_OUT_MBG_WFT${i}=${R_OUT_MBG_O_D} ;
            eval WFT${i}=${topfactor}D ;;
         *)
      esac
       let i=$i+1
    done

    if [ X"${pisces_UserChoices_Offline_Mode}" = X"y" ] ; then


       # 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_NPDT_DAY + 1 ))
       (( OPA_NDT   = PeriodLengthInDays * OPA_NPDT_DAY ))
       (( OPA_NITEND = OPA_NIT000 + OPA_NDT - 1))

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

       # 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} }" ) )
    fi

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

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

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

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

    else

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

    fi

# on force les sorties PISCES comme les sorties OPA
    if [ X"${pisces_UserChoices_Offline_Mode}" = X"y" ] ; then
      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 nn_stock ${OPA_NSTOCK}
      IGCM_comp_modifyNamelist blocker    namelist_cfg nn_date0 ${PeriodDateBegin}
      IGCM_comp_modifyNamelist blocker    namelist_cfg nn_leapy  ${OPA_NLEAPY}
   fi

   IGCM_comp_modifyNamelist blocker    namelist_top_cfg ln_rsttr  ${TOP_LRSTTR}
   IGCM_comp_modifyNamelist blocker    namelist_top_cfg nn_rsttr  ${TOP_NRSTTR}
   IGCM_comp_modifyNamelist blocker    namelist_pisces_cfg  nn_pisdmp  ${OPA_NPDT_YEAR}

   IGCM_debug_PopStack "MBG_Update"
}

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

    echo FINALIZE MBG !!!

    IGCM_debug_PopStack "MBG_Finalize"
}

