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

    JOB_NAME=${config_UserChoices_JobName}

    RESOL_OCE_ICE=$( echo ${RESOL} | awk "-Fx" '{print $1}' )
    case ${RESOL_OCE_ICE} in
	( *LIM2* )
	SEAICE_MODEL=LIM2 
	LIM_VERSION=2
	;;

	( *LIM3* )
	SEAICE_MODEL=LIM3
	LIM_VERSION=3
	;;
	( *CICE*) SEAICE_MODEL=CICE ;;
	( *     ) SEAICE_MODEL=UNKNOWN ;;
    esac
    RESOL_OCE=$( echo ${RESOL_OCE_ICE} | sed "s/${SEAICE_MODEL}//" )

    echo "RESOL          : ${RESOL}"
    echo "RESOL_OCE_ICE  : ${RESOL_OCE_ICE}"
    echo "SEAICE_MODEL   : ${SEAICE_MODEL}"
    echo "LIM_VERSION    : ${LIM_VERSION}"
    echo "RESOL_OCE      : ${RESOL_OCE}"

    # 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_cfg (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
    # nn_fwri   frequency of zonal means and transport output

    NAMELIST_OPA_CFG=${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE}_cfg
    NAMELIST_OPA_REF=${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE}_ref
    echo "namelist_ref : ${NAMELIST_OPA_REF}"
    if [ ! -r ${NAMELIST_OPA_REF} ] ; then
	echo "${NAMELIST_OPA_REF} non trouve"
    fi
    echo "namelist_cfg : ${NAMELIST_OPA_CFG}"
    if [ ! -r ${NAMELIST_OPA_CFG} ] ; then
	echo "${NAMELIST_OPA_CFG} non trouve"
    fi

    PAT_CEXPER=$(   supergrep cn_exp      ${NAMELIST_OPA_CFG} )
    PAT_NIT000=$(   supergrep nn_it000    ${NAMELIST_OPA_CFG} )
    PAT_NITEND=$(   supergrep nn_itend    ${NAMELIST_OPA_CFG} )
    PAT_NDATE0=$(   supergrep nn_date0    ${NAMELIST_OPA_CFG} )
    PAT_NLEAPY=$(   supergrep nn_leapy    ${NAMELIST_OPA_CFG} )
    PAT_NSTOCK=$(   supergrep nn_stock    ${NAMELIST_OPA_CFG} )
    PAT_NWRITE=$(   supergrep nn_write    ${NAMELIST_OPA_CFG} )
    PAT_RESTAR=$(   supergrep ln_rstart   ${NAMELIST_OPA_CFG} )
    PAT_NRSTAR=$(   supergrep nn_rstctl   ${NAMELIST_OPA_CFG} )
    PAT_NMSH=$(     supergrep nn_msh      ${NAMELIST_OPA_CFG} )
    PAT_NN_WRITE=$( supergrep nn_write    ${NAMELIST_OPA_CFG} )
    PAT_NN_FWRI=$(  supergrep nn_fwri     ${NAMELIST_OPA_CFG} )
    PAT_ICE_EMBD=$( supergrep nn_ice_embd ${NAMELIST_OPA_CFG} )
    PAT_ICEFLX=$(   supergrep cn_iceflx   ${NAMELIST_OPA_CFG} )
    PAT_JPNI=$(     supergrep jpni        ${NAMELIST_OPA_CFG} )
    PAT_JPNJ=$(     supergrep jpnj        ${NAMELIST_OPA_CFG} )
    PAT_JPNIJ=$(    supergrep jpnij       ${NAMELIST_OPA_CFG} )
    PAT_NN_FSBC=$(  supergrep nn_fsbc     ${NAMELIST_OPA_CFG} ) 

    ORCA_RDT=$(       supergrep rn_rdt        ${NAMELIST_OPA_CFG} | sed 's/ *rn_rdt *=//'  | sed 's/\. *//' )
    ORCA_NN_FSBC=$(   supergrep nn_fsbc       ${NAMELIST_OPA_CFG} | sed 's/ *nn_fsbc *=//' | sed 's/\. *//' )
    (( ORCA_NPDT_JOUR  = 86400 / ORCA_RDT     ))
    (( ORCA_NPDT_SBC   = ORCA_NPDT_JOUR / ORCA_NN_FSBC ))
 

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

    echo "PAT_CEXPER   $PAT_CEXPER "
    echo "PAT_NIT000   $PAT_NIT000"
    echo "PAT_NITEND   $PAT_NITEND"
    echo "PAT_NDATE0   $PAT_NDATE0"
    echo "PAT_NLEAPY   $PAT_NLEAPY"
    echo "PAT_NSTOCK   $PAT_NSTOCK"
    echo "PAT_NWRITE   $PAT_NWRITE"
    echo "PAT_RESTAR   $PAT_RESTAR"
    echo "PAT_NRSTAR   $PAT_NRSTAR"
    echo "PAT_NMSH     $PAT_NMSH"
    echo "PAT_NN_WRITE $PAT_NN_WRITE"
    echo "PAT_NN_FWRI  $PAT_NN_FWRI"
    echo "PAT_ICE_EMBD $PAT_ICE_EMBD"
    echo "PAT_ICEFLX   $PAT_ICEFLX"
    echo "PAT_JPNI     $PAT_JPNI"
    echo "PAT_JPNJ     $PAT_JPNJ"
    echo "PAT_JPNIJ    $PAT_JPNIJ"
    echo "PAT_NN_FSBC  $PAT_NN_FSBC"
    echo " "
    echo "ORCA_RDT     $ORCA_RDT"
    echo "DaysSinceJC  $DaysSinceJC"
    
    IGCM_debug_PopStack "OCE_Initialize"

    
}

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

    ## Check that nn_fsbc is correct compare to coupling frequency

    FreqCoupling=${oasis_UserChoices_FreqCoupling:-86400}
    if [[ ${FreqCoupling} -gt 0 ]] ; then
	(( ORCA_NPDT_COUP  = 86400 / FreqCoupling ))
    else
	ORCA_NPDT_COUP=${ORCA_NPDT_SBC}
    fi 
    
    if [[ ${ORCA_NN_FSBC} -lt ${ORCA_NPDT_COUP} ]] ; then
    	(( ORCA_NN_FSBC = ORCA_NPDT_JOUR / ORCA_NPDT_COUP ))
    fi

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

    echo "FreqCoupling    $FreqCoupling"
    echo "ORCA_NN_FSBC    $ORCA_NN_FSBC"
    echo "ORCA_NPDT_JOUR  $ORCA_NPDT_JOUR"
    echo "ORCA_NPDT_COUP  $ORCA_NPDT_COUP"
    echo "ORCA_NPDT_SBC   $ORCA_NPDT_SBC"

    ##--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} ;
	    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} ;
	    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} ;
	    WF1=${factor}D ;;
	*)
	    (( ORCA_NWRITE = 0 ))                                                            ;;
    esac

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

    V1D_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
            1M|1m) V1M_ENABLE=".TRUE." ;;
        esac
        case ${frequency} in
            *[yY]) V1Y_ENABLE=".TRUE." ;;
        esac
    done


    ##-- Output level : 3 for more 1D variables
    eval opa9_OUTPUT_LEVEL=\${opa9_UserChoices_OUTPUT_LEVEL} > /dev/null 2>&1
    OUTPUT_LEVEL=${opa9_OUTPUT_LEVEL}


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

    ##-- 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=1
	#echo "OPA RESTART"
    else
	ORCA_LRSTAR=.TRUE.
	ORCA_NRSTDT=2
	ORCA_NMSH=0
	#echo "OPA RESTART"
    fi

    ##-- Meshmask option
    IGCM_card_DefineVariableFromOption ${SUBMIT_DIR}/COMP/opa9.card UserChoices mesh_mask

    if [ "${opa9_UserChoices_mesh_mask}" = "y" ]; then
        ORCA_NMSH=1
        IGCM_card_WriteOption ${SUBMIT_DIR}/COMP/opa9.card UserChoices mesh_mask "n"
    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} }" ) ) 


    case ${SEAICE_MODEL} in
	( LIM2 ) 
	NN_ICE_EMBD=0
	ICEFLX=none
	;;
	( LIM3 ) 
	NN_ICE_EMBD=1 
	ICEFLX=${opa9_UserChoices_iceflx:-linear}
	;;
    esac

    echo "NUM_PROC_OCE : " ${NUM_PROC_OCE}

    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_NN_WRITE}/     nn_prg=${ORCA_NWRITE}/"                      \
	-e "s/${PAT_NN_FWRI}/      nn_fwri=${ORCA_NWRITE}/"                     \
	-e "s/${PAT_NN_FSBC}/      nn_fsbc=${ORCA_NN_FSBC}/"                    \
	-e "s/${PAT_ICE_EMBD}/     nn_ice_embd=${NN_ICE_EMBD}/"                 \
	-e "s/${PAT_ICEFLX}/       cn_iceflx=\'${ICEFLX}'/"                     \
	-e "s/${PAT_JPNI}/         jpni=1/"                                     \
	-e "s/${PAT_JPNJ}/         jpnj=${NUM_PROC_OCE}/"                       \
	-e "s/${PAT_JPNIJ}/        jpnij=${NUM_PROC_OCE}/"                      \
	namelist_cfg > namelist_cfg.tmp

    IGCM_sys_Mv namelist_cfg.tmp namelist_cfg

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

    # update iodef.xml

    echo 'Informations into iodef.xml : V1D_ENABLE V1M_ENABLE V1Y_ENABLE OUTPUT_LEVEL'
    echo ${V1D_ENABLE} ${V1M_ENABLE} ${V1Y_ENABLE} ${OUTPUT_LEVEL}

    sed -e "s/_1D_ENABLE_/${V1D_ENABLE}/" \
        -e "s/_1M_ENABLE_/${V1M_ENABLE}/" \
        -e "s/_1Y_ENABLE_/${V1Y_ENABLE}/" \
        -e "s/_OUTPUT_LEVEL_/${OUTPUT_LEVEL}/" \
        context_nemo.xml > context_nemo.xml.tmp

    IGCM_sys_Mv context_nemo.xml.tmp context_nemo.xml

    # vargas/titane/MPP and switch from 1 proc to 5 procs. We need to suppres restartopa the second month, if restartopa_0000 exist
    # same thing for restart_trc and restart_ice_in

    for restartfilenemo in restartopa restart_trc restart_ice_in ; do
      [ -f ${restartfilenemo}.nc ] && [ -f ${restartfilenemo}_0000.nc ] && IGCM_sys_Rm -f ${restartfilenemo}.nc
    done

    # Add include of nemo context in iodef.xml
    # In iodef.xml add on next line after "COMPONENT CONTEXT"
    #  <context id="nemo" src="./context_nemo.xml"/>
    echo '<context id="nemo" src="./context_nemo.xml"/>' > add.tmp
    cp iodef.xml iodef.xml.tmp
    sed -e "/COMPONENT CONTEXT/r add.tmp" \
        iodef.xml.tmp > iodef.xml
    rm iodef.xml.tmp add.tmp


    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}_1m_${DATE_OPA}
    fi

    echo FINALIZE OCE !!!

    IGCM_debug_PopStack "OCE_Finalize"
}
