#!/bin/ksh

#-----------------------------------------------------------------
function OOL_Initialize
{
    IGCM_debug_PushStack "OOL_Initialize"

     ##- Define variable DefSuffix set in orchidee_ol.card
     ##  This variable is used in orchidee_ol.card to choose
     ##  parameter file (orchidee_pft.def_DefSuffix).
     if [ ! X${orchidee_ol_UserChoices_DefSuffix} = X ] ; then
         DefSuffix=${orchidee_ol_UserChoices_DefSuffix}
     else
         # Default value used if DefSuffix is not set in orchidee_ol.card
         DefSuffix=15pft.1ac
     fi

     IGCM_debug_PopStack "OOL_Initialize"
}

#-----------------------------------------------------------------
function OOL_Update
{
    IGCM_debug_PushStack "OOL_Update"

    # Set TIME_LENGTH in run.def depending on PeriodLenght in config.card
    case ${config_UserChoices_PeriodLength} in
	*M|*m|*D|*d)
	    IGCM_comp_modifyDefFile nonblocker run.def TIME_LENGTH ${PeriodLengthInDays}D
	    ;;
	*s|*Y)
	    IGCM_comp_modifyDefFile nonblocker run.def TIME_LENGTH ${config_UserChoices_PeriodLength}
            ;;
        *)
            IGCM_debug_Exit "OOL_Update " ${config_UserChoices_PeriodLength} " invalid PeriodLength in config.card : choose between 1Y, 1M, 5D, 1D."
            IGCM_debug_Verif_Exit
    esac
    

    # Set TIME_SKIP only if starting without restart file
    if ( ${FirstInitialize} && [ "${config_OOL_Restart}" = "n" ] ) ; then
	# Calculate the TIME_SKIP as difference between the start date and 1th of January the same year
	IGCM_comp_modifyDefFile nonblocker run.def TIME_SKIP $( IGCM_date_DaysBetweenGregorianDate ${DateBegin} ${year}0101 )D
    else
	# Here using restart file, set TIME_SKIP=0
	IGCM_comp_modifyDefFile nonblocker run.def TIME_SKIP 0D
    fi

    # Set RESTART_FILEIN in run.def
    if ( ${FirstInitialize} && [ "${config_OOL_Restart}" = "n" ] ) ; then
	# Set RESTART_FILEIN=NONE in run.def
	IGCM_comp_modifyDefFile blocker run.def RESTART_FILEIN NONE
    else
        # Default option using restart file, set RESTART_FILEIN=driver_rest_in.nc in run.def
	IGCM_comp_modifyDefFile blocker run.def RESTART_FILEIN driver_rest_in.nc
    fi

    # Reset the simulation date as ORCHIDEE understands it for some special cases
    # DRIVER_reset_time=y : take the date from the first time step of the forcing file 
    # DRIVER_reset_time=n : default, take the date from the restart file if existing, else take it from the forcing file
    if ( ${FirstInitialize} &&  [ ${month} = 01 ] && [ ${day} = 01 ] ) ; then
	# Starting a new simulation: take the date from the forcing file instead of from restart file
        IGCM_comp_modifyDefFile nonblocker run.def DRIVER_reset_time y
    elif ( [ X${CyclicYear} = X${config_UserChoices_CyclicBegin} ] && [ ${month} = 01 ] && [ ${day} = 01 ] ) ; then
        # Start a new cycle, take the date from the forcing file instead of from restart file
        IGCM_comp_modifyDefFile nonblocker run.def DRIVER_reset_time y
    else
	# Default option, take the date from the restart file
	IGCM_comp_modifyDefFile nonblocker run.def DRIVER_reset_time n
    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}'`
	if [ X"${IPCC_CO2}" = X ] ; then
            # The grep returned empty variable: stop execution
            IGCM_debug_Exit "The file CO2.txt do not contain the current year."
            IGCM_debug_Verif_Exit
        fi
        IGCM_comp_modifyDefFile nonblocker run.def ATM_CO2 ${IPCC_CO2}
    else
	# The file is not available: take the default value from run.def. 
	# The syntax in run.def must be respected, for example:
        # ATM_CO2 = _AUTO_: DEFAULT = 350.
	IGCM_comp_modifyDefFile nonblocker run.def ATM_CO2 DEFAULT
    fi


    # Activation of XIOS
    if [ X${orchidee_ol_UserChoices_XIOS} = Xy ] ; then
      # Add include of orchidee context in iodef.xml
      # In iodef.xml add on next line after "COMPONENT CONTEXT"
      #  <context id="orchidee" src="./context_orchidee.xml"/>
      echo '<context id="orchidee" src="./context_orchidee.xml"/>' > add.tmp

      # Add inclusion of file context_input_orchidee.xml if this file exists
      if [ -f context_input_orchidee.xml ] ; then
          echo '<context id="orchidee" src="./context_input_orchidee.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
    fi


    # Add LongName as global attribute in all files produced by XIOS (if LongName is not empty)
    # Remove file_def_input_orchidee.xml from the list. 
    if [ ! "X${config_UserChoices_LongName}" = "X" ] ; then
	listfile=$(ls file_def*orchidee.xml | grep -v input)
	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
          
    IGCM_debug_PopStack "OOL_Update"
}

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