#!/bin/ksh

#D- Driver pour ORCHIDEE stomate component

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

    IGCM_debug_PopStack "SBG_Initialize"
}

#-----------------------------------------------------------------
function SBG_Update
{
    IGCM_debug_PushStack "SBG_Update"
    
    # Output management

    # Set default values for stomate output files.
    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. 
    for frequency in ${config_SBG_WriteFrequency} ; do
	case ${frequency} in
	    *Y|*y) 
		NbYears=$( echo ${frequency} | awk -F '[yY]' '{print $1}' )
		NbDaysYear=$( IGCM_date_DaysInYear ${year} )
		stomate_enabled=.TRUE.
		stomate_freq=${NbYears}y ;;
	    *M|*m) 
		NbMonths=$( echo ${frequency} | awk -F '[mM]' '{print $1}' )
		stomate_enabled=.TRUE.
		stomate_freq=${NbMonths}mo ;;
	    *D|*d)
		NbDays=$( echo ${frequency} | awk -F '[dD]' '{print $1}' )
		stomate_enabled=.TRUE.
		stomate_freq=${NbDays}d ;;
	    *) 
		IGCM_debug_Exit "SBG WriteFrequency=${frequency} is invalid. Choose between xY, xM and xD for Stomate." ;;
	esac
    done

    if [ X"$( echo ${config_UserChoices_ExpType} | grep CMIP6 )" != "X" ] ; then       
	stomate_enabled=.FALSE.
    fi

    # Modify file_def_orchidee.xml
    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate1 enabled ${stomate_enabled}
    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate1 output_freq ${stomate_freq}
    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate2 enabled ${stomate_enabled}
    IGCM_comp_modifyXmlFile nonblocker file_def_orchidee.xml stomate2 output_freq ${stomate_freq}
    

    # Define in orchidee.def if restart file should be used
    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

    IGCM_debug_PopStack "SBG_Update"
}

#-----------------------------------------------------------------
function SBG_Finalize
{
    IGCM_debug_PushStack "SBG_Finalize"
    
    IGCM_debug_PopStack "SBG_Finalize"
}
