#!/bin/ksh
#-----------------------------------------------------------------
function ICO_Initialize
{
    IGCM_debug_PushStack "ICO_Initialize"

    ##- Horizontal resolution read from dynamic.card
    if [ ! X${dynamico_UserChoices_RESOL_NBP} = X ] ; then
	RESOL_NBP=${dynamico_UserChoices_RESOL_NBP}
    else
	# Exit
	IGCM_debug_Exit "RESOL_NBP must be set in dynamico.card UserSection"
    IGCM_debug_Verif_Exit
    fi

    ##- Horizontal resolution read from dynamico.card
    if [ ! X${dynamico_UserChoices_RESOL_ATM_Z} = X ] ; then
	RESOL_ATM_Z=${dynamico_UserChoices_RESOL_ATM_Z}
    else
        # RESOL_ATM_Z is not set in dynamico.card but this is needed
	IGCM_debug_Exit "RESOL_ATM_Z must be set in dynamico.card UserSection"
	IGCM_debug_Verif_Exit
    fi


    if [ -f ${SUBMIT_DIR}/../../../bin/inca_${ConfChem}.dat ];  then 
        eval $(grep nbtrac ${SUBMIT_DIR}/../../../bin/inca_${ConfChem}.dat) || nbtrac=1
    else
	nbtrac=1
    fi
    ((nbtrac=nbtrac+3))


    if [ ! -f ${SUBMIT_DIR}/../../../modeles/DYNAMICO/xml/file_def_dynamico.xml ];  then 
	module load python3
	python3 ${SUBMIT_DIR}/../../../modeles/DYNAMICO/xml/file_def_dynamico.xml.py > ${SUBMIT_DIR}/../../../modeles/DYNAMICO/xml/file_def_dynamico.xml
    fi

    IGCM_debug_PopStack "ICO_Initialize"
}

#-----------------------------------------------------------------
function ICO_Update
{
    IGCM_debug_PushStack "ICO_Update"

    # Reset date from start.nc file on the first iteration in the simulation
    if [ ${CumulPeriod} -eq 1 ] ; then
	IGCM_comp_modifyDefFile blocker run_dynamico.def etat0_start_iteration_reset y
    else
	IGCM_comp_modifyDefFile blocker run_dynamico.def etat0_start_iteration_reset n
    fi

    # set number of tracer in run_dynamico.def 
    IGCM_comp_modifyDefFile nonblocker run_dynamico.def nqtot ${nbtrac}

    # Set lenght for execution 
    IGCM_comp_modifyDefFile blocker run_dynamico.def run_length $(( ${PeriodLengthInDays} * 86400 ))

    #  Activate nudging if ok_guide=y set in dynamico.card
    if [  X${dynamico_UserChoices_ok_guide} = Xy ] ; then
	IGCM_comp_modifyDefFile nonblocker run_dynamico.def guided_type  nudging
    else
	IGCM_comp_modifyDefFile nonblocker run_dynamico.def guided_type  none
    fi

    # Change run_dynamico.def according to UserChoices options set in dynmaico.card
    
    # Set create_etat0_limit=y or n and 
    if [ X${dynamico_UserChoices_create_etat0_limit} = Xy ] ; then 
	# create_etat0_limit is set in dynamcio.card to y
	# Activate create_etat0_limit=y in run_dynamico.def
	IGCM_comp_modifyDefFile nonblocker run_dynamico.def create_etat0_limit y

	# Use iflag_phys=101 or higher to activate aquaplanet mode
	if [ X${dynamico_UserChoices_iflag_phys} = X ] || [ X${dynamico_UserChoices_iflag_phys} = X1 ]; then 
            # iflag_phys is not set or iflag_phys=1 => run is not an aquaplanet
	    IGCM_comp_modifyDefFile nonblocker run_dynamico.def etat0              database
	    IGCM_comp_modifyDefFile nonblocker run_dynamico.def iflag_phys         1
	else
	    # This is an aquaplanet
	    IGCM_comp_modifyDefFile nonblocker run_dynamico.def etat0              held_suarez
	    IGCM_comp_modifyDefFile nonblocker run_dynamico.def iflag_phys         ${dynamico_UserChoices_iflag_phys}
	fi

	# Optimize the grid: set read_metric=n and optim_it=100000	
	IGCM_comp_modifyDefFile nonblocker   run_dynamico.def   read_metric  n
	IGCM_comp_modifyDefFile nonblocker   run_dynamico.def   optim_it     100000
    else
	# Deactivate create_etat0_limit to run a the GCM (aquaplanet or not)
	IGCM_comp_modifyDefFile nonblocker run_dynamico.def create_etat0_limit   n
	IGCM_comp_modifyDefFile nonblocker run_dynamico.def etat0                start_file

	# Set iflag_phys even though it only will be read but not used for the case create_etat0_limit=n
	if [ X${dynamico_UserChoices_iflag_phys} = X ] ||  [ X${dynamico_UserChoices_iflag_phys} = X1 ]; then 
            # iflag_phys is not set or iflag_phys=1 => run is not an aquaplanet
	    IGCM_comp_modifyDefFile nonblocker run_dynamico.def iflag_phys           1
	else
	    IGCM_comp_modifyDefFile nonblocker run_dynamico.def iflag_phys         ${dynamico_UserChoices_iflag_phys}
	fi	

	# Read grid from start.nc file: set read_metric=y and optim_it=0	
	IGCM_comp_modifyDefFile nonblocker   run_dynamico.def   read_metric  y
	IGCM_comp_modifyDefFile nonblocker   run_dynamico.def   optim_it     0
    fi 


    # Add include of context xml files for DYNAMICO in iodef.xml
    # In iodef.xml add on the next line after "COMPONENT CONTEXT"
    echo '<context id="icosagcm" src="./context_dynamico.xml"/>' >> add.tmp

   # Add inclusion of file sponge_dynamico.xml if this file exists
   if [ -f sponge_dynamico.xml ] ; then
        echo '<context id="icosagcm"        src="./sponge_dynamico.xml" />' >> add.tmp
   fi

    # Add inclusion of file context_input_dynamico.xml if this file exists
    if [ -f context_input_dynamico.xml ] ; then
        echo '<context id="icosagcm_input" src="./context_input_dynamico.xml"/>' >> add.tmp
    fi

    if [ -f tracers_dynamico.xml ] ; then
	echo '<context id="icosagcm" src="./tracers_dynamico.xml" />'  >> add.tmp
    fi

    if [  X${dynamico_UserChoices_ok_guide} = Xy ] ; then
	if [ -f nudging_dynamico.xml ] ; then
	    echo '<context id="icosagcm" src="./nudging_dynamico.xml" />'  >> add.tmp
	else
	    IGCM_debug_Exit "you choose ok_guide=y and forget to add the copy of nudging_dynamico.xml file in dynamico.card"
	    IGCM_debug_Verif_Exit
	fi
    fi

    if [ -f file_def_dynamico.xml ] ; then
	echo '<context id="icosagcm" src="./file_def_dynamico.xml" />' >> add.tmp
    fi 


    # Include xml files for output configuration if running with workflow CMIP6
    if [ X"$( echo ${config_UserChoices_ExpType} | grep CMIP6 )" != "X" ] ; then
      if [ -f ping_dynamico.xml ] ; then
        echo '<context id="icosagcm" src="./ping_dynamico.xml"/>' >> add.tmp
        echo '<context id="icosagcm" src="./dr2xml_dynamico.xml"/>' >> add.tmp
      fi
    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

    # Add a Long Name as global attribute in output files if LongName is set in config.card
    if [ ! "X${config_UserChoices_LongName}" = "X" ] ; then
      listfile=$(ls file_def*dynamico.xml)
      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

    #remove unlimited time axis on winds files 
    if [ -f u.nc ] ; then 
	nccopy -u u.nc tmp.nc
	mv tmp.nc u.nc
    fi 
    if [ -f v.nc ] ; then 
	nccopy -u v.nc tmp.nc
	mv tmp.nc v.nc
    fi 


    if [ X${config_ListOfComponents_CPL} = Xoasis ] ; then
    echo "Coupling mode using oasis, set using_oasis=y in run_dynamico.def"
    IGCM_comp_modifyDefFile nonblocker run_dynamico.def using_oasis y
    else
    echo "DYNAMICO is running in forced mode without ocean model, set using_oasis=y in run_dynamico.def"
    IGCM_comp_modifyDefFile nonblocker run_dynamico.def using_oasis n
    fi


    # Compression level (if CompressionLevel is not empty)
    if [ ! "X${config_UserChoices_CompressionLevel}" = "X" ] ; then
	echo "NetCDF output files compression level is " ${config_UserChoices_CompressionLevel}
	listfile=$(ls file_def*dynamico.xml)
	for file in ${listfile} ; do
            sed -i -e "s/\(compression_level=\"\)[^\"]*\(\"\)/\1${config_UserChoices_CompressionLevel}\2/" ${file}
	done
    fi

    IGCM_debug_PopStack "ICO_Update"
}

#-----------------------------------
function ICO_Finalize
{
    IGCM_debug_PushStack "ICO_Finalize"

    IGCM_debug_PopStack "ICO_Finalize"
}

