#!/bin/bash
# Default options
#
#
#
date
#### 1  Set up the compiling options
#### Define some directories
submitdir=$( pwd )
modipsl=$submitdir/../..
arch_path=$submitdir/ARCH 
mysrc_path=$submitdir/SOURCES
export ROOT=$modipsl/modeles/DYNAMICO
#### Set default options
# Activate compilation of LMDZ for regular latlon grid without DYNAMICO
regular_latlon=y
# Atmospheric resolution for regular grid for LMDZ/ORCHIDEE, if regular_latlon=y
resol_atm=144x142x79
# Coupled with ocean biogeochemistry (y/n)
nemotop=y
# Optimization mode
# optmode=prod/dev/debug
optmode=prod
# fcm_arch
fcm_arch=default
# Default values to be overritten
parallel=mpi_omp
export fcm_arch parallel xios
full_flag=""
full_nemo=n
full_inca=""
full_xios=""
full_lmdz=""
full_orch=""
full_dyna=""
full_oasis=n
# choose radiative code compilation option 
rad=rrtm
opt_rad=""
#choose chemistry inca configuration 
optchimie=GES

# subconfig : which sub-configuration to compile. By default, the full extracted configuration is compiled.
subconfig=default

# orchversion tells if ORCHIDEE_2_2 or ORCHIDEE_4 is compiled. This is used as argument and also in the suffix of the executables.
orchversion=orch22
# orchdriver : Permet to compile the ORCHIDEE offline drivers. This option is activated by setting -orchdriver as argument. 
# Drivers are now compiled by default
orchdriver="-driver"

# Default netcdf_lib is used for XIOS but can be change by argument
netcdf_lib=""

# Output text file for compilation of each component
datestr=`LC_ALL=C date +"%Y%m%dT%H%M"`
outfile=$submitdir/out_compile_ipslcm7.$datestr
echo > $outfile
echo; echo "Text output from compilation will be stored in file out_compile_ipslcm7.$datestr"; echo 


rm -f out_compile_ipslcm7
ln -s ${outfile} out_compile_ipslcm7


#### Read arguments 
# Loop over all arguments to modify default set up
while (($# > 0)) ; do
    case $1 in
	"-h"|"-help") cat <<end_help
########################################################################
# Usage of the script compile_ipslcm7.sh
#
########################################################################

./compile_ipslcm7.sh [Options] 

Description of all options:

[-full] Full recompilation of all components. This option can be added to all other options.
[-cleannemo] Full recompilation of NEMO component only.
[-regular_latlon yes/no] Activate or deactivate compilation of LMDZ dynamics for regular latlon grid. 
                         Default resol_atm size is used. This option is set in addition to the compilation of the icosahedric grid. 
[-resol_atm XXXxYYYxZZ] Define which regular grid to compile. A default grid is set if this option is not used.
[-debug / -dev / -prod] Level of optimization. One of these can be added to all other compile options. Default: -prod.
[-subconfig X] Set this option if you want to compile a sub-configuration. X can be one of following sub-configurations : 
               ICOLMDZORINCA, ICOLMDZOR, LMDZORINCA, LMDZOR, IPSLCM-reg or IPSLCM
               By default, all available components are compiled. 
[-orch4 / -orch22] Choice of ORCHIDEE version. The source code are found in modeles/ORCHIDEE_4 or modeles/ORCHIDEE_2_2 
                   and a link will be set to the choosen model version. Default version is currently ORCHIDEE_2_2 (-orch22).
[-orchdriver]   Activate compilation of orchidee offline drivers

Example 1: Default compilation of IPSLCM7 
./compile_ipslcm7.sh

Example 2: Default compilation in debug mode
./compile_ipslcm7.sh -debug

Example 3: Default compilation with full recompilation of all components. No clean is needed.
./compile_ipslcm7.sh -full

Example 4: Compilation in addition of LMDZ in regular lat-lon for a specific resolution : 
./compile_ipslcm7.sh -resol_atm 144x142x95

Example 5: Compilation without regular grid (only icosaedric grid)
./compile_ipslcm7.sh -regular_latlon no

Example 5: Compilation of ORCHIDEE_4 version
./compile_ipslcm7.sh -orch4

Example 6: compilation of a specific chemistry for INCA (default is GES) 
./compile_ipslcm7.sh -chimie NMHC_AER_S 

Example 7: Compilation of sub-configuration LMDZOR : 
./compile_ipslcm7.sh -subconfig LMDZOR

end_help
	    exit;;

	"-parallel")   parallel=$2 ; shift ; shift ;; 
	"-arch")       fcm_arch="$2" ; shift ; shift ;;
	"-debug")      optmode=debug ; shift ;;
	"-dev")	       optmode=dev ; shift ;;
	"-prod")       optmode=prod ; shift ;;
	"-regular_latlon")  regular_latlon=$2 ; shift ; shift ;;
	"-resol_atm")  regular_latlon=y ; resol_atm=$2 ; shift ; shift ;;
	"-subconfig")  subconfig=$2 ; shift ; shift ;;
	"-full")       full_flag="-full"; full_nemo=y ; full_xios="--full" ; full_lmdz="-full" ; full_orch="-full" ; full_oasis=y ; full_inca="-clean" ; full_dyna="-full" ; shift ;;
	"-full_xios")  full_xios="--full" ; shift ;;  # Note only full_xios is using double dash: --full
	"-full_lmdz")  full_lmdz="-full"  ; shift ;;
	"-full_orch")  full_orch="-full"  ; shift ;;
	"-full_nemo")  full_nemo=y ; shift ;;
	"-full_inca")  full_inca="-clean"; shift ;;
	"-full_dyna")  full_dyna="-full" ; shift ;;
 	"-full_oasis") full_oasis=y ; shift ;;
	"-cleannemo")  full_nemo=y ; shift ;;
	"-rad")        rad=$2; shift ; shift ;;
	"-orch22")     orchversion="orch22"; shift ;;
	"-orch4")      orchversion="orch4";  shift ;;
	"-orchdriver") orchdriver="-driver";  shift ;;
	"-chimie")     optchimie=$2; shift ; shift;;
	*)	       echo "unknown option "$1" , exiting..." ; exit
    esac
done


# Define which sub-configuration to compile. By default all extracted source components are compiled.
source define_config.sh

echo "Following options are set in current compiling:" >> $outfile
echo "   regular_latlon=$regular_latlon (if yes, then resol_atm=${resol_atm})" >> $outfile 
echo "   resol_atm=${resol_atm}, nemotop=${nemotop}" >> $outfile 
echo "   optmode = $optmode, parallel = $parallel, fcm_arch = $fcm_arch " >> $outfile 
echo "   full_flag=$full_flag, full_xios=$full_xios, full_lmdz=$full_lmdz, full_orch=$full_orch, full_nemo=$full_nemo, full_dyna=$full_dyna, full_oasis=$full_oasis" >> $outfile 
echo "   compinca=$compinca compnemo=$compnemo compoasis=$compoasis compdyna=$compdyna complmdz=y comporch=y compxios=y" >> $outfile
echo >> $outfile
### Verification of argument
# Set argorch depeinding on the version of ORCHIDEE. This is argument needed for the compilation of LMDZ to consider coherent interface. 
if [ $orchversion == orch22 ] ; then
    argorch=orchidee2.1
elif [ $orchversion == orch4 ] ; then
    argorch=orchideetrunk
else
    echo "ERROR in version of ORCHIDEE. It is only possible to have orch22 or orch4 for now"
fi

### Read host dependent default values
### These variables will not be changed if they were set as argument
###./host.sh $host
# Later : Following lines should be set in host.sh file
# begin host.sh
if [ $fcm_arch == default ] ; then
    # Find out current host and source specific paths and commands for the host
    case $( hostname -s ) in
	jean-zay*)
            if [[ $( hostname -s ) != *"pp"* ]] ; then
                echo "Warning! You MUST compile on jean-zay-pp."
                echo "EXIT"
                exit
            else
                fcm_arch=X64_JEANZAY
            fi ;;
        irene170|irene171|irene190|irene191|irene192|irene193)
            fcm_arch=X64_IRENE;;
        irene172|irene173|irene194|irene195)
            fcm_arch=X64_IRENE-AMD;;
	asterix*|obelix*)
	    fcm_arch=ifort_LSCE
            if [ "${parallel}" == "mpi_omp" ] ; then 
		echo "Warning!! Currently at Obelix hybrid mode is not possible."
		echo "          Option -parallel mpi_omp is now changed to -parallel mpi"
		echo ""
		parallel=mpi
            else
		echo "You used -parallel" $parallel
            fi ;;
        spirit*)
            fcm_arch=ifort_MESOIPSL;;
	ciclad*|climserv*|loholt*|camelot*)
	    fcm_arch=ifort_CICLAD;;
	*)
	    echo Current host is not known. You must use option -arch to specify which architecuture files to use.
	    echo Exit now.
	    exit
    esac
fi

# Set a link to arch.env if arch-${fcm_arch}.env file exist for current fcm_arch.
# The link arch.env is also set in config.card and will be used by libIGCM to ensure the same running environnement.
if [ -f ARCH/arch-${fcm_arch}.env ] ; then
    echo >> $outfile
    echo "The file ARCH/arch-${fcm_arch}.env will now be sourced with modules needed for compilation for all components."
    echo "Note that this new environement might be kept after compilation."
    echo "If this is the case, source again your personal environment after compilation."
    echo " Personal module list before sourcing of ARCH/arch.env file:"    >> $outfile 
    module list   >> $outfile 2>&1
    svn_version=$(module list -t | grep subversion)
       
    # Make a link to this file, to be used also in config.card
    rm -f ARCH/arch.env
    ln -s arch-${fcm_arch}.env ARCH/arch.env

    # Source the file
    source ARCH/arch.env   >> $outfile 2>&1
    if [ X$svn_version != X ] ; then
	module load ${svn_version}
    fi
    echo >> $outfile
    echo " New module list after sourcing of ARCH/arch.env file:"    >> $outfile 
    module list   >> $outfile 2>&1
fi


#### Clean if full_orch
# If full recompilation of ORCHIDEE then first clean modipsl/lib folder
if [ X${full_orch} == X"-full" ] ; then
   rm -f $modipsl/lib/*
fi

#### 2 Do the compilation 
## 2.1 Compile ioipsl
cd $modipsl/modeles/IOIPSL
echo; echo "NOW COMPILE IOIPSL"
echo >> $outfile ; echo " NOW COMPILE IOIPSL"   >> $outfile 

echo ./makeioipsl_fcm -$optmode -parallel -arch ${fcm_arch} -arch_path $arch_path -j 8 $full_flag   >> $outfile 
     ./makeioipsl_fcm -$optmode -parallel -arch ${fcm_arch} -arch_path $arch_path -j 8 $full_flag   >> $outfile 2>&1
# Test if compiling succeded 
if [[ $? != 0 ]] ; then 
    echo "THERE IS A PROBLEM IN IOIPSL COMPILATION - STOP"
    exit
fi

if [ $compoasis == y ] ; then
## 2.2 Compile oasis3-mct
if [ $full_oasis == y ] ; then
    rm -rf $modipsl/oasis3-mct/BLD
fi
cd $modipsl/oasis3-mct/util/make_dir
echo; echo "NOW COMPILE OASIS3-MCT"
echo >> $outfile ; echo " NOW COMPILE OASIS3-MCT"   >> $outfile
cp $mysrc_path/OASIS3-MCT/make_${fcm_arch} make.inc

echo make -f TopMakefileOasis3 >> $outfile
     make -f TopMakefileOasis3 >> $outfile 2>&1
if [[ $? != 0 ]] ; then
    echo "THERE IS A PROBLEM IN OASIS COMPILATION - STOP"
    exit
fi
 

else
echo ; echo No compilation of OASIS
fi

## 2.3 Compile xios
cd $modipsl/modeles/XIOS
echo; echo "NOW COMPILE XIOS"
echo >> $outfile ; echo " NOW COMPILE XIOS"   >> $outfile 
if [ $compoasis == y ] ; then
argoasis="--use_oasis oasis3_mct "
else
argoasis=" "
fi
echo ./make_xios $argoasis --$optmode --arch $fcm_arch --arch_path $arch_path ${netcdf_lib} --job 4 $full_xios   >> $outfile 
     ./make_xios $argoasis --$optmode --arch $fcm_arch --arch_path $arch_path ${netcdf_lib} --job 4 $full_xios   >> $outfile 2>&1
# Test if compiling succeded 
if [[ $? != 0 ]] ; then 
    echo "THERE IS A PROBLEM IN XIOS COMPILATION - STOP"
    exit
fi
# Move executables to modipsl/bin
if [ -f $modipsl/modeles/XIOS/bin/xios_server.exe ] ; then 
    mv $modipsl/modeles/XIOS/bin/xios_server.exe $modipsl/bin/xios_server_${optmode}.exe
else
    echo "THERE IS A PROBLEM IN XIOS COMPILATION EXECUTABLE MISSING - STOP"
    exit
fi


## 2.4 Compile ORCHIDEE
# Choose ORCHIDEE version to compile and create a link to generic folder name ORCHIDEE.
# This link is needed for the compilation of ICOSA_LMDZ for it to find the orchidee librarie. 
cd $modipsl/modeles
rm -f ORCHIDEE
if [ $orchversion == orch22 ] ; then
    ln -s ORCHIDEE_2_2 ORCHIDEE
    cd $modipsl/modeles/ORCHIDEE_2_2
    echo; echo "NOW COMPILE ORCHIDEE_2_2"
    echo >> $outfile ; echo " NOW COMPILE ORCHIDEE_2_2"   >> $outfile 
else
    ln -s ORCHIDEE_4 ORCHIDEE
    cd $modipsl/modeles/ORCHIDEE_4
    echo; echo "NOW COMPILE ORCHIDEE_4 (trunk)"
    echo >> $outfile ; echo " NOW COMPILE ORCHIDEE_4 (trunk)"   >> $outfile 
fi

# Check if the compilation of ORCHIDEE was previsouly interupted prematured. 
# In that case, the files fcm.bld.lock exist. If the file exist, it is here removed to avoid makeorchidee_fcm 
# to ask question and wait for interactivly answer from the user.
if [ -f build/fcm.bld.lock ] ; then
    echo >> $outfile
    echo " WARNING!! The file ORCHIDEE/build/fcm.bld.lock exist. "   >> $outfile
    echo "           This means that the compilation is either currently on going in another terminal was previous interupted before the end."   >> $outfile
    echo "           The file will now be removed. "   >> $outfile
    echo >> $outfile
    rm -f build/fcm.bld.lock
fi

echo    ./makeorchidee_fcm -j 8 -xios -parallel $parallel -$optmode -arch ${fcm_arch} -arch_path $arch_path $full_orch $orchdriver >> $outfile 
        ./makeorchidee_fcm -j 8 -xios -parallel $parallel -$optmode -arch ${fcm_arch} -arch_path $arch_path $full_orch $orchdriver >> $outfile 2>&1
# Test if compiling finished
if [[ $? != 0 ]] ; then
    echo "THERE IS A PROBLEM IN ORCHIDEE COMPILATION - STOP"
    exit
fi

# Rename exetubles for ORCHIDEE offline driver with suffix version
cd $modipsl/bin
if [ -f orchideedriver ] ; then 
    mv orchideedriver orchideedriver.${orchversion}_$optmode
    ln -sf orchideedriver.${orchversion}_$optmode orchideedriver_$optmode
fi
if [ -f orchidee_ol ] ; then 
    mv orchidee_ol orchidee_ol.${orchversion}_$optmode
    ln -sf orchidee_ol.${orchversion}_$optmode orchidee_ol_$optmode
fi

## 2.5 Compile NEMO
if [ $compnemo == y ] ; then
    nemo_root=$modipsl/modeles/NEMO
    cfg_ref=ORCA2_ICE_PISCES
    cfg_wrk=ORCA_ICE_TRC
    addkeys="key_oasis3 key_top key_si3 key_isf"
    delkeys=""
    
    if [ ${nemotop} == n ] ; then
	cfg_wrk=ORCA_ICE
	delkeys="key_top"
    fi
    
    if [ ${nemotop} == n ] ; then
	echo; echo "NOW COMPILE NEMO with ice model SI3 without passive tracer model TOP"
	echo >> $outfile ; echo " NOW COMPILE NEMO with ice model SI3 without passive tracer model TOP"   >> $outfile
    else
	echo; echo "NOW COMPILE NEMO with ice model SI3 and passive tracer model TOP"
	echo >> $outfile ; echo " NOW COMPILE NEMO with ice model SI3 and passive tracer model TOP"   >> $outfile
    fi
    
    echo >> $outfile ; echo cd $nemo_root  >> $outfile
    echo >> $outfile ; echo cp $mysrc_path/NEMO/arch-${fcm_arch}.fcm arch/CNRS/.   >> $outfile
    echo >> $outfile
    
    cd $nemo_root ; cp $mysrc_path/NEMO/arch-${fcm_arch}.fcm arch/CNRS/.
    
    # creation of config
    echo >> $outfile ; echo cd $nemo_root  >> $outfile
    echo ./makenemo -m ${fcm_arch} -n $cfg_wrk -r $cfg_ref -j0 add_key "$addkeys"  del_key "$delkeys"   >> $outfile
    echo >> $outfile
    cd $nemo_root
    ./makenemo -m ${fcm_arch} -n $cfg_wrk -r $cfg_ref -j0  add_key "$addkeys"  del_key "$delkeys"  >> $outfile 2>&1
    
    
    # Copy of specfic source files
    echo >> $outfile ; echo cp $mysrc_path/NEMO/*.*90  $nemo_root/cfgs/$cfg_wrk/MY_SRC/.   >> $outfile
    echo >> $outfile
    cp $mysrc_path/NEMO/*.*90  $nemo_root/cfgs/$cfg_wrk/MY_SRC/.
    
    
    if [ $full_nemo == y ] ; then
	# To make a full compilation, first make a clean to remove all files produced during previous compilation
	echo ./makenemo -m ${fcm_arch} -n $cfg_wrk -r $cfg_ref clean   >> $outfile
	echo >> $outfile
	./makenemo -m ${fcm_arch} -n $cfg_wrk -r $cfg_ref clean  >> $outfile 2>&1
    fi
    echo ./makenemo -m ${fcm_arch} -n $cfg_wrk -r $cfg_ref -j8  >> $outfile
    echo >> $outfile
    ./makenemo -m ${fcm_arch} -n $cfg_wrk -r $cfg_ref -j8  >> $outfile 2>&1
    
    echo >> $outfile
    echo "Move nemo executable to modipsl/bin" >> $outfile
    echo ls -lrt $nemo_root/cfgs/$cfg_wrk/BLD/bin   >> $outfile
    ls -lrt $nemo_root/cfgs/$cfg_wrk/BLD/bin  >> $outfile
    echo >> $outfile
    
    if [ -f $nemo_root/cfgs/$cfg_wrk/BLD/bin/nemo.exe ] ; then
	mv $nemo_root/cfgs/$cfg_wrk/BLD/bin/nemo.exe $modipsl/bin/opa_${optmode}.exe
    else
	echo "ERROR nemo.exe executable does not exist."
	echo "THERE IS A PROBLEM IN NEMO COMPILATION - STOP"
	exit
    fi
    
else
    echo ; echo No compilation of NEMO
fi

##2.6  Compile INCA 
if [ $compinca == y ] ; then
    cd $modipsl/modeles/INCA
    
    echo; echo "NOW COMPILE INCA ${optchimie}"
    echo >> $outfile ; echo " NOW COMPILE INCA ${optchimie}"   >> $outfile 
    
    echo ./makeinca_fcm -chimie ${optchimie} -$optmode -xios -parallel mpi_omp -j 8 -arch ${fcm_arch}  -arch_path $arch_path $full_inca  >> $outfile
    ./makeinca_fcm -chimie ${optchimie} -$optmode -xios -parallel mpi_omp  -j 8 -arch ${fcm_arch} -arch_path $arch_path $full_inca >> $outfile 2>&1
    
    # Test if compiling finished
    if [[ $? != 0 ]] ; then
	echo "THERE IS A PROBLEM IN INCA COMPILATION - STOP"
	echo "ALL INFORMATION IN FILE $outfile"
	exit
    fi
    
    echo "Move inca.dat modipsl/bin"
    if [[ -f $modipsl/modeles/INCA/SIMULATIONS/${optchimie}/inca.dat ]] ;  then  
	mv $modipsl/modeles/INCA/SIMULATIONS/${optchimie}/inca.dat $modipsl/bin/inca_${optchimie}.dat ;
    else
	echo "THERE IS A PROBLEM IN INCA COMPILATION - STOP"
	echo "ALL INFORMATION IN FILE $outfile"
	exit	
    fi
    
    echo "Move tracer.def to  modipsl/bin"
    if [[ -f $modipsl/modeles/INCA/tracer.def ]] ;  then
        mv $modipsl/modeles/INCA/tracer.def $modipsl/bin/tracer_${optchimie}.def ;
    fi
    
else
    echo ; echo No compilation of INCA
fi

## 2.7 Compile LMDZ 
cd $modipsl/modeles/LMDZ


# Temporary use of SOURCES/LMDZ to handle modifications needed by IPSLCM7 for LMDZ 4515
# To be remove for newer versions of LMDZ 
cp $mysrc_path/LMDZ/phylmd/*.*90  libf/phylmd/.
cp $mysrc_path/LMDZ/dyn3d_common/*.*90  libf/dyn3d_common/.


# Compile LMDZ as library to couple to DYNAMICO
if [ $compdyna == y ] ; then
    echo; echo "NOW COMPILE LMDZ FOR COUPLING TO DYNAMICO"
    echo >> $outfile ; echo " NOW COMPILE LMDZ FOR COUPLING TO DYNAMICO"   >> $outfile 
    
    
    # Check if the compilation of LMDZ was previsouly interupted prematured. 
    # In that case, the files dimension.h and .lock exist. If the files exist, they are here removed to avoid makelmdz_fcm 
    # to ask question and wait for interactivly answer from the user.
    if [ -f libf/grid/dimensions.h ] || [ -f .lock ] ; then
	echo >> $outfile
	echo " WARNING!! The file LMDZ/libf/grid/dimension.h and/or the LMDZ/.lock exist. "   >> $outfile
	echo "           This means that the compilation is either currently on going in another terminal was previous interupted before the end."   >> $outfile
	echo "           The files dimension.h and .lock will now be removed. "   >> $outfile
	echo >> $outfile
	rm -f libf/grid/dimensions.h
	rm -f .lock
    fi
    
    # Need to define the proper option for radiative code compilation. By default, we use rrtm
    case $rad in
	oldrad) opt_rad="" ;;
	rrtm)    opt_rad="-rad rrtm" ;;
	ecrad)  opt_rad="-rad ecrad" ;;
	*) echo Only oldrad rrtm ecrad for rad option ; exit
    esac
    
    
    if [ $compinca == y ] ; then
	arginca="-chimie INCA "
    else
	arginca=" "
    fi
    
    if [ $compoasis == y ] ; then
	argoasis="-c OMCT "
    else
	argoasis=" "
    fi

    echo ./makelmdz_fcm -p lmd $argoasis $opt_rad -$optmode -mem -parallel $parallel -libphy -v $argorch $arginca  -io xios -arch $fcm_arch -arch_path $arch_path -j 8 $full_lmdz    >> $outfile 
    ./makelmdz_fcm -p lmd $argoasis $opt_rad -$optmode -mem -parallel $parallel -libphy -v $argorch $arginca  -io xios -arch $fcm_arch -arch_path $arch_path -j 8 $full_lmdz    >> $outfile 2>&1
    
    
    # Test if compiling finished
    if [[ $? != 0 ]] ; then
	echo "THERE IS A PROBLEM IN LMDZ PHYSICS COMPILATION - STOP"
	exit
    fi
fi


## 2.8 Compile DYNAMICO
if [ $compdyna == y ] ; then
    cd $modipsl/modeles/DYNAMICO
    echo; echo "NOW COMPILE DYNAMICO "
    echo >> $outfile ; echo " NOW COMPILE DYNAMICO"   >> $outfile 
    
    if [ $compoasis == y ] ; then
	argoasis="-with_oasis "
    else
	argoasis=" "
    fi
    if [ $compinca == y ] ; then
	arginca="-with_inca "
    else
	arginca=" "
    fi
    
    
    echo ./make_icosa -$optmode -with_fcm1 -parallel $parallel -external_ioipsl $argoasis -with_xios -arch $fcm_arch -arch_path $arch_path -job 8 $full_dyna    >> $outfile 
    ./make_icosa -$optmode -with_fcm1 -parallel $parallel -external_ioipsl $argoasis -with_xios -arch $fcm_arch -arch_path $arch_path -job 8 $full_dyna    >> $outfile 2>&1
    # Test if compiling finished
    if [[ $? != 0 ]] ; then
	echo "THERE IS A PROBLEM IN DYNAMICO COMPILATION - STOP"
	exit
    fi
fi
    
## 2.9 Compile interface ICOSA_LMDZ
if [ $compdyna == y ] ; then
    cd $modipsl/modeles/ICOSA_LMDZ
    echo; echo "NOW COMPILE ICOSA_LMDZ "
    echo >> $outfile ; echo " NOW COMPILE ICOSA_LMDZ"   >> $outfile 
    
    echo ./make_icosa_lmdz -nodeps -p lmd -$optmode -parallel $parallel $argoasis -with_orchidee $arginca -arch ${fcm_arch} -arch_path ${arch_path} -job 8 $full_dyna    >> $outfile 
    ./make_icosa_lmdz -nodeps -p lmd -$optmode -parallel $parallel $argoasis -with_orchidee $arginca -arch ${fcm_arch} -arch_path ${arch_path} -job 8 $full_dyna    >> $outfile 2>&1
    # Test if compiling finished
    if [[ $? != 0 ]] ; then
	echo "THERE IS A PROBLEM IN ICOSA_LMDZ COMPILATION - STOP"
	exit
    fi
    # Move executables to modipsl/bin
    if [ -f $modipsl/modeles/ICOSA_LMDZ/bin/icosa_lmdz.exe ] ; then 
	if [ $compinca == y ] ; then
	    mv $modipsl/modeles/ICOSA_LMDZ/bin/icosa_lmdz.exe $modipsl/bin/icosa_lmdz_${orchversion}_${optmode}_${optchimie}.exe
	    # Create link to be use by IPSLCM and LMDZOR without any change in the executable name
	    cd  $modipsl/bin
            rm -f icosa_lmdz_${orchversion}_${optmode}.exe
	    ln -s icosa_lmdz_${orchversion}_${optmode}_${optchimie}.exe icosa_lmdz_${orchversion}_${optmode}.exe
	else
	    mv $modipsl/modeles/ICOSA_LMDZ/bin/icosa_lmdz.exe $modipsl/bin/icosa_lmdz_${orchversion}_${optmode}.exe
	fi
    else
	echo "THERE IS A PROBLEM IN ICOSA_LMDZ COMPILATION EXECUTABLE MISSING - STOP"
	exit
    fi
fi


## 2.10 Compile LMDZ for regular latlon configuration
if [ $regular_latlon = y ] ; then

    cd $modipsl/modeles/LMDZ
    # Compile LMDZ regular lat-lon exectuable
    echo; echo "NOW COMPILE LMDZ REGULAR LAT-LON MODE. Resolution = ${resol_atm}"
    echo >> $outfile ; echo " NOW COMPILE LMDZ REGULAR LAT-LON MODE. Resolution = ${resol_atm}"   >> $outfile 
    # Check if the compilation of LMDZ was previsouly interupted prematured. 
    # In that case, the files dimension.h and .lock exist. If the files exist, they are here removed to avoid makelmdz_fcm 
    # to ask question and wait for interactivly answer from the user.
    if [ -f libf/grid/dimensions.h ] || [ -f .lock ] ; then
	echo >> $outfile
	echo " WARNING!! The file LMDZ/libf/grid/dimension.h and/or the LMDZ/.lock exist. "   >> $outfile
	echo "           This means that the compilation is either currently on going in another terminal was previous interupted before the end."   >> $outfile
	echo "           The files dimension.h and .lock will now be removed. "   >> $outfile
	echo >> $outfile
	rm -f libf/grid/dimensions.h
	rm -f .lock
    fi

    # Need to define the proper option for radiative code compilation. By default, we use rrtm
    case $rad in
	oldrad) opt_rad="" ;;
	rrtm)    opt_rad="-rad rrtm" ;;
	ecrad)  opt_rad="-rad ecrad" ;;
	*) echo Only oldrad rrtm ecrad for rad option ; exit
    esac
    
    if [ $compinca == y ] ; then
	arginca="-chimie INCA"
    else
	arginca=""
    fi
    
    if [ $compoasis == y ] ; then
	argoasis="-c OMCT"
    else
	argoasis=""
    fi
    echo ./makelmdz_fcm -d ${resol_atm} $argoasis -p lmd $opt_rad -$optmode -mem -parallel $parallel $arginca  -io xios -v $argorch -arch $fcm_arch -arch_path $arch_path -j 8 $full_lmdz gcm    >> $outfile 
         ./makelmdz_fcm -d ${resol_atm} $argoasis -p lmd $opt_rad -$optmode -mem -parallel $parallel $arginca  -io xios -v $argorch -arch $fcm_arch -arch_path $arch_path -j 8 $full_lmdz gcm    >> $outfile 2>&1
    # Test if compiling finished
    if [[ $? != 0 ]] ; then
	echo "THERE IS A PROBLEM IN LMDZ REGULAR LATLON COMPILATION - STOP"
	exit
    fi

    # Find executable suffix
    suffix=_${resol_atm}_phylmd
    suffix=${suffix}_${rad} 
    if [ $parallel == seq ] || [ $parallel == none ] ; then
	suffix=${suffix}_seq_orch_inca.e
    else
	if [ $compoasis == y ] ; then
	    suffix=${suffix}_para_mem_orch_couple
	else
	    suffix=${suffix}_para_mem_orch
	fi
	if [ $compinca == y ] ; then
	    suffix=${suffix}_inca.e
	else
	    suffix=${suffix}.e
	fi
    fi
    echo gcm suffix = $suffix
    
    # Move executables to modipsl/bin folder
    echo "Move gcm.e executable to modipsl/bin"
    if [ -f $modipsl/modeles/LMDZ/bin/gcm${suffix} ] ;  then
	if [ $compinca == y ] ; then
	    mv $modipsl/modeles/LMDZ/bin/gcm${suffix} $modipsl/bin/gcm_${resol_atm}_${orchversion}_${optmode}_${optchimie}.e
	    # Create link to be use by IPSLCM and LMDZOR without any change in the executable name
	    cd $modipsl/bin
            rm -f gcm_${resol_atm}_${orchversion}_${optmode}.e
	    ln -s gcm_${resol_atm}_${orchversion}_${optmode}_${optchimie}.e gcm_${resol_atm}_${orchversion}_${optmode}.e
	else
	    mv $modipsl/modeles/LMDZ/bin/gcm${suffix} $modipsl/bin/gcm_${resol_atm}_${orchversion}_${optmode}.e
	fi
    else
	echo "ERROR gcm${suffix} executable does not exist." 
	echo "THERE IS A PROBLEM IN LMDZ REGULAR LATLON COMPILATION - STOP"
	exit
    fi    

    # Find executable suffix
    suffix=_${resol_atm}_phylmd
    suffix=${suffix}_${rad} 
    if [ $parallel == seq ] || [ $parallel == none ] ; then
	suffix=${suffix}_seq_orch.e
    else
	if [ $compoasis == y ] ; then
	    suffix=${suffix}_para_mem_orch_couple.e
	else
	    suffix=${suffix}_para_mem_orch.e
	fi
    fi
    echo ce0l suffix = $suffix

    # Compile ce0l initialization program for LMDZ regular lat-lon exectuable
    cd $modipsl/modeles/LMDZ
    echo; echo "NOW COMPILE CE0L OF LMDZ. Resolution = ${resol_atm}"
    echo >> $outfile ; echo " NOW COMPILE CE0L OF LMDZ. Resolution = ${resol_atm}"   >> $outfile 

    echo ./makelmdz_fcm -d ${resol_atm} $argoasis -p lmd -rrtm true -$optmode -mem -parallel $parallel -io xios -v $argorch -arch $fcm_arch -arch_path $arch_path -j 8 $full_lmdz ce0l    >> $outfile 
         ./makelmdz_fcm -d ${resol_atm} $argoasis -p lmd -rrtm true -$optmode -mem -parallel $parallel -io xios -v $argorch -arch $fcm_arch -arch_path $arch_path -j 8 $full_lmdz ce0l    >> $outfile 2>&1
    # Test if compiling finished
    if [[ $? != 0 ]] ; then
	echo "THERE IS A PROBLEM IN CE0L (LMDZ) REGULAR LATLON COMPILATION - STOP"
	exit
    fi
   
 
    # Move executable ce0l to modipsl/bin folder
    echo "Move ce0l executable to modipsl/bin"
    if [ -f $modipsl/modeles/LMDZ/bin/ce0l${suffix} ] ;  then
	mv $modipsl/modeles/LMDZ/bin/ce0l${suffix} $modipsl/bin/ce0l_${resol_atm}_${optmode}.e
    else
	echo "ERROR ce0l${suffix} executable does not exist." 
	echo "THERE IS A PROBLEM IN LMDZ REGULAR LATLON COMPILATION - STOP"
	exit
    fi
fi

echo >>$outfile ; echo "ALL COMPILING FINISHED" >> $outfile
echo ls -lrt modipsl/bin >> $outfile
ls -lrt $modipsl/bin >> $outfile

echo; echo "ALL COMPILING FINISHED" ; echo
echo "Executables are found in modipsl/bin"
echo "Check that executable names correspond with the name set in config.card before launching the job"
echo ls -lrt modipsl/bin
ls -lrt $modipsl/bin

date

exit


