#!/bin/ksh
#-----------------------------------------------------------------
function LMDZ_sed
{
# Usage : LMDZ_sed filedef var_name myvalue
#         In file filedef modify the line containing var_name=xxx into var_name=myvalue
    IGCM_debug_PushStack "LMDZ_sed"
    
    # Test if the fichier exist
    if [ ! -f ${1} ] ; then
	echo "WARNING : ${1} file does not exist. Following will not be done : LMDZ_sed : ${1} ${2} ${3}"
        IGCM_debug_PopStack "LMDZ_sed"
	return
    fi

    sed -e "s/^${2}\ *=.*/${2}= ${3}/" ${1} > ${1}.tmp
    RET=$?
    echo "LMDZ_sed : ${1} ${2} ${3}"
    \mv ${1}.tmp ${1}

    IGCM_debug_PopStack "LMDZ_sed"
    return $RET
}

function LMDZ_sed_default
{
# Usage : LMDZ_sed_default filedef var_name
#         In file filedef modify the line  "var_name=xxx DEFAULT= myvalue"
#         into "var_name=myvalue"
    IGCM_debug_PushStack "LMDZ_sed_default"

    DefValue=$( grep ${2} ${1}  | awk -F"DEFAULT.=*" '{print $2}')

    LMDZ_sed  ${1} ${2} $DefValue
    IGCM_debug_PopStack "LMDZ_sed_default"
    return $RET
}

function LMDZ_sed_xml
{
# Usage : LMDZ_sed_xml xml_file output_file attribute value 
#         In file xml_file modify at the line containing id="output_file" the attribute "attribute=xxx" into "attribute=value"
    
    # Test if the fichier exist
    if [ ! -f ${1} ] ; then
	echo "WARNING : ${1} file does not exist. Following will not be done : LMDZ_sed : ${1} ${2} ${3} ${4}"
        IGCM_debug_PopStack "LMDZ_sed"
	return
    fi
    sed -e "/id=\"${2}\"/s/\(${3}=\"\)[^\"]*\(\"\)/\1${4}\2/" ${1} > ${1}.tmp
    RET=$?
    echo "LMDZ_sed : ${1} ${2} ${3} ${4}"
    \mv ${1}.tmp ${1}

    return $RET
}

function ATM_Initialize
{
    IGCM_debug_PushStack "ATM_Initialize"

    RESOL_ATM=$( echo $RESOL | awk "-Fx" '{print $2}' | awk "-F-" '{print $1}')

    [ -f ${SUBMIT_DIR}/../.resol ] && eval $(grep RESOL_ATM_3D ${SUBMIT_DIR}/../.resol) || RESOL_ATM_3D=96x95x39

    RESOL_ATM_Z=$( echo ${RESOL_ATM_3D} | awk "-Fx" '{print $3}' )
    RESOL_ATM_X=$( echo ${RESOL_ATM_3D} | awk "-Fx" '{print $1}' )
    RESOL_ATM_Y=$( echo ${RESOL_ATM_3D} | awk "-Fx" '{print $2}' )
    RESOL_ATM_XY="${RESOL_ATM_X}x${RESOL_ATM_Y}"
    FreqCoupling=${oasis_UserChoices_FreqCoupling:-86400}

    ##-- Calendar type for LMDZ and create_etat0_limit
    case ${config_UserChoices_CalendarType} in
        leap|gregorian)
            CalendarTypeForLmdz=earth_366d
	    CalendarTypeForCreate=gregorian;;
        noleap)
            CalendarTypeForLmdz=earth_365d
            CalendarTypeForCreate=${CalendarTypeForLmdz};;
        360d)
            CalendarTypeForLmdz=earth_360d
            CalendarTypeForCreate=${CalendarTypeForLmdz};;
        *)
            CalendarTypeForLmdz=earth_360d
            CalendarTypeForCreate=${CalendarTypeForLmdz}
    esac

    ##- LMDZ physics version
    ##  Read LMDZ_Physics option in lmdz.card, if not present take default value AP (old physics) 
    if [ ! X${lmdz_UserChoices_LMDZ_Physics} = X ] ; then
	LMDZ_Physics=${lmdz_UserChoices_LMDZ_Physics}
    else
	LMDZ_Physics=AP
    fi
    echo LMDZ physics version : ${LMDZ_Physics}

    ##- Create_etat0_limit version
    ##  Define variable CREATE only if it is set in lmdz.card section UserChoices.
    ##  This variable is only used in lmdz.card to choose input files.
    if [ ! X${lmdz_UserChoices_CREATE} = X ] ; then
	IGCM_card_DefineVariableFromOption ${SUBMIT_DIR}/COMP/lmdz.card UserChoices CREATE
	CREATE=${lmdz_UserChoices_CREATE}
	echo create_etat0_limit version : ${CREATE}
    fi


    ## - LMDZ choice of config.def file
    ##   ConfType must be set in lmdz.card
    ConfType=${lmdz_UserChoices_ConfType}

    ##- LMDZ output level, to be set in lmdz.card
    if [ X${lmdz_UserChoices_OutLevel} = X ] ; then
	# OutLevel is not set. Take default value low.
	OutLevel=low
    else
	OutLevel=${lmdz_UserChoices_OutLevel}
    fi

    ##-- Output frequency purpose ....
    ##--  Initialisation  ....
    ok_mensuel=n
    ok_journe=n
    ok_hf=n
    ok_hf3h=n
    ok_hf3hm=n
    ok_stn=n

    case ${config_UserChoices_PeriodLength} in
	1Y|1y|1M|1m) ok_mensuel=y ;;
	5D|5d|1D|1d) ok_journe=y ;;
    esac

    for frequency in ${config_ATM_WriteFrequency} ; do
	case ${frequency} in
	    1M|1m) ok_mensuel=y ;;
	esac
	case ${frequency} in
	    5D|5d|1D|1d) ok_journe=y ;;
	esac
	case ${frequency} in
	    HF|hf) ok_hf=y ;;
	esac
	case ${frequency} in 
	    HF3h|hf3h) ok_hf3h=y ;;
	esac
	case ${frequency} in 
	    HF3hm|hf3hm) ok_hf3hm=y ;;
	esac
	case ${frequency} in
	    STN|stn) ok_stn=y ;;
	esac
    done

    ## Read LMDZ_NbPeriod_adjust option in lmdz.card 
    if [ X"${lmdz_UserChoices_LMDZ_NbPeriod_adjust}" = X"" ] ; then
	# The variable is not in lmdz.card, set default value
	LMDZ_NbPeriod_adjust=0
    else	
	LMDZ_NbPeriod_adjust=${lmdz_UserChoices_LMDZ_NbPeriod_adjust}
    fi

    if [ ${LMDZ_NbPeriod_adjust} -eq 0 ] ; then
	LMDZ_Bands_file_name=${lmdz_UserChoices_LMDZ_Bands_file_name}
    fi


    ##  Read LMDZ_COSP_OK in lmdz.card
    if [ ! X${lmdz_UserChoices_LMDZ_COSP_OK} = X ] ; then
	LMDZ_COSP_OK=${lmdz_UserChoices_LMDZ_COSP_OK}
    else
	LMDZ_COSP_OK=n
    fi
    ##  Read LMDZ_COSP_monthly in lmdz.card
    if [ ! X${lmdz_UserChoices_LMDZ_COSP_monthly} = X ] ; then
	LMDZ_COSP_monthly=${lmdz_UserChoices_LMDZ_COSP_monthly}
    else
	LMDZ_COSP_monthly=n
    fi
    ##  Read LMDZ_COSP_daily in lmdz.card
    if [ ! X${lmdz_UserChoices_LMDZ_COSP_daily} = X ] ; then
	LMDZ_COSP_daily=${lmdz_UserChoices_LMDZ_COSP_daily}
    else
	LMDZ_COSP_daily=n
    fi
    ##  Read LMDZ_COSP_hf in lmdz.card
    if [ ! X${lmdz_UserChoices_LMDZ_COSP_hf} = X ] ; then
	LMDZ_COSP_hf=${lmdz_UserChoices_LMDZ_COSP_hf}
    else
	LMDZ_COSP_hf=n
    fi

    ##  Read LMDZ_NMC_monthly in lmdz.card
    if [ ! X${lmdz_UserChoices_LMDZ_NMC_monthly} = X ] ; then
	LMDZ_NMC_monthly=${lmdz_UserChoices_LMDZ_NMC_monthly}
    else
	LMDZ_NMC_monthly=n
    fi

    ## Read LMDZ_NMC_daily in lmdz.card
    if [ ! X${lmdz_UserChoices_LMDZ_NMC_daily} = X ] ; then
	LMDZ_NMC_daily=${lmdz_UserChoices_LMDZ_NMC_daily}
    else
	LMDZ_NMC_daily=n
    fi
    
    ## Read LMDZ_NMC_hf in lmdz.card
    if [ ! X${lmdz_UserChoices_LMDZ_NMC_hf} = X ] ; then
	LMDZ_NMC_hf=${lmdz_UserChoices_LMDZ_NMC_hf}
    else
	LMDZ_NMC_hf=n
    fi


    IGCM_debug_PopStack "ATM_Initialize"
}

#-----------------------------------------------------------------
function ATM_Update
{
    IGCM_debug_PushStack "ATM_Update"


    case ${config_UserChoices_PeriodLength} in
        *Y|*y) 
               LMDZ_ecrit_ISCCP=30.
               LMDZ_periodav=30.
               if [ "${config_UserChoices_CalendarType}" != "360d" ] ; then
                  echo Do not consider following warning if your running create_etat0_limit :
                  echo WARNING !!! For lmdz : calendartype in config.card. PeriodLength=1Y allowed only for CalendarType=360d 
	       fi
               ;;
        *)
               LMDZ_ecrit_ISCCP=${PeriodLengthInDays}.
               LMDZ_periodav=${PeriodLengthInDays}.
               ;;
    esac
  
    ##-- Remise ou non a zero de la date initiale de LMDZ pour le fichier run.def
    if [ ${CumulPeriod} -eq 1 ] ; then
	RAZ_DATE=1
    else
	RAZ_DATE=0
    fi

    ## Algorithme for special treatment for Bands_xxx file
    ## For CumulPeriod=1 ; 
    ##        IF NbPeriod_Adjust = 0 ; set LMDZ_adjust=n
    ##                                IF LMDZ_Bands_file_name was given in lmdz.card THEN Get Bands file directly from server. Store it later with _0 suffix.
    ##                                IF no LMDZ_Bands_file_name was given, start without Bands file. Store it later with _0 suffix.
    ##        ELSE set LMDZ_adjust=y ; start without Bands file ; Store it later in PARAM/ directory in submit directory with suffix _1 ;
    ##
    ## For CumulPeriod=2 to LMDZ_NbPeriod_adjust ; 
    ##       Get Bands file from PARAM/ in submit directory (CumulPeriod-1) ; set LMDZ_adjust=y ; Store Bands file in PARAM/ ;
    ##
    ## For CumulPeriod > LMDZ_NbPeriod_adjust ; LMDZ_adjust=n ; Get Bands file from PARAM/ ; Do not store ;

    if [ ${CumulPeriod} -eq 1 ] ; then
        if [ ${LMDZ_NbPeriod_adjust} -eq 0 ] ; then
	    if [ ! X${LMDZ_Bands_file_name} = X ] ; then
		IGCM_sys_Get ${LMDZ_Bands_file_name} Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat 
		IGCM_sys_Chmod u+w Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat
		IGCM_debug_Print 1 "Bands file forced to ${LMDZ_Bands_file_name} and stored in ${config_UserChoices_JobName}_Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat_0"
	    fi
        fi
    fi

    LMDZ_adjust=n
    [ ${CumulPeriod} -le ${LMDZ_NbPeriod_adjust} ] && LMDZ_adjust=y

    RefPeriod=${LMDZ_NbPeriod_adjust} #0 to use a Bands file from Restart
    [ ${CumulPeriod} -le ${LMDZ_NbPeriod_adjust} ] && (( RefPeriod = ${CumulPeriod} - 1 )) 

    # Get Bands file from PARAM directory if file exist
    if ( [ ${CumulPeriod} -gt 1 ] && [ -f ${SUBMIT_DIR}/PARAM/${config_UserChoices_JobName}_Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat_${RefPeriod} ] ) ; then
        IGCM_sys_Cp ${SUBMIT_DIR}/PARAM/${config_UserChoices_JobName}_Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat_${RefPeriod} Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat
        IGCM_sys_Chmod u+w Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat
    fi

    ##-- GHG forcing :
    ##   If forcing file exist in run directory, read values for the current year and modify config.def
    if [ -f SOLARANDVOLCANOES.txt ] ; then
	IPCC_SOLAR=`grep Annee_${year} SOLARANDVOLCANOES.txt | awk -F= '{print $2}'`
	LMDZ_sed config.def solaire     ${IPCC_SOLAR}
    else
	LMDZ_sed_default config.def solaire
    fi
    if [ -f CO2.txt ] ; then
	IPCC_CO2=`grep Annee_${year} CO2.txt | awk -F= '{print $2}'`
	LMDZ_sed config.def co2_ppm     ${IPCC_CO2}
    else
	LMDZ_sed_default config.def co2_ppm
    fi


    if [ -f CH4.txt ] ; then
	IPCC_CH4=`grep Annee_${year} CH4.txt | awk -F= '{print $2}'`
	LMDZ_sed config.def CH4_ppb     ${IPCC_CH4}
    else
	LMDZ_sed_default config.def CH4_ppb
    fi
    if [ -f N2O.txt ] ; then
	IPCC_N2O=`grep Annee_${year} N2O.txt | awk -F= '{print $2}'`
	LMDZ_sed config.def N2O_ppb     ${IPCC_N2O}
    else
	LMDZ_sed_default config.def N2O_ppb
    fi
    if [ -f CFC11.txt ] ; then
	IPCC_CFC11=`grep Annee_${year} CFC11.txt | awk -F= '{print $2}'`
	LMDZ_sed config.def CFC11_ppt   ${IPCC_CFC11}
    else
	LMDZ_sed_default config.def CFC11_ppt
    fi
    if [ -f CFC12.txt ] ; then
	IPCC_CFC12=`grep Annee_${year} CFC12.txt | awk -F= '{print $2}'`
	LMDZ_sed config.def CFC12_ppt   ${IPCC_CFC12}
    else
	LMDZ_sed_default config.def CFC12_ppt
    fi

    ## Coupling Time Step
    LMDZ_t_coupl=${oasis_UserChoices_FreqCoupling:-${lmdz_UserChoices_t_coupl}}
    IGCM_debug_Print 3 "LMDZ_t_coupl "   ${LMDZ_t_coupl}
    LMDZ_sed config.def t_coupl   ${LMDZ_t_coupl}

    ##-- Add special treatement for CARBON CYCLE
    if [ X"${lmdz_UserChoices_CARBON_CYCLE}" = X"control" ] || [ X"${lmdz_UserChoices_CARBON_CYCLE}" = X"historical" ] ; then
	ATM_Carbon_Update
    fi


    ##-- Set LMDZ_COSP_daily1979=y in section UserChoices in lmdz.card to activate 
    ##   COSP daily output for years 1979 and later (mandatory for historical CMIP5 run).
    if ([ X"${lmdz_UserChoices_LMDZ_COSP_daily1979}" = X"y" ] &&  [ ${year} -ge 1979 ]) ; then
	LMDZ_COSP_daily=y
    fi


    ## output.def parameters
    #  columns in phys_output_filekeys refer to the filenames given in phys_out_filenames in output.def :  
    #                                            histmth       histday        histhf    histfh3h   histhf3hm   histstn
    LMDZ_sed output.def phys_out_filekeys       "${ok_mensuel} ${ok_journe}   ${ok_hf}  ${ok_hf3h} ${ok_hf3hm} ${ok_stn}"
    LMDZ_sed output.def ecrit_ISCCP ${LMDZ_ecrit_ISCCP}
    LMDZ_sed output.def ok_cosp     ${LMDZ_COSP_OK}
    LMDZ_sed output.def ok_mensuelCOSP  ${LMDZ_COSP_monthly}
    LMDZ_sed output.def ok_journeCOSP   ${LMDZ_COSP_daily}
    LMDZ_sed output.def ok_hfCOSP   ${LMDZ_COSP_hf}
    LMDZ_sed output.def ok_histNMC  "${LMDZ_NMC_monthly} ${LMDZ_NMC_daily} ${LMDZ_NMC_hf}"

    # XIOS XML definition
    # Default init : files are desactivated
	LMDZ_sed_xml file_def_histmth_lmdz.xml histmth enabled .FALSE. 
	LMDZ_sed_xml file_def_histday_lmdz.xml histday enabled .FALSE. 
	LMDZ_sed_xml file_def_histhf_lmdz.xml histhf enabled .FALSE.
	LMDZ_sed_xml file_def_histfh3h_lmdz.xml histfh3h enabled .FALSE.
	LMDZ_sed_xml file_def_histhf3hm_lmdz.xml histfh3hm enabled .FALSE.
	LMDZ_sed_xml file_def_histstn_lmdz.xml histstn enabled .FALSE.
	LMDZ_sed_xml file_def_histmthNMC_lmdz.xml histmthNMC enabled .FALSE.
	LMDZ_sed_xml file_def_histdayNMC_lmdz.xml histdayNMC enabled .FALSE.
	LMDZ_sed_xml file_def_histhfNMC_lmdz.xml histhfNMC enabled .FALSE.
	if [ X${lmdz_UserChoices_XIOS}  = Xy ] ; then
    # Default output level : 5
	    LMDZ_sed_xml file_def_histmth_lmdz.xml histmth output_level 5 
	    LMDZ_sed_xml file_def_histday_lmdz.xml histday output_level 5 
	    LMDZ_sed_xml file_def_histhf_lmdz.xml histhf output_level 5
	    LMDZ_sed_xml file_def_histfh3h_lmdz.xml histfh3h output_level 5
	    LMDZ_sed_xml file_def_histhf3hm_lmdz.xml histfh3hm output_level 5
	    LMDZ_sed_xml file_def_histstn_lmdz.xml histstn output_level 5
	    LMDZ_sed_xml file_def_histmthNMC_lmdz.xml histmthNMC output_level 5
	    LMDZ_sed_xml file_def_histdayNMC_lmdz.xml histdayNMC output_level 5
	    LMDZ_sed_xml file_def_histhfNMC_lmdz.xml histhfNMC output_level 5
     # Filling of XML files 
	if [ X${ok_mensuel} = Xy ] ; then
	    LMDZ_sed_xml file_def_histmth_lmdz.xml histmth enabled .TRUE. 
	    LMDZ_sed_xml file_def_histmth_lmdz.xml histmth output_freq 1mo
	    LMDZ_sed_xml file_def_histmth_lmdz.xml histmth name histmth
	fi
	if [ X${ok_journe} = Xy ] ; then	
	    LMDZ_sed_xml file_def_histday_lmdz.xml histday enabled .TRUE. 
	    LMDZ_sed_xml file_def_histday_lmdz.xml histday output_freq 1d
	    LMDZ_sed_xml file_def_histday_lmdz.xml histday name histday
	    if [ X${OutLevel} = Xlow ] || [ X${OutLevel} = Xmedium ] ; then
		LMDZ_sed_xml file_def_histday_lmdz.xml histday output_level 2
	    fi
	fi
	if [ X${ok_hf} = Xy ] ; then
	    LMDZ_sed_xml file_def_histhf_lmdz.xml histhf enabled .TRUE. 
	    LMDZ_sed_xml file_def_histhf_lmdz.xml histhf output_freq 6h
	    LMDZ_sed_xml file_def_histhf_lmdz.xml histhf name histhf
	    if [ X${OutLevel} = Xlow ] ; then
		LMDZ_sed_xml file_def_histhf_lmdz.xml histhf output_level 2
	    fi
	fi	
	if [ X${ok_hf3h} = Xy ] ; then
	    LMDZ_sed_xml file_def_histhf3h_lmdz.xml histhf3h enabled .TRUE. 
	    LMDZ_sed_xml file_def_histhf3h_lmdz.xml histhf3h output_freq 3h
	    LMDZ_sed_xml file_def_histhf3h_lmdz.xml histhf3h name histhf3h
	fi	
	if [ X${ok_hf3hm} = Xy ] ; then
	    LMDZ_sed_xml file_def_histhf3hm_lmdz.xml histhf3hm enabled .TRUE. 
	    LMDZ_sed_xml file_def_histhf3hm_lmdz.xml histhf3hm output_freq 3h
	    LMDZ_sed_xml file_def_histhf3hm_lmdz.xml histhf3hm name histhf3hm
	fi
	if [ X${ok_stn} = Xy ] ; then
	    LMDZ_sed_xml file_def_histstn_lmdz.xml histstn enabled .TRUE. 
	    LMDZ_sed_xml file_def_histstn_lmdz.xml histstn output_freq 1800s
	    LMDZ_sed_xml file_def_histstn_lmdz.xml histstn name histstn
	fi
	if [ X${LMDZ_NMC_monthly} = Xy ] ; then
	    LMDZ_sed_xml file_def_histmthNMC_lmdz.xml histmthNMC enabled .TRUE. 
	    LMDZ_sed_xml file_def_histmthNMC_lmdz.xml histmthNMC output_freq 1mo
	    LMDZ_sed_xml file_def_histmthNMC_lmdz.xml histmthNMC name histmthNMC
	fi
	if [ X${LMDZ_NMC_daily} = Xy ] ; then
	    LMDZ_sed_xml file_def_histdayNMC_lmdz.xml histdayNMC enabled .TRUE. 
	    LMDZ_sed_xml file_def_histdayNMC_lmdz.xml histdayNMC output_freq 1d
	    LMDZ_sed_xml file_def_histdayNMC_lmdz.xml histdayNMC name histdayNMC
	fi
	if [ X${LMDZ_NMC_hf} = Xy ] ; then
	    LMDZ_sed_xml file_def_histhfNMC_lmdz.xml histhfNMC enabled .TRUE. 
	    LMDZ_sed_xml file_def_histhfNMC_lmdz.xml histhfNMC output_freq 6h
	    LMDZ_sed_xml file_def_histhfNMC_lmdz.xml histhfNMC name histhfNMC
	fi
    fi

    ## gcm.def parameters : 
    # Modification only for new physics
    if [ X${LMDZ_Physics} = X"AP" ] ; then
        LMDZ_sed gcm.def iphysiq     10
    else
        LMDZ_sed_default gcm.def iphysiq
    fi


    ## run.def parameters
    LMDZ_sed run.def dayref   ${InitDay}
    LMDZ_sed run.def nday     ${PeriodLengthInDays}
    LMDZ_sed run.def raz_date ${RAZ_DATE}
    LMDZ_sed run.def periodav ${LMDZ_periodav}
    LMDZ_sed run.def adjust   ${LMDZ_adjust}

    # Set anneeref different for gcm and ce0l
    # Variable calend is different for a run with create_etat0_limit and the gcm
    # Test if executable create_etat0_limit is present and lmdz.x is not present
    if [ -f create_etat0_limit* ] || [ -f ce0l* ] && [ ! -f lmdz.x ] ; then
	# for case ce0l : always take current year
	LMDZ_sed run.def anneeref ${year}
	LMDZ_sed run.def calend   ${CalendarTypeForCreate}
    else
	# for case gcm : take first year of simulation
	LMDZ_sed run.def anneeref ${InitYear}
	LMDZ_sed run.def calend   ${CalendarTypeForLmdz}
    fi

    # Activate creation of file grilles_gcm.nc only at first period
    if [ ${CumulPeriod} -eq 1 ] ; then
	LMDZ_sed run.def grilles_gcm_netcdf y
    else
	LMDZ_sed run.def grilles_gcm_netcdf n
    fi

    ## Determine from the variable ListOfComponents in config.card coupling to external models 
    ## and set corresponding parameters in run.def
    echo ListOfComponents now running : ${config_ListOfComponents[*]}

    if [ X${config_ListOfComponents_SRF} = Xorchidee ] ; then
	echo "Activate ORCHIDEE, set VEGET=y in run.def"
	LMDZ_sed run.def VEGET y
    else
	echo "No ORCHIDEE, set VEGET=n in run.def"
	LMDZ_sed run.def VEGET n
    fi

    if [ X${config_ListOfComponents_CPL} = Xoasis ] ; then
	echo "Activate coupling to ocean, set type_ocean=couple in run.def"
	LMDZ_sed run.def type_ocean couple
    else
	echo "LMDZ is running in forced mode without ocean model, set type_ocean=force in run.def"
	LMDZ_sed run.def type_ocean force
    fi

    if [ X${config_ListOfComponents_CHM} = Xinca ] ; then
	echo "Activate coupling to INCA, set type_trac=inca in run.def"
	LMDZ_sed run.def type_trac inca
    elif [ X${config_ListOfComponents_CHM} = Xreprobus ] ; then
	echo "Activate coupling to REPROBUS, set type_trac=repr in run.def"
	LMDZ_sed run.def type_trac repr
        LMDZ_sed run.def config_inca none
    else
	echo "No coupling to chemistry model, set type_trac=lmdz in run.def"
	LMDZ_sed run.def type_trac lmdz
        LMDZ_sed run.def config_inca none
    fi


    # config.def : Activate direct radiative effect if ok_ade=y
    if [ ! X${lmdz_UserChoices_ok_ade} = X ]; then 
	LMDZ_sed config.def ok_ade ${lmdz_UserChoices_ok_ade}
    else
	LMDZ_sed config.def ok_ade n
    fi 

    # config.def : Activate indirect radiative effect if ok_aie=y
    if [ ! X${lmdz_UserChoices_ok_aie} = X ]; then 
	LMDZ_sed config.def ok_aie ${lmdz_UserChoices_ok_aie}
    else
	LMDZ_sed config.def ok_aie n
    fi 

    # config.def : Activate online aerosol coupled model if aerosol_couple=y
    if [ ! X${lmdz_UserChoices_aerosol_couple} = X ]; then 
	LMDZ_sed config.def aerosol_couple ${lmdz_UserChoices_aerosol_couple}
    else
	LMDZ_sed config.def aerosol_couple n
    fi 

    # config.def : Activate reading of ozone in climatology if read_climoz=2
    if [ ! X${lmdz_UserChoices_read_climoz} = X ]; then 
	LMDZ_sed config.def read_climoz ${lmdz_UserChoices_read_climoz}
    else
	LMDZ_sed config.def read_climoz 0	
    fi 

    # config.def : Choose aerosol use in radiative effect 
    #  type of coupled aerosol =1 (default) =2 => bc  only =3 => pom only =4 => seasalt only 
    # =5 => dust only =6 => all aerosol    
    if [ ! X${lmdz_UserChoices_flag_aerosol} = X ]; then 
	LMDZ_sed config.def flag_aerosol ${lmdz_UserChoices_flag_aerosol}
    else
	LMDZ_sed config.def flag_aerosol 0
    fi 

    # config.def : Activate calcul of Cloud droplet number concentration if ok_cdnc=y
    if [ ! X${lmdz_UserChoices_ok_cdnc} = X ]; then 
	LMDZ_sed config.def ok_cdnc ${lmdz_UserChoices_ok_cdnc}
    else
	LMDZ_sed config.def ok_cdnc n	
    fi 

    # guide.def : Activate nudging if ok_guide=y set in lmdz.card
    if [ ! X${lmdz_UserChoices_ok_guide} = X ] ; then
	LMDZ_sed guide.def ok_guide  ${lmdz_UserChoices_ok_guide}
    else
	LMDZ_sed guide.def ok_guide n
    fi

    ## Read ByPass_hgardfou_teta option in lmdz.card --> divide teta* by 2 if [ $ByPass_hgardfou_teta = 1 ]
    ByPass_hgardfou_teta=${lmdz_UserChoices_ByPass_hgardfou_teta}
    if [ X"${ByPass_hgardfou_teta}" = X"y" ] ; then
	awk '{ if ($0 ~ /^teta.*=/) {split($0,a,"=") ; print a[1]"="a[2]/2"."} else print $0}' gcm.def > gcm.def.tmp
	IGCM_sys_Mv gcm.def.tmp gcm.def
	echo
	IGCM_debug_Print 1 "ByPass_hgardfou_teta : ^teta*/2 in gcm.def"
	echo
	cat gcm.def
	ByPass_hgardfou_teta=n
	IGCM_card_WriteOption ${SUBMIT_DIR}/COMP/lmdz.card UserChoices ByPass_hgardfou_teta "${ByPass_hgardfou_teta}"
    fi

    ## Read ByPass_hgardfou_mats option in lmdz.card --> purmats=y 2 if [ $ByPass_hgardfou_mats = 1 ]
    ByPass_hgardfou_mats=${lmdz_UserChoices_ByPass_hgardfou_mats}
    if [ X"${ByPass_hgardfou_mats}" = X"y" ] ; then
	sed -e "s/^purmats=.*/purmats=y/" gcm.def > gcm.def.tmp
        IGCM_sys_Mv gcm.def.tmp gcm.def
        echo
        IGCM_debug_Print 1 "ByPass_hgardfou_mats : purmats=y in gcm.def"
        echo
        cat gcm.def
        ByPass_hgardfou_mats=n
        IGCM_card_WriteOption ${SUBMIT_DIR}/COMP/lmdz.card UserChoices ByPass_hgardfou_mats "${ByPass_hgardfou_mats}"
    fi

    if ( ${FirstInitialize} ) ; then
	if [ -f start.nc ] && [ -f startphy.nc ] ; then
	    # The restart files already exist. They have been copied from a previous run or from a CREATE job
	    echo "Restart files for LMDZ have been copied from a previous run"
	elif [ -f create_etat0_limit* ] || [ -f ce0l* ] && [ ! -f lmdz.x ] ; then
	    # Do nothing because it is the program for creating restart files that is running and not LMDZ
	    echo "create_etat0_limit.e will create initial start files"
	else
	    # Restart files have to be created
	    echo "Run create_etat0_limit.e to create restart files start.nc and startphy.nc for LMDZ"
	    if [ ${DRYRUN} -le 2 ] ; then
                ##-- suppression of ozone file construction --
		cp config.def config.def.save
		LMDZ_sed config.def read_climoz 0
		IGCM_sys_Cp ${R_EXE}/create_etat0_limit.e ${RUN_DIR}/.
		if [ ${DRYRUN} -le 1 ] ; then
		    ${HOST_MPIRUN_COMMAND} -np 1 ./create_etat0_limit.e
		    IGCM_sys_Put_Out start.nc    ${R_OUT_ATM_R}/${config_UserChoices_JobName}_${PeriodDateBegin}_start.nc
		    IGCM_sys_Put_Out startphy.nc ${R_OUT_ATM_R}/${config_UserChoices_JobName}_${PeriodDateBegin}_startphy.nc
		fi
		IGCM_sys_Mv config.def.save config.def
	    else
		echo "EXECUTION of ${HOST_MPIRUN_COMMAND} -np 1 ./create_etat0_limit.e simulated"
		echo "EXECUTION of ${HOST_MPIRUN_COMMAND} -np 1 ./create_etat0_limit.e simulated for DRYRUN = " $DRYRUN >> stack
	    fi
	fi
    fi

    if [ X${lmdz_UserChoices_XIOS}  = Xy ] ; then
    # Add include of LMDZ context in iodef.xml
    # In iodef.xml add on next line after "COMPONENT CONTEXT"
    #  <context id="LMDZ" src="./context_lmdz.xml"/>
	echo '<context id="LMDZ" src="./context_lmdz.xml"/>' > add.tmp
	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
    
    IGCM_debug_PopStack "ATM_Update"
}

#-----------------------------------
function ATM_Finalize
{
    IGCM_debug_PushStack "ATM_Finalize"

    # If the file exist, copy Bands_ file to PARAM/ in submit directory. This file will be used for the simulation.
    # Copy also the same file into ATM/Restart at ARCHIVE directory for backup.
    if [ -f Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat ] ; then 
      if [ ${CumulPeriod} -le ${LMDZ_NbPeriod_adjust} ] ; then
        IGCM_sys_Cp Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat ${SUBMIT_DIR}/PARAM/${config_UserChoices_JobName}_Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat_${CumulPeriod}
        IGCM_sys_Put_Out Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat ${R_OUT_ATM_R}/${config_UserChoices_JobName}_Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat_${CumulPeriod}
      elif [ ${CumulPeriod} -eq 1 ] && [ ${LMDZ_NbPeriod_adjust} -eq 0 ] ; then
        # Special case : first period and no adjust => Save bands file with suffix _0
        IGCM_sys_Cp Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat ${SUBMIT_DIR}/PARAM/${config_UserChoices_JobName}_Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat_0
        IGCM_sys_Put_Out Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat ${R_OUT_ATM_R}/${config_UserChoices_JobName}_Bands_${RESOL_ATM_3D}_${NUM_PROC_ATM}prc.dat_0
      fi
    fi

    # Add special treatement for CARBON CYCLE
    if [ X"${lmdz_UserChoices_CARBON_CYCLE}" = X"control" ] || [ X"${lmdz_UserChoices_CARBON_CYCLE}" = X"historical" ] ; then
	ATM_Carbon_Finalize
    fi

    echo FINALIZE ATM !

    IGCM_debug_PopStack "ATM_Finalize"
}



function ATM_Carbon_Update
{
    # This fuction will be called only if CARBON_CYCLE is set to control or historical in lmdz.card

    IGCM_debug_PushStack "ATM_Carbon_Update"

    typeset InitPeriodCo2 InitDateBeginCo2 InitDateEndCo2
    typeset CO2SBG CO2MBG CO2LU CO2_ppm CO2_ppm_prec fCO2_ff
    typeset PathCO2log 
    typeset PreviousLinelog LastPeriodDateBegin LastPeriodDateEnd LastDatesPeriod LastPREFIX
    
    if ( ${FirstInitialize} && [ X"${config_ATM_Restart}" = X"n" ] ) ; then
        ##--Initialization of fluxes to an undefined value at the first run
	UndefinedValueCo2=-9999
	InitPeriodCo2=0
	InitDateBeginCo2=${UndefinedValueCo2}
	InitYearCo2=$(( ${year} - 1 )) 
	InitDateEndCo2=${InitYearCo2}1231
	fCO2_ff=${UndefinedValueCo2} 
	CO2SBG=${UndefinedValueCo2}
	CO2LU=${UndefinedValueCo2}
	CO2MBG=${UndefinedValueCo2}
	CO2_ppm_prec=${UndefinedValueCo2}
        # Get the initial value of atmosp. pco2 
	CO2_ppm=${lmdz_UserChoices_co2_init}
	
	IGCM_sys_Cp ${SUBMIT_DIR}/co2.log.init ${SUBMIT_DIR}/co2.log
	IGCM_sys_Chmod u+w ${SUBMIT_DIR}/co2.log
	
        # Save CO2 values in ExeCpuLog variable contents 5 fields
	echo "${InitPeriodCo2} ${InitDateBeginCo2} ${InitDateEndCo2} ${CO2_ppm} ${CO2_ppm_prec} ${fCO2_ff} ${CO2MBG} ${CO2SBG} ${CO2LU}" |   \
	    gawk '{printf("  %11d | %15s | %15s | %22.15g | %20.15g | %11.8g | %11.8g | %12.8g | %12.8g \n", \
                              $1,$2,$3,$4,$5,$6,$7,$8,$9)}' >> ${SUBMIT_DIR}/co2.log
	
        # Get the path where the log file co2.log is
	PathCO2log=${SUBMIT_DIR} 
        # Get Previous line in co2.log
	PreviousLinelog=$( tail -1 ${PathCO2log}/co2.log )
	
    else
	
	# NEW parameter in config.card (even for Overule all restarts, you must modify the line after this comment ):
        # !! NEW for Carbone cycle !! Path where to find old co2.log file for restart CO2.
	#SubmitRestartPath=
	if ( ${FirstInitialize} && [ X"${config_ATM_Restart}" = X"y" ] ) ; then
	    IGCM_card_DefineVariableFromOption ${SUBMIT_DIR}/config.card ATM SubmitRestartPath
	    PathCO2log=${config_ATM_SubmitRestartPath}
	    Date_r=$( IGCM_date_ConvertFormatToGregorian ${config_ATM_RestartDate} )
	    PreviousLinelog=$( grep ${Date_r} ${PathCO2log}/co2.log )
	    
	    IGCM_sys_Cp ${SUBMIT_DIR}/co2.log.init ${SUBMIT_DIR}/co2.log
	    IGCM_sys_Chmod u+w ${SUBMIT_DIR}/co2.log
	    
            # Save Last Line of control in new co2.log file
	    InitPeriodCo2=0   
	    InitDateBeginCo2=$( echo "${PreviousLinelog[*]}" | gawk -F '|' '{gsub(" ",""); print $2}' )
	    InitDateEndCo2=$( echo "${PreviousLinelog[*]}" | gawk -F '|' '{gsub(" ",""); print $3}' )
	    fCO2_ff=$( echo "${PreviousLinelog[*]}" | gawk -F '|' '{gsub(" ",""); print $6}' )
	    CO2SBG=$( echo "${PreviousLinelog[*]}" | gawk -F '|' '{gsub(" ",""); print $8}' )
	    CO2LU=$( echo "${PreviousLinelog[*]}" | gawk -F '|' '{gsub(" ",""); print $9}' )
	    CO2MBG=$( echo "${PreviousLinelog[*]}" | gawk -F '|' '{gsub(" ",""); print $7}' )
	    CO2_ppm_prec=$( echo "${PreviousLinelog[*]}" | gawk -F '|' '{gsub(" ",""); print $5}' )
	    CO2_ppm=$( echo "${PreviousLinelog[*]}" | gawk -F '|' '{gsub(" ",""); print $4}' )
	    
	    echo "${InitPeriodCo2} ${InitDateBeginCo2} ${InitDateEndCo2} ${CO2_ppm} ${CO2_ppm_prec} ${fCO2_ff} ${CO2MBG} ${CO2SBG} ${CO2LU}" |   \
		gawk '{printf("  %11d | %15s | %15s | %22.15g | %20.15g | %11.8g | %11.8g | %12.8g | %12.8g \n", \
                              $1,$2,$3,$4,$5,$6,$7,$8,$9)}' >> ${SUBMIT_DIR}/co2.log
	else
           # Get restart line in co2.log
	    PathCO2log=${SUBMIT_DIR}
	    PreviousLinelog=$( tail -1 ${PathCO2log}/co2.log )
           # Get the value of atmosp. pco2 in co2.log
	    CO2_ppm=$( echo "${PreviousLinelog[*]}" | gawk -F '|' '{gsub(" ",""); print $4}' )
	fi
	
    fi
    
    if [ ${lmdz_UserChoices_CARBON_CYCLE} = historical ] ; then
	    # Modify co2_ppm in config.def only for historical run
	    # If not historical run, keep co2_ppm value set earlier by LMDZ_sed
	LMDZ_sed config.def co2_ppm     ${CO2_ppm}
    fi
    IGCM_debug_PopStack "ATM_Carbon_Update"
}


function ATM_Carbon_Finalize
{
    # This fuction will be called only if CARBON_CYCLE is set to control or historical in lmdz.card

    IGCM_debug_PushStack "ATM_Carbon_Finalize"

    typeset CO2SBG_3V CO2SBG CO2MBG CO2SRF CO2LU CO2_ppm CO2_ppm_prec fCO2_ff
    
	# Fossil fuel emission
    if [ ${lmdz_UserChoices_CARBON_CYCLE} = control ] ; then
            # For Control, no fossil fuel emission :
	fCO2_ff=0
	echo "Fossil Fuel for control run  :" ${fCO2_ff}
    else
            # For historical, get the fossile fuel file :
	fCO2_ff=$( gawk "{if (match(\$0,\"${year}\ *${month}\")) {print \$3}}" ${SUBMIT_DIR}/PARAM/CMIP5_gridcar_CO2_emissions_fossil_fuel_Andres_1751-2007_monthly_SC.txt )
	echo "Fossil Fuel for historical run  :" ${fCO2_ff}
    fi
    
        # Get the value of ocean carbon flux
    CO2MBG=$( ${SUBMIT_DIR}/COMP/lmdz_analyse_pisces_out.awk ocean.output )
    CO2MBG=$( echo ${CO2MBG} | sed -e "s/ *//" )
    echo "Ocean carbon flux  :" ${CO2MBG}
    
        # Get the value of land fluxes
    set +A CO2SBG_3V -- $( ${SUBMIT_DIR}/COMP/lmdz_analyse_stomate_out.awk out_orchidee_0000 )
    CO2SRF=$( echo ${CO2SBG_3V[0]} | sed -e "s/ *//" )
    CO2LU=$( echo ${CO2SBG_3V[1]} | sed -e "s/ *//" )
    CO2SBG=$( echo ${CO2SBG_3V[2]} | sed -e "s/ *//" )
    echo "Land carbon flux (NEP)         :" ${CO2SRF}
    echo "LU flux          (FLUC)        :" ${CO2LU}
    echo "Total Land carbon flux (NBP)   :" ${CO2SBG}
    
        # Previous CO2
    CO2_ppm_prec=$( echo "${PreviousLinelog[*]}" | gawk -F '|' '{gsub(" ",""); print $4}' )
    echo "Previous CO2  :" ${CO2_ppm_prec}
    
        # Formula
    CO2_ppm=$( echo "${CO2_ppm_prec} + (${fCO2_ff} + ${CO2MBG} + ${CO2SBG}) / 2.12" | bc -l )
    echo "New CO2  :" ${CO2_ppm}
    
        # Save CO2 values in ExeCpuLog variable contents 5 fields
    echo "${CumulPeriod} ${PeriodDateBegin} ${PeriodDateEnd} ${CO2_ppm} ${CO2_ppm_prec} ${fCO2_ff} ${CO2MBG} ${CO2SBG} ${CO2LU}" |   \
	gawk '{printf("  %11d | %15s | %15s | %22.15g | %20.15g | %11.8g | %11.8g | %12.8g | %12.8g \n", \
                           $1,$2,$3,$4,$5,$6,$7,$8,$9)}' >> ${SUBMIT_DIR}/co2.log
    
    IGCM_debug_PopStack "ATM_Carbon_Finalize"
}
