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

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

    if [ -z "${opa_UserChoices_OPA_NPDT_JOURS}" ] ; then
	ORCA_NPDT_JOUR=15
    else
	ORCA_NPDT_JOUR=${opa_UserChoices_OPA_NPDT_JOURS}
    fi

    ##--Transformation namelist fortran 77 --> fortran 90
    #   ?       ? Is it really necessary ?       ?
    #sed -e /:/d -e s/" \&END"/"\/"/ -e s/" \&"/"\&"/ ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} > ${SUBMIT_DIR}/PARAM/namelist

    ##--Variables used by OPA --

    # cexper experience name for vairmer format
    # nit000 number of the first time step
    # nitend number of the last time step
    # nbisex Leap year calendar (0/1) (30 for 360d)
    # nwrite frequency of OUTPUT file
    # nwrihf frequency of HF OUTPUT file
    # lrstar boolean term for restart (true or false)
    # nstock frequency of restart file
    # nrstdt control of the time step (0, 1 or 2)
    # ndate0 initial calendar date aammjj
    # nmsh  =1 create a mesh file (coordinates, scale factors, masks)

    PAT_CEXPER=$( grep 'cexper' ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NIT000=$( grep 'nit000' ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NITEND=$( grep 'nitend' ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NBISEX=$( grep 'nbisex  =' ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE}| sed 's/ nbisex  =//' |sed '/^[ ]$/d'|sed 's/,//' )
    PAT_NWRITE=$( grep 'nwrite' ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_RESTAR=$( grep 'lrstar' ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NSTOCK=$( grep 'nstock' ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NRSTAR=$( grep 'nrstdt' ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NPRG=$(   grep 'nprg'   ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NDATE0=$( grep 'ndate0' ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NMSH=$(   grep 'nmsh'   ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} ) 
    PAT_NWRIHF=$( grep 'nwrihf' ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )

    ORCA_NSTOCK=$( echo $PAT_NSTOCK | sed "s/[a-z,A-Z,=]//g" )
    ORCA_RDT=$( egrep '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  ))

    ##-- Calcul du numero de pas de temps de debut de job ORCA
    (( ORCA_NIT000 = ( PeriodDaysSinceJC - DaysSinceJC ) * ORCA_NPDT_JOUR + 1 ))
    (( ORCA_NPDT   = PeriodLengthInDays * ORCA_NPDT_JOUR ))
    (( ORCA_NITEND = ORCA_NIT000 + ORCA_NPDT - 1))

    if [ "${ORCA_NSTOCK}" -gt "${ORCA_NPDT}" ]
	then
	ORCA_NSTOCK="${ORCA_NPDT}"
    fi

    ##-- verification du nb de pas de temps par jour
    (( 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 " VERIFIER ORCA_NPDT_JOUR dans le job ${JOB} "
        exit
    fi

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

	ORCA_LRSTAR=.FALSE.
	ORCA_NRSTDT=0
	ORCA_NMSH=1
        # ??? a garder ???
	# cat <<EOF > EMPave_old.dat
        # Old global EMP coeff =   1.000000000
        # EOF

	#echo "PAS DE RESTART OPA"
    elif ( [ "${CumulPeriod}" -eq 1 ] && [ "${config_OCE_Restart}" = "y" ] ) ; then

	ORCA_LRSTAR=.TRUE.
	ORCA_NRSTDT=0
	ORCA_NMSH=0

	#echo "RESTART OPA"
    else

	ORCA_LRSTAR=.TRUE.
	ORCA_NRSTDT=1
	ORCA_NMSH=0

	#echo "RESTART OPA"
    fi

    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}/       lrstar=${ORCA_LRSTAR}/" \
	-e "s/${PAT_NPRG}/         nprg=${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_NMSH}/         nmsh=${ORCA_NMSH}/" \
	-e "s/${PAT_NWRIHF}/       nwrihf=${ORCA_NWRIHF}/" \
	namelist > namelist.tmp

    IGCM_sys_Mv namelist.tmp namelist

    IGCM_debug_PopStack "OCE_Update"
}

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

    if [ -f date.file ] ; then
        # Prefix use in opa.card AND in lim.card :
	DATE_OPA=$( cat date.file | \
	    sed "s/\ ${config_UserChoices_JobName}_[0-9]*[a-z]_\([0-9]*_[0-9]*\)_output\ */\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"
}
