#!/bin/ksh
#-----------------------------------------------------------------
function OCE_Initialize
{
    IGCM_debug_PushStack "OCE_Initialize"

    JOB_NAME=${config_UserChoices_JobName}
    RESOL_OCE=$( echo $RESOL | awk "-Fx" '{print $1}' )

    ORCA_NPDT_JOUR=${opa9_UserChoices_OPA_NPDT_JOURS:=15}

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

    ##--Variables used by OPA --

    # cexper experience name for vairmer format
    # ln_rstart boolean term for restart (true or false)
    # nrstdt control of the time step (0, 1 or 2)
    # nit000 number of the first time step
    # nitend number of the last time step
    # ndate0 initial calendar date aammjj
    # nleapy Leap year calendar (1) or not (0), or 360 days calendar (30)
    # nstock frequency of restart file
    # nwrite frequency of OUTPUT file
    # nmsh  =1 create a mesh file (coordinates, scale factors, masks)
    # nwrihf frequency of HF OUTPUT file
    # rdt time step in seconds (coming from namelist)
    # nf_ptr_wri frequency of zonal means and transport output

    PAT_CEXPER=$( supergrep cexper     ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NIT000=$( supergrep nit000     ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NITEND=$( supergrep nitend     ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NWRITE=$( supergrep nwrite     ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NF_PTR=$( supergrep nf_ptr_wri ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_RESTAR=$( supergrep ln_rstart  ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NSTOCK=$( supergrep nstock     ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NRSTAR=$( supergrep nrstdt     ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NDATE0=$( supergrep ndate0     ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NLEAPY=$( supergrep nleapy     ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NMSH=$(   supergrep nmsh       ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )

    ORCA_RDT=$( supergrep rdt  ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} | 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 ))

    IGCM_debug_PopStack "OCE_Initialize"
}

#-----------------------------------------------------------------
function OCE_Update
{
    IGCM_debug_PushStack "OCE_Update"

    NbFreq=$( echo ${config_OCE_WriteFrequency} | wc -w )

    ##--Write Frequency Purpose ....
    frequency=$( echo ${config_OCE_WriteFrequency} | awk "-F " '{print $1}' )
    factor=$( echo ${frequency} | sed -e "s/[yYmMdD]//" )
    case ${frequency} in
	1Y|1y)
	    (( ORCA_NWRITE = ORCA_NPDT_JOUR * factor * $( IGCM_date_DaysInYear  ${year} ) ))          ;
	    PREFIX_NWRITE=${config_UserChoices_JobName}_${factor}y ;
	    R_OUT_OCE_NWRITE=${R_OUT_OCE_O_Y} ;
	    R_OUT_ICE_NWRITE=${R_OUT_ICE_O_Y} ;
	    WF1=${factor}Y ;;
	1M|1m)
	    (( ORCA_NWRITE = ORCA_NPDT_JOUR * factor * $( IGCM_date_DaysInMonth ${year} ${month} ) )) ;
	    PREFIX_NWRITE=${config_UserChoices_JobName}_${factor}m ;
	    R_OUT_OCE_NWRITE=${R_OUT_OCE_O_M} ;
	    R_OUT_ICE_NWRITE=${R_OUT_ICE_O_M} ;
	    WF1=${factor}M ;;
	*D|*d)
	    (( ORCA_NWRITE = ORCA_NPDT_JOUR * factor  ))  ;
	    PREFIX_NWRITE=${config_UserChoices_JobName}_${factor}d ;
	    R_OUT_OCE_NWRITE=${R_OUT_OCE_O_D} ;
	    R_OUT_ICE_NWRITE=${R_OUT_ICE_O_D} ;
	    WF1=${factor}D ;;
	*)
	    (( ORCA_NWRITE = 0 ))                                                            ;;
    esac

    ##--Write Frequency Purpose .... concerning the second opa file type.
    if [ ${NbFreq} -eq 2 ] ; then
	frequency=$( echo ${config_OCE_WriteFrequency} | awk "-F " '{print $2}' )
	factor=$( echo ${frequency} | sed -e "s/[yYmMdD]//" )
	case ${frequency} in
	    *Y|*y)
		(( ORCA_NWRIHF = ORCA_NPDT_JOUR * factor * $( IGCM_date_DaysInYear  ${year} ) ))          ;
		PREFIX_NWRIHF=${config_UserChoices_JobName}_${factor}y ;
		R_OUT_OCE_NWRIHF=${R_OUT_OCE_O_Y} ;
		WF2=${factor}Y ;;
	    *M|*m)
		(( ORCA_NWRIHF = ORCA_NPDT_JOUR * factor * $( IGCM_date_DaysInMonth ${year} ${month} ) )) ;
		PREFIX_NWRIHF=${config_UserChoices_JobName}_${factor}m ;
		R_OUT_OCE_NWRIHF=${R_OUT_OCE_O_M} ;
		WF2=${factor}M ;;
	    *D|*d)
		(( ORCA_NWRIHF = ORCA_NPDT_JOUR * factor ))  ;
		PREFIX_NWRIHF=${config_UserChoices_JobName}_${factor}d ;
		R_OUT_OCE_NWRIHF=${R_OUT_OCE_O_D} ;
		WF2=${factor}D ;;
	    *)
		(( ORCA_NWRIHF = 0 ))                                                            ;;
	esac
    else
	ORCA_NWRIHF=0
    fi

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

    ##-- Number of time steps updated : the first, the last and the number of time steps
    (( ORCA_NIT000 = ( PeriodDaysSinceJC - DaysSinceJC ) * ORCA_NPDT_JOUR + 1 ))
    (( ORCA_NPDT   = PeriodLengthInDays * ORCA_NPDT_JOUR ))
    (( ORCA_NITEND = ORCA_NIT000 + ORCA_NPDT - 1))

    ##-- We force one restart file at the end of the trunk
    ORCA_NSTOCK="${ORCA_NITEND}"

    ##-- Let verify the number of time steps per day
    (( NB_SEC_JOUR_MODEL = ORCA_NPDT_JOUR * ORCA_RDT ))
    (( NB_SEC_JOUR = 60 * 60 * 24 ))

    if [ ${NB_SEC_JOUR_MODEL} -ne ${NB_SEC_JOUR} ] ; then
        echo " VERIFY ORCA_NPDT_JOUR in opa9.card "
        exit
    fi

    ##-- Restart configuration
    if ( [ "${CumulPeriod}" -eq 1 ] && [ "${config_OCE_Restart}" = "n" ] ) ; then
	ORCA_LRSTAR=.FALSE.
	ORCA_NRSTDT=0
        # Put ORCA_NMSH=0 when OPA running in parallel mode
	ORCA_NMSH=1
	#echo "NO OPA RESTART"
    elif ( [ "${CumulPeriod}" -eq 1 ] && [ "${config_OCE_Restart}" = "y" ] ) ; then
	ORCA_LRSTAR=.TRUE.
	ORCA_NRSTDT=0
	ORCA_NMSH=0
	#echo "OPA RESTART"
    else
	ORCA_LRSTAR=.TRUE.
	ORCA_NRSTDT=2
	ORCA_NMSH=0
	#echo "OPA RESTART"
    fi

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

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


    sed -e "s/${PAT_CEXPER}/       cexper=\"${config_UserChoices_JobName}\"/" \
	-e "s/${PAT_NIT000}/       nit000=${ORCA_NIT000}/"                    \
	-e "s/${PAT_NITEND}/       nitend=${ORCA_NITEND}/"                    \
	-e "s/${PAT_NWRITE}/       nwrite=${ORCA_NWRITE}/"                    \
	-e "s/${PAT_RESTAR}/       ln_rstart=${ORCA_LRSTAR}/"                 \
	-e "s/${PAT_NPRG}/         nprg=${ORCA_NWRITE}/"                      \
	-e "s/${PAT_NF_PTR}/       nf_ptr_wri=${ORCA_NWRITE}/"                \
	-e "s/${PAT_NSTOCK}/       nstock=${ORCA_NSTOCK}/"                    \
	-e "s/${PAT_NRSTAR}/       nrstdt=${ORCA_NRSTDT}/"                    \
	-e "s/${PAT_NDATE0}/       ndate0=${PeriodDateBegin}/"                \
        -e "s%${PAT_NLEAPY}%       nleapy=${ORCA_NLEAPY}%"                    \
	-e "s/${PAT_NMSH}/         nmsh=${ORCA_NMSH}/"                        \
	namelist > namelist.tmp

    IGCM_sys_Mv namelist.tmp namelist

    echo 'Variables automatically updated in ORCA namelist'
    grep AUTO namelist

    IGCM_debug_PopStack "OCE_Update"
}

#-----------------------------------
function OCE_Finalize
{
    IGCM_debug_PushStack "OCE_Finalize"

    if [ -f date.file ] ; then
        # Prefix use in opa9.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" )
	MainPrefix=${config_UserChoices_JobName}_1d_${DATE_OPA}
	SecondPrefix=${config_UserChoices_JobName}_5d_${DATE_OPA}
    fi

    echo FINALIZE OCE !!!

    IGCM_debug_PopStack "OCE_Finalize"
}
