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

    JOB_NAME=${config_UserChoices_JobName}
    RESOL_OCE=${ResolOce}
    ORCAGRID=${opa9_UserChoices_ORCA_version%%.*}
    IGCM_debug_Print 1 "RESOL_OCE      : ${RESOL_OCE}"
    IGCM_debug_Print 1 "ORCAGRID         : ${ORCAGRID}"


    # Local function to find namelists parameters
    #supergrep () { grep "^ *$1 *=" $2 | sed -e "s% *\!.*%%" ; }
    supergrep () { grep "^ *$1 *=" $2 | sed -e "s% *\!.*%%" -e "s%^ *$1 *=%%" ; }
    ##--Variables used by OPA --
    NAMELIST_OPA_CFG=${SUBMIT_DIR}/PARAM/namelist_${RESOL_OCE}_cfg
    IGCM_debug_Print 1 "namelist_cfg : ${NAMELIST_OPA_CFG}"
    if [ ! -r ${NAMELIST_OPA_CFG} ] ; then
        IGCM_debug_Exit "${NAMELIST_OPA_CFG} not found"
	IGCM_debug_Verif_Exit
    fi
    OPA_RDT=$(       supergrep rn_rdt        ${NAMELIST_OPA_CFG} )
    OPA_NN_FSBC=$(   supergrep nn_fsbc       ${NAMELIST_OPA_CFG} )
    #
    # OPA_RDT=$(       supergrep rn_rdt        namelist_cfg )
    # OPA_NN_FSBC=$(   supergrep nn_fsbc       namelist_cfg )
    (( OPA_NPDT_DAY   =  86400 / OPA_RDT        ))
    (( OPA_NPDT_YEAR  =  OPA_NPDT_DAY * 365     ))
    (( OPA_RDT_SBC    =  OPA_RDT * OPA_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 ))

    IGCM_debug_Print 1 " "
    IGCM_debug_Print 1 "OPA_RDT        ${OPA_RDT}"
    IGCM_debug_Print 1 "OPA_NN_FSBC    ${OPA_NN_FSBC}"
    IGCM_debug_Print 1 "OPA_RDT_SBC    ${OPA_RDT_SBC}"
    IGCM_debug_Print 1 "OPA_NPDT_DAY   ${OPA_NPDT_DAY}"
    IGCM_debug_Print 1 "OPA_NPDT_YEAR  ${OPA_NPDT_YEAR}"
    IGCM_debug_Print 1 "DaysSinceJC    ${DaysSinceJC}"

    ## Check that nn_fsbc is correct compare to coupling frequency
    FreqCoupling=${oasis_UserChoices_FreqCoupling:-86400}
    
    ## This informations are used for diaptr, trends and diagap files
    ## only the first frequency is used for this files
    
    IGCM_debug_Print 1 "FreqCoupling    ${FreqCoupling}"
    IGCM_debug_Print 1 "OPA_NN_FSBC    ${OPA_NN_FSBC}"
    IGCM_debug_Print 1 "OPA_RDT        ${OPA_RDT}"
    IGCM_debug_Print 1 "OPA_RDT_SBC    ${OPA_RDT_SBC}"
    
    if [[ ${OPA_RDT_SBC} -gt ${FreqCoupling} ]] ; then
	IGCM_debug_Exit "OPA_RDT_SBC=${OPA_RDT_SBC} is greater than FreqCoupling=${FreqCoupling}"
     	IGCM_debug_Verif_Exit
    fi

    IGCM_debug_PopStack "OCE_Initialize"
   
}

#-----------------------------------------------------------------
function OCE_Update
{
    IGCM_debug_PushStack "OCE_Update"
  
    ##--Write Frequency for iomput
    ## Differents frequencies are allowed for OCE 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." ;;
            ( 5D|5d ) V5D_ENABLE=".TRUE." ;;
            ( 1M|1m ) V1M_ENABLE=".TRUE." ;;
            ( *[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
    (( OPA_NIT000 = ( PeriodDaysSinceJC - DaysSinceJC ) * OPA_NPDT_DAY + 1 ))
    (( OPA_NPDT   = PeriodLengthInDays * OPA_NPDT_DAY ))
    (( OPA_NITEND = OPA_NIT000 + OPA_NPDT - 1))

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


    ##-- Additionnal Restart Option to force reproducibility ; force kt to kt red in restart file
    ## ${opa9_UserChoices_Reproducibility_after_restart}

    IGCM_card_DefineVariableFromOption ${SUBMIT_DIR}/COMP/opa9.card UserChoices Reproducibility_after_restart

   ##-- Restart configuration
    if ( [ "${opa9_UserChoices_Reproducibility_after_restart}" = "y" ] && [ "${config_OCE_Restart}" = "y" ] ) ; then
      OPA_LRSTAR=.TRUE.
      OPA_NRSTDT=2
      #echo "OPA RESTART"
      IGCM_debug_Print 1 'WARNING : dangerous option for NEMO opa9 pisces lim3'
      IGCM_debug_Print 1 'Reproducibility_after_Restart forced ie kt forced to kt red in restart file : ' ${opa9_UserChoices_Reproducibility_after_restart}

    elif ( [ "${CumulPeriod}" -eq 1 ] && [ "${config_OCE_Restart}" = "n" ] ) ; then
      OPA_LRSTAR=.FALSE.
      OPA_NRSTDT=0
      #echo "NO OPA RESTART"
    elif ( [ "${CumulPeriod}" -eq 1 ] && [ "${config_OCE_Restart}" = "y" ] ) ; then
      OPA_LRSTAR=.TRUE.
      OPA_NRSTDT=0
      #echo "OPA RESTART"
    else
      OPA_LRSTAR=.TRUE.
      OPA_NRSTDT=2
      #echo "OPA RESTART"
    fi

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

    OPA_NMSH=.FALSE.
    if [ "${opa9_UserChoices_mesh_mask}" = "y" ]; then
        OPA_NMSH=.TRUE.
        IGCM_card_WriteOption ${SUBMIT_DIR}/COMP/opa9.card UserChoices mesh_mask "n"
    fi

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

    if ( [ "${opa9_UserChoices_Reproducibility_after_restart}" = "y" ] ) ; then
      ##-- choose the right restart file
      NEMO_RESTART_FILE=restartopa.nc
      [ -f restartopa_0000.nc ] && NEMO_RESTART_FILE=restartopa_0000.nc
      ##-- Getting from restart file the last time step of the run at which we want to re-start
      NEMO_KT_FROM_RESTART=$(ncdump -v kt ${NEMO_RESTART_FILE}|grep 'kt ='|awk '{print $3}' )

      if ( [ "${CumulPeriod}" -eq 1 ] ) ; then
        ## Force the date in the restart file to be the last day before the begining of the new run
        dateendprevious=$( IGCM_date_AddDaysToGregorianDate ${DateBegin} -1 )
        IGCM_debug_Print 1 "Previous Date  ${dateendprevious}"
        IGCM_debug_Print 1 "cmd done to modify NEMO restartfile:   ncap2 -s ndastp=${dateendprevious} ${NEMO_RESTART_FILE}  tmp.nc"
	if [ -f restartopa_0000.nc ] ; then
           typeset -Z4 ncpu=0
           while [ $ncpu -lt ${OCE_PROC_MPI} ] ; do
              ncap2 -s "ndastp=${dateendprevious}" restartopa_${ncpu}.nc  tmp.nc
              mv tmp.nc restartopa_${ncpu}.nc
              (( ncpu = ncpu + 1 ))
           done
        else
           ncap2 -s "ndastp=${dateendprevious}" ${NEMO_RESTART_FILE}  tmp.nc
           mv tmp.nc ${NEMO_RESTART_FILE}
        fi
        ##-- Getting from restart file the "new" restart date of run at which we want to re-start
        NEMO_NDASTP_FROM_RESTART=$(ncdump -v ndastp ${NEMO_RESTART_FILE}|grep 'ndastp ='|awk '{print $3}' )
        IGCM_debug_Print 1 "NEMO_NDASTP (from Restart) for 1st Period       : ${NEMO_NDASTP_FROM_RESTART}"

      fi

      (( NEMO_NIT000 = NEMO_KT_FROM_RESTART + 1 ))
      (( NEMO_NITEND = NEMO_KT_FROM_RESTART + OPA_NITEND - OPA_NIT000 + 1 ))
      IGCM_debug_Print 1 "NEMO_NIT000 (from Restart)        : ${NEMO_NIT000}"
      IGCM_debug_Print 1 "NEMO_NITEND (from Restart + ... ) : ${NEMO_NITEND}"
      ##-- We force one restart file at the end of the trunk
      OPA_NSTOCK="${NEMO_NITEND}"
      OPA_NIT000="${NEMO_NIT000}"
      OPA_NITEND="${NEMO_NITEND}"
    fi

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

    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 ln_rstart    ${OPA_LRSTAR}
    IGCM_comp_modifyNamelist blocker    namelist_cfg nn_stock     ${OPA_NSTOCK}
    IGCM_comp_modifyNamelist blocker    namelist_cfg nn_rstctl    ${OPA_NRSTDT}
    IGCM_comp_modifyNamelist blocker    namelist_cfg nn_date0     ${PeriodDateBegin}
    IGCM_comp_modifyNamelist nonblocker namelist_cfg ln_meshmask   ${OPA_NMSH}
    IGCM_comp_modifyNamelist blocker    namelist_cfg nn_leapy     ${OPA_NLEAPY}
    
    # Update iodef.xml

    IGCM_debug_Print 1 'Informations into iodef.xml : V1D_ENABLE V5D_ENABLE V1M_ENABLE V1Y_ENABLE '
    IGCM_debug_Print 1 ${V1D_ENABLE}  ${V5D_ENABLE} ${V1M_ENABLE} ${V1Y_ENABLE}

    IGCM_comp_modifyXmlFile nonblocker file_def_nemo-oce.xml 1d_opa enabled ${V1D_ENABLE}
    IGCM_comp_modifyXmlFile nonblocker file_def_nemo-oce.xml 5d_opa enabled ${V5D_ENABLE}
    IGCM_comp_modifyXmlFile nonblocker file_def_nemo-oce.xml 1m_opa enabled ${V1M_ENABLE}
    IGCM_comp_modifyXmlFile nonblocker file_def_nemo-oce.xml 1y_opa enabled ${V1Y_ENABLE}

    IGCM_comp_modifyXmlFile nonblocker file_def_nemo-oce.xml 1d_opa output_level ${opa9_UserChoices_OutputLevel}
    IGCM_comp_modifyXmlFile nonblocker file_def_nemo-oce.xml 5d_opa output_level ${opa9_UserChoices_OutputLevel}
    IGCM_comp_modifyXmlFile nonblocker file_def_nemo-oce.xml 1m_opa output_level ${opa9_UserChoices_OutputLevel}
    IGCM_comp_modifyXmlFile nonblocker file_def_nemo-oce.xml 1y_opa output_level ${opa9_UserChoices_OutputLevel}


    # Update reference year/month/day
    IGCM_date_GetYearMonthDay ${DateBegin} iyear imonth iday
    IGCM_comp_modifyXmlFile force context_nemo.xml ref_year  NONE ${iyear} 
    IGCM_comp_modifyXmlFile force context_nemo.xml ref_month NONE ${imonth} 
    IGCM_comp_modifyXmlFile force context_nemo.xml ref_day   NONE ${iday} 
    
    
    # for MPP and switch to different number of procs for NEMO.  We need to suppres restartopa the second period, 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
    if [ X"$( echo ${config_UserChoices_ExpType} | grep CMIP6 )" != "X" ] ; then
	echo '<context id="nemo" src="./ping_nemo.xml"/>' >> add.tmp
	echo '<context id="nemo" src="./dr2xml_opa9.xml"/>' >> add.tmp
    fi
    cp iodef.xml iodef.xml.tmp
    sed -e "/COMPONENT CONTEXT/r add.tmp" \
        iodef.xml.tmp > iodef.xml
    rm iodef.xml.tmp add.tmp

    #Long Name as global attribute (if LongName is not empty)
    if [ ! "X${config_UserChoices_LongName}" = "X" ] ; then
	listfile=$(ls file_def_nemo*.xml)
	echo "<variable id=\"LongName\" type=\"string\">${config_UserChoices_LongName}</variable>" > add.tmp
	for file in ${listfile}
	do
	    cp ${file} ${file}.tmp
	    sed -e "/<file id/r add.tmp" \
		${file}.tmp > ${file}
	    rm ${file}.tmp 
	done 
	rm add.tmp
    fi

    #Compression level (if CompressionLevel is not empty)
    if [ ! "X${config_UserChoices_CompressionLevel}" = "X" ] ; then
	echo "NetCDF output files compression level is " ${config_UserChoices_CompressionLevel}
    	listfile=$(ls file_def_nemo*.xml)
    	for file in ${listfile}
    	do
	    sed -i -e "s/\(compression_level=\"\)[^\"]*\(\"\)/\1${config_UserChoices_CompressionLevel}\2/" ${file}
    	done
    fi


    IGCM_debug_PopStack "OCE_Update"
}

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

    IGCM_debug_Print 1 FINALIZE OCE !!!

    IGCM_debug_PopStack "OCE_Finalize"
}
