#!/bin/ksh

#D- Driver du script pour ORCHIDEE

#-----------------------------------------------------------------
function BIOS_Initialize
{
    IGCM_debug_PushStack "BIOS_Initialize"

    RESOL_BIOS=ALL
    
    IGCM_debug_PopStack "BIOS_Initialize"
}

#-----------------------------------------------------------------
function BIOS_Update
{
    IGCM_debug_PushStack "BIOS_Update"

    typeset STOMATE_WRITE_STEP

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

    ORCHIDEE_sed STOMATE_OK_STOMATE y

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

    IGCM_debug_PopStack "BIOS_Update"
}

#-----------------------------------------------------------------
function BIOS_Finalize
{
#set -vx
    IGCM_debug_PushStack "BIOS_Finalize"

    if [ $( IGCM_date_DaysBetweenGregorianDate ${PeriodDateEnd} ${year}1230 ) -ge 0 ] ; then
	IGCM_sys_Put_Out stomate_Cforcing.nc ${R_OUT_BIOS_R}/${config_UserChoices_JobName}_${PeriodDateEnd}_stomate_Cforcing.nc
	IGCM_sys_Put_Out stomate_forcing.nc  ${R_OUT_BIOS_R}/${config_UserChoices_JobName}_${PeriodDateEnd}_stomate_forcing.nc
# 	rm -f stomate_Cforcing.nc
# 	rm -f stomate_forcing.nc
    fi

    IGCM_debug_PopStack "BIOS_Finalize"
}
