#!/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 --

    # cn_exp    experience name
    # nn_it000  number of the first time step
    # nn_itend  number of the last time step
    # nn_date0  initial calendar date yymmdd (used if  nn_rstctl=1)
    # nn_leapy  Leap year calendar (1) or not (0), or 360 days calendar (30)
    # nn_stock  frequency of creation of a restart file (modulo referenced to 1)
    # nn_write  frequency of write in the output file   (modulo referenced to nn_it000)
    # ln_rstart start from rest (F) or from a restart file (T)
    # nn_rstctl restart control = 0 nn_it000 is not compared to the restart file value
    #                           = 1 use nn_date0 in namelist (not the value in the restart file)
    #                           = 2 calendar parameters read in the restart file
    # nn_msh    =1 create a mesh file (coordinates, scale factors, masks)
    # rn_rdt    time step in seconds for the dynamics (and tracer if nacc=0)   ==> 5760 (coming from namelist)
    # nn_prg    time-step frequency of gap print in model output
    # nf_ptr_wri frequency of zonal means and transport output

    PAT_CEXPER=$( supergrep cn_exp     ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NIT000=$( supergrep nn_it000   ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NITEND=$( supergrep nn_itend   ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NDATE0=$( supergrep nn_date0   ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NLEAPY=$( supergrep nn_leapy   ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NSTOCK=$( supergrep nn_stock   ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NWRITE=$( supergrep nn_write   ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_RESTAR=$( supergrep ln_rstart  ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NRSTAR=$( supergrep nn_rstctl  ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NMSH=$(   supergrep nn_msh     ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_PRG=$(    supergrep nn_prg     ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )
    PAT_NF_PTR=$( supergrep nf_ptr_wri ${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE} )

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

    ##--Variables used for XMLIO_SERVER configuration file
    # using_server: .TRUE.(.FALSE.) to use(bypass) the io_server
    PAT_SERVER=$( supergrep using_server ${SUBMIT_DIR}/PARAM/xmlio_server.def )

    IGCM_debug_PopStack "OCE_Initialize"
}

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

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

    ## This informations are used for diaptr, trends and diagap files
    ## only the first frequency is used for this files

    ##--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} -ge 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


    ##--Write Frequency for iomput
    ## Differents frequencies are allowed for grid_[TUVW] and icemod files

    V1D_ENABLE=".FALSE."
    V5D_ENABLE=".FALSE."
    V1M_ENABLE=".FALSE."
    V1Y_ENABLE=".FALSE."

    for frequency in ${config_OCE_WriteFrequency} ; do
        case ${frequency} in
            1D|1d) V1D_ENABLE=".TRUE." ;;
        esac
        case ${frequency} in
            5D|5d) V5D_ENABLE=".TRUE." ;;
        esac
        case ${frequency} in
            1M|1m) V1M_ENABLE=".TRUE." ;;
        esac
        case ${frequency} in
            *[yY]) V1Y_ENABLE=".TRUE." ;;
        esac
    done

    # 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}/       cn_exp=\"${config_UserChoices_JobName}\"/" \
	-e "s/${PAT_NIT000}/       nn_it000=${ORCA_NIT000}/"                    \
	-e "s/${PAT_NITEND}/       nn_itend=${ORCA_NITEND}/"                    \
	-e "s/${PAT_NDATE0}/       nn_date0=${PeriodDateBegin}/"                \
        -e "s%${PAT_NLEAPY}%       nn_leapy=${ORCA_NLEAPY}%"                    \
	-e "s/${PAT_NSTOCK}/       nn_stock=${ORCA_NSTOCK}/"                    \
	-e "s/${PAT_NWRITE}/       nn_write=${ORCA_NWRITE}/"                    \
	-e "s/${PAT_RESTAR}/       ln_rstart=${ORCA_LRSTAR}/"                 \
	-e "s/${PAT_NRSTAR}/       nn_rstctl=${ORCA_NRSTDT}/"                    \
	-e "s/${PAT_NMSH}/         nn_msh=${ORCA_NMSH}/"                        \
	-e "s/${PAT_NPRG}/         nn_prg=${ORCA_NWRITE}/"                      \
	-e "s/${PAT_NF_PTR}/       nf_ptr_wri=${ORCA_NWRITE}/"                \
	namelist > namelist.tmp

    IGCM_sys_Mv namelist.tmp namelist

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

    ##--Variables used for iodef xml configuration file
    # output_1m_frequency_oce : output frequency of ocean output files in seconds
    #     - length of 1 month (in seconds) 
    #     - -1 for monthly mean with 31-28-31-30 .... calendar if
    #          simulation are done per year. ie PeriodLength=1Y in config.card
    #     - n days (in seconds) for other Period Length
    #                           

    output_1m_frequency_oce=-1

    case ${config_UserChoices_PeriodLength} in
        *Y|*y)
              (( output_1m_frequency_oce = 86400 * $( IGCM_date_DaysInMonth ${year} ${month} ) )) 
              if [ "${config_UserChoices_CalendarType}" != "360d" ] ; then
                 output_1m_frequency_oce=-1
                 echo "PeriodLength ${config_UserChoices_PeriodLength} and CalendarType ${config_UserChoices_CalendarType} are not working yet"
                 exit
              fi
              ;;
        *M|*m)
              (( output_1m_frequency_oce = 86400 * $( IGCM_date_DaysInMonth ${year} ${month} ) ))
              ;;
        *)
              (( output_1m_frequency_oce = PeriodLengthInDays * 86400 )) ;;
    esac

    echo 1M_Frequency in iodef : ${output_1m_frequency_oce}

    # update iodef.xml

    sed -e "s/<1D_ENABLE>/${V1D_ENABLE}/" \
        -e "s/<5D_ENABLE>/${V5D_ENABLE}/" \
        -e "s/<1M_ENABLE>/${V1M_ENABLE}/" \
        -e "s/<1Y_ENABLE>/${V1Y_ENABLE}/" \
        -e "s/<1M_FREQUENCY>/${output_1m_frequency_oce}/g" \
        iodef.xml > iodef.xml.tmp

    IGCM_sys_Mv iodef.xml.tmp iodef.xml

    # update xmlio_server.def

    if [ X${opa9_UserChoices_io_server} = Xy ] ; then
        sed -e "s/${PAT_SERVER}/  using_server = .TRUE./" \
        xmlio_server.def > xmlio_server.def.tmp
        IGCM_sys_Mv xmlio_server.def.tmp xmlio_server.def
    fi

    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"
}
