#!/bin/ksh

#D- Driver du script pour STOMATE

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

    RESOL_SBG=ALL

    typeset frequency
    for frequency in ${config_SBG_WriteFrequency} ; do
        case ${frequency} in
            HF|hf) SBG_ok_hf=y ;;
        esac
    done
    
    IGCM_debug_PopStack "SBG_Initialize"
}

#-----------------------------------------------------------------
function SBG_PeriodStart
{
    IGCM_debug_PushStack "SBG_PeriodStart"

    IGCM_debug_PopStack "SBG_PeriodStart"
}

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

    typeset STOMATE_WRITE_STEP

    # 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

    case ${config_SBG_WriteFrequency} in
	*Y|*y) 
	    WriteInYears=$( echo ${config_SBG_WriteFrequency} | awk -F '[yY]' '{print $1}' )
	    PeriodLengthInYears=$( echo ${config_UserChoices_PeriodLength} | awk -F '[yY]' '{print $1}' )
	    (( STOMATE_WRITE_STEP = PeriodLengthInDays * WriteInYears / PeriodLengthInYears )) 

            stomate_enabled=.TRUE.
            stomate_freq=${WriteInYears}y
        ;;
	1M|1m) 
            stomate_enabled=.TRUE.
            stomate_freq=1mo
	    case ${config_UserChoices_PeriodLength} in
	    *Y|*y)
		STOMATE_WRITE_STEP=-1.
		;;
	    *M|*m)
		STOMATE_WRITE_STEP=-1.
		;;
	    *)
		(( STOMATE_WRITE_STEP = $( IGCM_date_DaysInMonth $year $month ) )) ;;
	    esac
	    ;;
	*M|*m) 
	    WriteInMonths=$( echo ${config_SBG_WriteFrequency} | awk -F '[mM]' '{print $1}' )
            stomate_enabled=.TRUE.
            stomate_freq=${WriteInMonths}mo
	    case ${config_UserChoices_PeriodLength} in
	    *Y|*y)
		PeriodLengthInYears=$( echo ${config_UserChoices_PeriodLength} | awk -F '[yY]' '{print $1}' )
		(( STOMATE_WRITE_STEP = 30 )) ;;
	    *M|*m)
		PeriodLengthInMonths=$( echo ${config_UserChoices_PeriodLength} | awk -F '[mM]' '{print $1}' )
		(( STOMATE_WRITE_STEP = PeriodLengthInDays * WriteInMonths / PeriodLengthInMonths )) ;;
	    *)
		(( STOMATE_WRITE_STEP = $( IGCM_date_DaysInMonth $year $month ) )) ;;
	    esac
	    ;;
	5D|5d)
            stomate_enabled=.TRUE.
            stomate_freq=5d
	    (( STOMATE_WRITE_STEP = 5 )) ;;
	1D|1d)
	    stomate_enabled=.TRUE.
            stomate_freq=1d
 	    (( STOMATE_WRITE_STEP = 1 )) ;;
	*s)
	    WriteInSeconds=$( echo ${config_SBG_WriteFrequency} | awk -F '[s]' '{print $1}' )
	    stomate_enabled=.TRUE.
            stomate_freq=${WriteInSeconds}s
	    (( STOMATE_WRITE_STEP = 1 )) ;;
	*) 
	    IGCM_debug_Exit "SBG_Update " ${config_SBG_WriteFrequency} " invalid WriteFrequency : choose in 1Y, 1M, 5D, 1D." 
	    IGCM_debug_Verif_Exit ;;
    esac

    # Modify file_def_orchidee.def if XIOS is activated
    if [ X${orchidee_ol_UserChoices_XIOS} = Xy ] ; then
	# 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}

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

    ORCHIDEE_def STOMATE_OK_STOMATE y

    if [ X${stomate_UserChoices_SPINUP_ANALYTIC} = Xy ] ; then
       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 ))
       ORCHIDEE_def SPINUP_PERIOD ${CycleNb}

    fi

    ORCHIDEE_def STOMATE_HIST_DT ${STOMATE_WRITE_STEP}
    ORCHIDEE_def STOMATE_HISTLEVEL ${stomate_UserChoices_stomate_LEVEL}
    if ( [ ${CumulPeriod} -eq 1 ] && [ "${config_SBG_Restart}" = "n" ] ) ; then
	echo "STOMATE : without restart"
    else
	ORCHIDEE_def STOMATE_RESTART_FILEIN stomate_rest_in.nc
    fi

    if [ X${SBG_ok_hf} = Xy ] ; then 
	ORCHIDEE_def STOMATE_IPCC_HIST_DT 1D
    else
	ORCHIDEE_def STOMATE_IPCC_HIST_DT ${STOMATE_WRITE_STEP}
    fi


    if [ -f CO2.txt ] ; then
        # If this file exist, then read CO2 value and set ATM_CO2 in run.def
        IPCC_CO2=`grep Annee_${year} CO2.txt | awk -F= '{print $2}'`
        ORCHIDEE_def ATM_CO2 ${IPCC_CO2}
    fi


    # Special case using forcesoil executable
    if [ -f forcesoil ] ; then
	# Set STOMATE_CFORCING_NAME
        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
    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
        echo "SPINUP ANALYTIC :  your spinup is successful :"
        echo ${CondSpinup}
        echo "We stop the simulation now. PeriodDateEnd is set to DateEnd."
        PeriodDateEnd=${DateEnd}
      fi
    fi

    IGCM_debug_PopStack "SBG_Finalize"
}
