#!/bin/ksh
## Driver for the component SBG corresponding to the stomate part of ORCHIDEE

#-----------------------------------------------------------------
function SBG_Initialize
{
    IGCM_debug_PushStack "SBG_Initialize"

    IGCM_debug_PopStack "SBG_Initialize"
}

#-----------------------------------------------------------------
function SBG_Update
{
    IGCM_debug_PushStack "SBG_Update"

    # For IOIPSL: get frequency from config.card
    # Set default values for stomate output files.
    # These variables are used only to modify file_def_orchidee.xml if XIOS=y
    stomate_enabled=.FALSE.
    stomate_freq=0s

    # Read WriteFrequency set in config.card section SBG. 
    # Only one choice can be set as WriteFrequency. The same choice will be used for 
    # both stomate_history and stomate_ipcc_history files. 
    case ${config_SBG_WriteFrequency} in
	*Y|*y) 
	    NbYears=$( echo ${config_SBG_WriteFrequency} | awk -F '[yY]' '{print $1}' )
	    NbDaysYear=$( IGCM_date_DaysInYear ${year} )
            stomate_enabled=.TRUE.
            stomate_freq=${NbYears}y
	    (( STOMATE_WRITE_STEP = NbYears * NbDaysYear )) 
        ;;
	*M|*m) 
	    NbMonths=$( echo ${config_SBG_WriteFrequency} | awk -F '[mM]' '{print $1}' )
            stomate_enabled=.TRUE.
            stomate_freq=${NbMonths}mo
	    # Note only 1M possible with IOIPSL!
	    STOMATE_WRITE_STEP=-1. ;;
	*D|*d)
	    NbDays=$( echo ${config_SBG_WriteFrequency} | awk -F '[dD]' '{print $1}' )
            stomate_enabled=.TRUE.
            stomate_freq=${NbDays}d
	    STOMATE_WRITE_STEP=${NbDays} ;;
    esac

    # Modify file_def_orchidee.xml if XIOS is activated using information in stomate.card
    # Settings in config.card WriteFrequency are not used any more.
    if [ X${orchideedriver_UserChoices_XIOS} = Xy ] ; then

	# Modify file_def_orchidee.xml file using settings from stomate.card
	# We here suppose that for each file, in stomate.card UserChoices section, if the parameter 
	# output_level_filename is set, then also output_freq_filename must be set. The existance of output_freq_filename will not be checked. 
	# If output_level_filename=NONE or if it is not set, the corresponding file will be deactivated.

	if [ X${stomate_UserChoices_output_level_stomate_history} = X ] || [ X${stomate_UserChoices_output_level_stomate_history} = XNONE ] ; then
	    # output_level_stomate_history is not set in stomate.card or it is set to NONE.
	    # Deactivate the file.
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate1 enabled .FALSE.
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate1 output_level 0
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate1 output_freq 1mo
	else
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate1 enabled      .TRUE.
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate1 output_level ${stomate_UserChoices_output_level_stomate_history}
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate1 output_freq  ${stomate_UserChoices_output_freq_stomate_history}
	fi

	if [ X${stomate_UserChoices_output_level_stomate_ipcc_history} = X ] || [ X${stomate_UserChoices_output_level_stomate_ipcc_history} = XNONE ] ; then
	    # output_level_stomate_ipcc_history is not set in stomate.card or it is set to NONE.
	    # Deactivate the file.
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate2 enabled .FALSE.
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate2 output_level 0
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate2 output_freq 1mo
	else
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate2 enabled      .TRUE.
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate2 output_level ${stomate_UserChoices_output_level_stomate_ipcc_history}
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate2 output_freq  ${stomate_UserChoices_output_freq_stomate_ipcc_history}
	fi

	if [ X${stomate_UserChoices_output_level_stomate_history_4dim} = X ] || [ X${stomate_UserChoices_output_level_stomate_history_4dim} = XNONE ] ; then
	    # output_level_stomate_history_4dim is not set in stomate.card or it is set to NONE.
	    # Deactivate the file.
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate3 enabled .FALSE.
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate3 output_level 0
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate3 output_freq 1mo
	else
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate3 enabled      .TRUE.
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate3 output_level ${stomate_UserChoices_output_level_stomate_history_4dim}
	    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate3 output_freq  ${stomate_UserChoices_output_freq_stomate_history_4dim}
	fi

        # Deactivate stomate IOIPSL output
	(( STOMATE_WRITE_STEP = 0 ))
    fi


    if [ X${stomate_UserChoices_SPINUP_ANALYTIC} = Xy ] ; then
       IGCM_comp_modifyDefFile nonblocker orchidee.def SPINUP_ANALYTIC y
      
       # Test if CyclicBegin and CyclicEnd is set in config.card
       if ( [ X${config_UserChoices_CyclicBegin} = X ] || [ X${config_UserChoices_CyclicEnd} = X ] ) ; then
           IGCM_debug_Exit "CyclicBegin and CyclicEnd must be set in config.card to run option spinup_analytic."
       fi
       # Calculate and set number of years of forcing data
       CycleNb=$(( ${config_UserChoices_CyclicEnd} - ${config_UserChoices_CyclicBegin} + 1 ))
       IGCM_comp_modifyDefFile nonblocker orchidee.def SPINUP_PERIOD ${CycleNb}
    else
	IGCM_comp_modifyDefFile nonblocker orchidee.def SPINUP_ANALYTIC n
	IGCM_comp_modifyDefFile nonblocker orchidee.def SPINUP_PERIOD -1
    fi

    IGCM_comp_modifyDefFile nonblocker orchidee.def STOMATE_HIST_DT ${STOMATE_WRITE_STEP}
    IGCM_comp_modifyDefFile nonblocker orchidee.def STOMATE_IPCC_HIST_DT ${STOMATE_WRITE_STEP}

    if ( [ ${CumulPeriod} -eq 1 ] && [ "${config_SBG_Restart}" = "n" ] ) ; then
	echo "STOMATE : without restart"
	IGCM_comp_modifyDefFile blocker orchidee.def STOMATE_RESTART_FILEIN NONE
    else
	IGCM_comp_modifyDefFile blocker orchidee.def STOMATE_RESTART_FILEIN stomate_rest_in.nc
    fi


    # Special case using forcesoil executable
    if [ -f forcesoil ] ; then
	# Set STOMATE_CFORCING_NAME
        IGCM_comp_modifyDefFile nonblocker orchidee.def STOMATE_CFORCING_NAME stomate_Cforcing.nc

	# Check if restart file is missing
	if ( [ ${CumulPeriod} -eq 1 ] && [ "${config_SBG_Restart}" = "n" ] ) ; then
            IGCM_debug_Exit "YOU MUST USE OLD STOMATE RESTART FILE WITH THE JOB FORCESOIL."
            IGCM_debug_Verif_Exit
	fi
    else
	IGCM_comp_modifyDefFile nonblocker orchidee.def STOMATE_CFORCING_NAME NONE
    fi


    # Modify in orchidee.def NINPUT_UPDATE if it is set in stomate.card section UserChoices
    # NINPUT_UPDATE inidcates if the nitrogen maps should be updated and at which frequency
    if [ ! X${stomate_UserChoices_NINPUT_UPDATE} = X ] ; then
	# Take the value from stomate.card
	IGCM_comp_modifyDefFile nonblocker orchidee.def NINPUT_UPDATE   ${stomate_UserChoices_NINPUT_UPDATE}
    else
        # Set default value 0Y
        IGCM_comp_modifyDefFile nonblocker orchidee.def NINPUT_UPDATE 0Y
    fi

    # Modify in orchidee.def STOMATE_IMPOSE_CN if it is set in stomate.card section UserChoices
    # STOMATE_IMPOSE_CN inidcates if the nitrogen should be imposed or not. 
    if [ ! X${stomate_UserChoices_STOMATE_IMPOSE_CN} = X ] ; then
        # Take the value from stomate.card
        IGCM_comp_modifyDefFile nonblocker orchidee.def STOMATE_IMPOSE_CN   ${stomate_UserChoices_STOMATE_IMPOSE_CN}
    else
        # Set default value n (nitrogen is not imposed)
        IGCM_comp_modifyDefFile nonblocker orchidee.def STOMATE_IMPOSE_CN n
    fi

    IGCM_debug_PopStack "SBG_Update"
}

#-----------------------------------------------------------------
function SBG_Finalize
{
    IGCM_debug_PushStack "SBG_Finalize"

#   Check if equilibrium is reached for spinup analytic
#   and if true stop the simulation in the end of this period.
    if [ X${stomate_UserChoices_SPINUP_ANALYTIC} = Xy ] ; then
      CondSpinup=$(grep -a  "Equilibrium for carbon pools is reached"  out_*)
      if [ X"${CondSpinup}" != X ] ; then
	  IGCM_debug_Print 1 "SPINUP ANALYTIC :  your spinup is successful :"
	  IGCM_debug_Print 1 ${CondSpinup}
	  IGCM_debug_Print 1  "You can now stop the simulation if you want."
      fi
    fi

    IGCM_debug_PopStack "SBG_Finalize"
}
