###########################################################################
#
# Shell verification. Try to be robust => very simple.
#
GAG_SHELL_TEST="shell test" || echo "gildas-env.sh error: You must be under a sh-compatible shell!"
GAG_SHELL_TEST="shell test" || exit 1
unset GAG_SHELL_TEST
#
###########################################################################
#
# Main function definition
#
gagenv() {
    #
    # Variable and function definitions
    #
    GAGENV_AUTHOR='J. Pety <pety@iram.fr>'
    GAGENV_VERSION=`echo '$Revision$' | cut -d' ' -f2`
    GAGENV_PROJECT='GILDAS <http://www.iram.fr/IRAMFR/GILDAS>'
    GAGENV_PROGNAME="gildas-env.sh"
    #
    gagenv_usage() {
        cat <<EOF 1>&2

Define the environment needed for compilation, test and installation
GILDAS. It take the following steps:

  1. Definition of:
           * gagadmdir       (administrative directory);
           * gagsrcdir       (root directory of the source tree);
           * gagintdir       (root directory of the integration tree);
           * gagexedir       (root directory of the executable tree);
           * GAG_ROOT_DIR    (root directory of the currently used tree);
           * GAG_GAG         (location of init, scratch, and log directories)
           * GAG_PATH        (location of dictionaries);
           * GAG_VERS        (current gildas version);
           * GAG_EXEC_SYSTEM (MACHINE-OS-COMPILER(-CONFIG));
           * GAG_OBSERVATORY (default observatory at ASTRO startup);
           * GAG_PAPER_SIZE  (default paper size in PostScript files).

     By default, GAG_OBSERVATORY is set to NOEMA. If you want to
     change this default, just "export GAG_OBSERVATORY=YOUR-OBS-NAME"
     before sourcing gildas-env.sh. By default, GAG_PAPER_SIZE is set
     to A4. If you want to change this default to US_LETTER, just
     export "GAG_PAPER_SIZE=US_LETTER" before sourcing gildas-env.sh.

  2. Search for the binaries and associated headers of important
     libraries (GTK+, ...). Search first in standard places, then in a
     path that user can pass either through the GAG_SEARCH_PATH
     environment variable or through the -s switch. A warning is
     output when the search fails. GILDAS by default uses its own
     versions of the FFT library. If the user wants to use its own
     copies (e.g. FFTW v3), he has to pass the directory where those
     libraries are installed in the search path (i.e. through
     GAG_SEARCH_PATH or through the -s switch).

  3. Search for useful, but non-essential GILDAS dependencies (ie
     CFITSIO,PNG) in the path passed either through GAG_SEARCH_PATH or
     through the -s switch. Default to sensible solution when not
     found.

  4. (Re)define needed paths for full use of the source tree in place
     (ie before installation). Some of the (re)defined paths are also
     useful at compile time.

usage: $GAGENV_PROGNAME [options]

options:
  -b ccompiler  Replace default C compiler by this one
  -c fcompiler  Replace default Fortran compiler by this one
  -d cxxcompil  Replace default C++ compiler by this one
  -o <config>   Add config to the config list.
  -u use-dir    Set gildas directory to use as a complement of local Gildas.
  -s path       Additional search path for libraries GILDAS depends
                upon. This path is searched after default standard
                locations and will thus override them.
  -p            Compile prototypes in addition of stables GILDAS parts
                Setting the GAG_PROTO environment variable to "yes" will
                have the same effect.
  -n <feature>  Disable input feature. Keyword(s) can be:
                  python  : disable Python binding
                or any other config as set with -o option.
  -t target     Define the system target compiled under current
                build environment.
  -x            Also detect X11. X11 is not directly a Gildas dependency,
                but it might be needed for other software built against
                Gildas.
  -h            Show this help page
  -v            Show version information

EOF
        gagenv_clean
    }
    #
    gagenv_showversion() {
        echo
        echo "$GAGENV_PROGNAME version $GAGENV_VERSION, by $GAGENV_AUTHOR"
        echo "Project: $GAGENV_PROJECT"
        echo
        gagenv_clean
    }
    #
    gagenv_message() {
        echo "$1"
    }
    #
    gagenv_error() {
        echo "$GAGENV_PROGNAME error: $1" 1>&2
    }
    #
    gagenv_remove_config() {
        if [ "$GAGENV_CONFIG" != "default" ]; then
            GAGENV_CONFIG=`echo $GAGENV_CONFIG|tr '-' '\n'|egrep -v "^$1\$"|tr '\n' '-' | \sed 's/-$//'`
            if [ "$GAGENV_CONFIG" = "" ]; then
                GAGENV_CONFIG="default"
            fi
        fi
    }
    #
    gagenv_add_config() {
        #if [ $1 =~ "^no_" ]; then # works with recent bash
        if [ `echo $1 | grep '^no_'` ]; then
            # remove yes config
            NO_CONFIG=`echo $1 | \sed 's/no_//'`
            gagenv_remove_config $NO_CONFIG
            gagenv_disable $NO_CONFIG "yes"
        else
            # remove no config
            gagenv_remove_config no_$1
            gagenv_disable $1 "no"
        fi;
        if [ "$GAGENV_CONFIG" = "default" ]; then
            GAGENV_CONFIG=$1;
        else
            GAGENV_CONFIG=$GAGENV_CONFIG-$1;
        fi;
    }
    #
    gagenv_disable() {
        # Disable or reenable input feature. Variables DISABLE_* are local to
        # this file, and ensure detection or not of the desired feature.
        # If input feature name in unknown: no matter. This means that it has
        # no effect in this file.
        # $1: feature name
        # $2: "yes" or "no"
        if [ "$1" = "python" ]; then
            DISABLE_PYTHON=$2
        elif [ "$1" = "staticlink" ]; then
            if [ "$2" = "no" ]; then
        	DISABLE_PYTHON="yes"
            fi
        elif [ "$1" = "profile" ]; then
            # Config "-o profile" turns on static linking: must disable Python
            if [ "$2" = "no" ]; then
        	DISABLE_PYTHON="yes"
            fi
        fi
    }
    #
    gagenv_clean() {
        unset GAGENV_AUTHOR GAGENV_PROJECT GAGENV_PROGNAME
        unset GAGENV_CCOMPILER GAGENV_FCOMPILER GAGENV_CXXCOMPILER GAGENV_CONFIG
        unset GAG_INT_BIN_DIR GAG_INT_INC_DIR GAG_INT_LIB_DIR GAG_INT_PYTHON_DIR GAG_INT_ROOT_DIR GAG_INT_TASKTEX_DIR
        unset gagenv_errors gagenv_warnings
        unset gagenv_usage gagenv_showversion gagenv_message gagenv_error gagenv_clean
        unset DISABLE_PYTHON
        unset DIR DIRLIST NO_CONFIG occurences gagenv_option_x11
    }
    #
    # file_present "FILE" "DIR": Is file FILE present in DIR directory?
    file_present() {
        # Find any extension (e.g. so, a, dll, ...) which does NOT contain a
        # dot (e.g. so.3 is not counted), because e.g. /usr/lib64/liblapack.so.3
        # is useless and can not be found by the linker on command lines like
        # "-L/usr/lib -llapack"
        occurences=`\ls ${2}/${1}* 2> /dev/null | \grep -v "${2}/${1}.*\." | \wc -l`
        if [ ${occurences} -ge 1 ]; then
            \return 0
        else
            \return 1
        fi
    }
    #
    # file_absent "FILE" "DIR": Is file FILE absent in DIR directory?
    file_absent() {
        if file_present ${1} ${2}; then
            \return 1
        else
            \return 0
        fi
    }
    #
    # Portable functions for version strings comparison, based on sort -V.
    verle() {
        # Return 0 if first argument is "lower or equal" the second argument
        # NB: the line return in echo below is more portable than echo -e "\n"
        [  "$1" = "`echo "$1
$2" | sort -V | head -n1`" ]
    }
    verlt() {
        # Return 0 if first argument is "lower than" second argument
        [ "$1" = "$2" ] && return 1 || verle $1 $2
    }
    #
    gagenv_detect_x11() {
	#
	X11_INC=no
	X11_LIB=no
	OLDIFS=$IFS
	IFS=:
	for DIR in $INC_PATH; do
	    if file_present "X.h" "${DIR}/X11"; then
		X11_INC=yes
		X11_INC_DIR=$DIR
	    fi
	done
	for DIR in $LIB_PATH; do
	    if file_present "libX11." "${DIR}"; then
		X11_LIB=yes
		X11_LIB_DIR=$DIR
	    fi
	done
	IFS=$OLDIFS
	#
	if [ "$X11_INC" = "yes" ]; then
	    gagenv_message "Found X11 header  in $X11_INC_DIR"
	    GAG_INC_DEP_PATH=$GAG_INC_DEP_PATH:$X11_INC_DIR
	else
	    gagenv_message "WARNING: X11 header file not found"
	    gagenv_message "This is only needed for the PdBI utilities"
	    gagenv_warnings=$((gagenv_warnings+1))
	fi
	if [ "$X11_LIB" = "yes" ]; then
	    gagenv_message "Found X11 library in $X11_LIB_DIR"
	    GAG_LIB_DEP_PATH=$GAG_LIB_DEP_PATH:$X11_LIB_DIR
	else
	    gagenv_message "WARNING: X11 binary file not found"
	    gagenv_message "This is probably not needed on your system"
	    gagenv_warnings=$((gagenv_warnings+1))
	fi
	#
	# Clean local variables
	unset X11_INC X11_LIB X11_INC_DIR X11_LIB_DIR
    }
    #
    gagenv_detect_legacy() {
	#
	# Explore GAGENV_SEARCH_PATH
	#
	FFTW3_PRESENT=no
	FFTW3F_PRESENT=no
	#
	OLDIFS=$IFS
	IFS=:
	for DIR in $GAGENV_SEARCH_PATH; do
	    # Note: libfftw3 and libfftw3f must be in the same directory
	    if file_present "libfftw3." "${DIR}"; then
		FFTW3_PRESENT=yes
		FFTW3_LIB_DIR=$DIR
		if file_present "libfftw3f." "${DIR}"; then
		    FFTW3F_PRESENT=yes
		fi
	    fi
	done
	IFS=$OLDIFS
	#
	if [ "$GAG_CONFIG" != -no_openmp ]; then
	    gagenv_message "FFTW v3 are not supported in OpenMP mode. Default to GILDAS FFT."
	    FFTW3_PRESENT=no
	    FFTW3F_PRESENT=no
	elif [ "$FFTW3F_PRESENT" = "yes" ]; then
	    gagenv_message "Found FFTW v3 libraries in $FFTW3_LIB_DIR"
	    GAG_LIB_DEP_PATH=$GAG_LIB_DEP_PATH:$FFTW3_LIB_DIR
	elif [ "$FFTW3_PRESENT" = "yes" ]; then
	    gagenv_message "Found FFTW v3 library in $FFTW3_LIB_DIR"
	    GAG_LIB_DEP_PATH=$GAG_LIB_DEP_PATH:$FFTW3_LIB_DIR
	else
	    gagenv_message "FFTW3 not found. Default to GILDAS FFT."
	fi
	#
	# Clean local variables
	unset FFTW3_LIB_DIR
    }
    #
    gagenv_detect_openmp() {
        #
        if [ "$GAG_CONFIG" = -no_openmp ]; then
            gagenv_message "Parallelization with OpenMP is DISABLED."
        else
            gagenv_message "Parallelization with OpenMP is enabled."
        fi
    }
    #
    gagenv_detect_atm() {
	#
	if [ -n "$GAG_COMPILER_CXXEXE" ]; then
	    ATM2009_PRESENT=yes  # Default is to activate this one
	    ATM2016_PRESENT=no
	else
	    gagenv_message "No C++ compiler found in your \$PATH"
	    gagenv_message "This means that ATM will not be available"
	    ATM2009_PRESENT=no
	    ATM2016_PRESENT=no
	fi
	#
	if [ "$ATM2009_PRESENT" = "yes" ] || [ "$ATM2016_PRESENT" = "yes" ]; then
	    gagenv_message "Found $GAG_COMPILER_CXXEXE compiler in your \$PATH"
	    gagenv_message "You will have the possibility to use ATM 2009/2016 in ASTRO"
	    gagenv_message 'Just type "ASTRO> set atm 2009|2016"'
	else
	    gagenv_warnings=$((gagenv_warnings+1))
	fi
    }
    #
    gagenv_detect_png() {
        #
	if \which libpng-config > /dev/null 2>&1; then
	    PNG_VERSION=`libpng-config --version`
	    gagenv_message "Found PNG $PNG_VERSION development tools"
	    PNG_PRESENT=yes
	else
	    gagenv_message "WARNING: PNG development tools not found"
	    gagenv_message "You won't be able to produce PNG hardcopies"
	    PNG_PRESENT=no
	    gagenv_warnings=$((gagenv_warnings+1))
	fi
	#
	# Clean local variables
	unset PNG_VERSION
    }
    #
    gagenv_detect_gtk() {
	#
	GTK_PRESENT=no
	if ! \which pkg-config > /dev/null 2>&1; then
	    gagenv_message "ERROR: pkg-config not found on your system"
	    gagenv_message "Some dependencies can not be detected without it"
	    gagenv_errors=$((gagenv_errors+1))
	elif pkg-config --exists gtk+-2.0; then
	    GTK_VERSION=`pkg-config --modversion gtk+-2.0`
	    gagenv_message "Found GTK+ $GTK_VERSION"
	    GTK_VERSION_MAJOR=`echo $GTK_VERSION | \sed "s%\([0-9][0-9]*\)\.[0-9][0-9]*.*%\1%"`
	    GTK_VERSION_MINOR=`echo $GTK_VERSION | \sed "s%[0-9][0-9]*\.\([0-9][0-9]*\).*%\1%"`
	    if [ "$GTK_VERSION_MAJOR" -lt "2" ]; then
		gagenv_message "ERROR: this version is too old, support starts at 2.6"
		GTK_PRESENT=no
		gagenv_errors=$((gagenv_errors+1))
	    elif [ "$GTK_VERSION_MINOR" -lt "6" ]; then
		gagenv_message "ERROR: this version is too old, support starts at 2.6"
		GTK_PRESENT=no
		gagenv_errors=$((gagenv_errors+1))
	    else
		GTK_PRESENT=yes
	    fi
	else
	    gagenv_message "ERROR: GTK+ 2.0 not found on your system"
	    gagenv_message "You have to install the GTK+ 2.0 development package"
	    gagenv_errors=$((gagenv_errors+1))
	fi
	#
	# Clean local variables
	unset GTK_VERSION GTK_VERSION_MAJOR GTK_VERSION_MINOR
    }
    #
    gagenv_detect_openssl() {
	#
	OPENSSL_PRESENT=no
	if \which pkg-config > /dev/null 2>&1; then
	    # Already raised a warning if pkg-config is not available
	    if pkg-config --exists openssl; then
		OPENSSL_PRESENT=yes;
	    fi
	fi
	#
	if [ "$OPENSSL_PRESENT" = "yes" ]; then
	    gagenv_message "Found OPENSSL version "`pkg-config --modversion openssl`" in "`pkg-config --variable=libdir openssl`
	else
	    gagenv_message "WARNING: OPENSSL not found using pkg-config"
	    gagenv_warnings=$((gagenv_warnings+1))
	fi
    }
    #
    gagenv_detect_cfitsio() {
	#
	CFITSIO_PRESENT=no
	if \which pkg-config > /dev/null 2>&1; then
	    # Already raised a warning if pkg-config is not available
	    #
	    # For backward compatibility, search first in $GAG_SEARCH_PATH paths
	    OLD_PKG_CONFIG_PATH=$PKG_CONFIG_PATH
	    OLDIFS=$IFS
	    IFS=:
	    for DIR in $GAG_SEARCH_PATH; do
		export PKG_CONFIG_PATH="${DIR}/pkgconfig${OLD_PKG_CONFIG_PATH:+:$OLD_PKG_CONFIG_PATH}"
		if pkg-config --exists cfitsio; then
		    CFITSIO_PRESENT=yes
		    break
		else
		  PKG_CONFIG_PATH=$OLD_PKG_CONFIG_PATH
		fi
	    done
	    IFS=$OLDIFS
	    #
	    # Not found in $GAG_SEARCH_PATH? Try user's custom PKG_CONFIG_PATH or default
	    # system location
	    if [ "$CFITSIO_PRESENT" != "yes" ]; then
		if pkg-config --exists cfitsio; then
		    CFITSIO_PRESENT=yes;
		fi
	    fi
	fi
	#
	if [ "$CFITSIO_PRESENT" = "yes" ]; then
	    gagenv_message "Found CFITSIO version "`pkg-config --modversion cfitsio`" in "`pkg-config --variable=libdir cfitsio`
	    gagenv_message "You will have support for on-line 30m calibration (inside MIRA or MRTCAL)"
	else
	    gagenv_message "WARNING: CFITSIO not found using pkg-config and looking in \$PKG_CONFIG_PATH"
	    gagenv_message "This means impossible calibration of data from 30m/NCS inside MIRA or MRTCAL"
	    gagenv_message "The FITS <-> Gildas internal converters will still be available"
	    gagenv_warnings=$((gagenv_warnings+1))
	fi
	#
	# Clean local variables
	unset OLD_PKG_CONFIG_PATH
    }
    #
    gagenv_detect_python() {
	#
	# Detection
	unset GAG_PYTHON_VERS
	if [ "$DISABLE_PYTHON" = "no" ]; then
	    PYTHON_VERS=none
	    PYTHON_VERS_FULL=none
	    PYTHON_INC=no
	    PYTHON_LIB=no
	    NUMPY_PRESENT=no
	    SQLITE3_PRESENT=no
	    SETUPTOOLS_PRESENT=no
	    PYTHONCONFIG_PRESENT=no
	    if \which python > /dev/null 2>&1; then
		# Check the version of python the user is currently using
		if python -V 2>&1 > /dev/null 2>&1; then
		    PYTHON_VERS_FULL=`python -V 2>&1 | cut -d' ' -f2`
		    PYTHON_VERS=`echo $PYTHON_VERS_FULL | \sed "s%\([0-9]\.[0-9][0-9]*\).*%\1%"`
		    # Search for Python header and library. kernel/python/binding/setup.py
		    # does exactly the same, so this should be consistent
		    PYTHON_INC_DIR=`python -c "import sysconfig; print(sysconfig.get_config_var('INCLUDEPY'))"`
		    if [ -e "$PYTHON_INC_DIR/Python.h" ]; then PYTHON_INC=yes; else PYTHON_INC=no; fi
		    PYTHON_LIB_DIR=`python -c "import sysconfig; print(sysconfig.get_config_var('LIBDIR'))"`
		    PYTHON_LIB=yes  # libpython name on the various supported systems is just
				    # unpredictible. Can not check in advance if the linker will
				    # find it or not. See also our script python-config-ldflags.py
		    #
		    # Now search for Numpy
		    if python -c "import numpy" > /dev/null 2>&1; then
			NUMPY_PRESENT=yes
			NUMPY_INC_DIR=`python -c "import numpy; print(numpy.__path__[0] + '/core/include')"`
			if [ -e "$NUMPY_INC_DIR/numpy/arrayobject.h" ]; then
			    NUMPY_INC_PRESENT=yes
			else
			    NUMPY_INC_PRESENT=no
			fi
		    fi
		    # Search for sqlite3
		    if python -c "import sqlite3" > /dev/null 2>&1; then
			SQLITE3_PRESENT=yes
		    fi
		    # Search for setuptools
		    if python -c "import setuptools" > /dev/null 2>&1; then
			SETUPTOOLS_PRESENT=yes
		    fi
		    # Search for python-config
		    if \which python-config > /dev/null 2>&1; then
		       PYTHONCONFIG_PRESENT=yes
		    fi
		fi
	    else
		gagenv_message "Python not found in your \$PATH"
	    fi
	fi
	export GAG_PYTHON_VERS=$PYTHON_VERS_FULL
	#
	# Feedback
	PYTHON_SUPPORTED="3.6"  # Minimum Python version supported
	if [ "$DISABLE_PYTHON" = "yes" ]; then
	    gagenv_message "You have disabled Python binding"
	elif [ "$PYTHON_VERS" = "none" ]; then
	    gagenv_message "Problem executing Python"
	    PYTHON_PRESENT=no
	elif verlt "$PYTHON_VERS" "$PYTHON_SUPPORTED"; then
	    gagenv_message "Python $PYTHON_VERS not supported (support available from $PYTHON_SUPPORTED)"
	    PYTHON_PRESENT=no
	elif [ "$SETUPTOOLS_PRESENT" = "no" ]; then
	    gagenv_message "Python module setuptools not found"
	    PYTHON_PRESENT=no
	elif [ "$PYTHONCONFIG_PRESENT" = "no" ]; then
	    gagenv_message "python-config utility not found"
	    PYTHON_PRESENT=no
	elif [ "$GAG_TARGET_KIND" = "linux" ] || [ "$GAG_TARGET_KIND" = "darwin" ] || [ "$GAG_TARGET_KIND" = "cygwin" ]; then
	    # Detect the libraries and add them to paths ONLY if system is supported
	    if [ "$PYTHON_INC" = "yes" -a "$PYTHON_LIB" = "yes" ]; then
		gagenv_message "Found PYTHON $PYTHON_VERS_FULL header  in $PYTHON_INC_DIR"
		gagenv_message "Found PYTHON $PYTHON_VERS_FULL library in $PYTHON_LIB_DIR"
		if [ "$NUMPY_PRESENT" = "yes" ]; then
		    GAG_LIB_DEP_PATH=$GAG_LIB_DEP_PATH:$PYTHON_LIB_DIR
		    GAG_INC_DEP_PATH=$GAG_INC_DEP_PATH:$PYTHON_INC_DIR
		    if [ "$NUMPY_PRESENT" = "yes" ]; then
			gagenv_message "Found Numpy python package"
			if [ "$NUMPY_INC_PRESENT" = "yes" ]; then
			    gagenv_message "Found Numpy header file in $NUMPY_INC_DIR"
			    PYTHON_PRESENT=yes
			else
			    gagenv_message "Numpy header file not found"
			    PYTHON_PRESENT=no
			fi
		    fi
		    if [ "$PYTHON_PRESENT" = "no" ]; then
			# We already found a condition not satisfied
			:  # Do nothing
		    elif [ "$GAG_TARGET_KIND" = "linux" ]; then
			if [ -z "$GAG_COMPILER_FLIBS" ];  then
			    PYTHON_PRESENT=no
			    gagenv_message "Undefined library associated to $GAG_COMPILER_FEXE"
			else
			    PYTHON_PRESENT=yes
			fi
		    fi
		else
		    PYTHON_PRESENT=no
		    gagenv_message "Numpy python package not found"
		fi
	    else
		if [ "$PYTHON_INC" = "no" -a "$PYTHON_LIB" = "no" ]; then
		    gagenv_message "PYTHON $PYTHON_VERS_FULL library and header files not found"
		elif [ "$PYTHON_INC" = "no" ]; then
		    gagenv_message "PYTHON $PYTHON_VERS_FULL header file not found"
		else
		    gagenv_message "PYTHON $PYTHON_VERS_FULL library file not found"
		fi
		gagenv_message "Missing Python Development package for your system?"
		PYTHON_PRESENT=no
	    fi
            gagenv_message "You will have access to the Python port of GILDAS"
	else
	    PYTHON_PRESENT=no
	    gagenv_message "Python not supported on $GAG_TARGET_KIND"
	fi
	if [ "$DISABLE_PYTHON" = "yes" -o "$PYTHON_PRESENT" = "no" ]; then
	    gagenv_message "WARNING: GILDAS Python binding will *not* be available"
	    gagenv_warnings=$((gagenv_warnings+1))
	fi
	#
	# Clean local variables
	unset  PYTHON_VERS    PYTHON_VERS_FULL PYTHON_SUPPORTED
	unset  PYTHON_INC     PYTHON_LIB
	unset  PYTHON_INC_DIR PYTHON_LIB_DIR
	unset  NUMPY_INC_DIR  NUMPY_INC_PRESENT
	unset  SETUPTOOLS_PRESENT PYTHONCONFIG_PRESENT
    }
    #
    gagenv_detect_weeds() {
	# Check if Weeds can be enabled or not
	#
	# Detection
	if [ "$PYTHON_PRESENT" = "no" ]; then
	    WEEDS_PRESENT=no
	elif [ "$SQLITE3_PRESENT" = "no" ]; then
	    gagenv_message "sqlite3 Python module not found (required by Weeds)"
	    WEEDS_PRESENT=no
	else
	    WEEDS_PRESENT=yes
	fi
	#
	# Feedback
	if [ "$WEEDS_PRESENT" = "yes" ]; then
	    gagenv_message "You will have access to the Weeds extension of Class"
	else
	    gagenv_message "WARNING: You will not have access to the Weeds extension of Class"
	    gagenv_warnings=$((gagenv_warnings+1))
	fi
	#
	unset SQLITE3_PRESENT  # Not needed anymore
    }
    #
    #######################################################################
    #
    # Option parsing
    #
    GAGENV_SEARCH_PATH=$GAG_SEARCH_PATH
    GAGENV_CCOMPILER="default" # Default C compiler will be setup by gagdefsys
    GAGENV_FCOMPILER="default" # Default Fortran compiler will be setup by gagdefsys
    GAGENV_CXXCOMPILER="default" # Default C++ compiler will be setup by gagdefsys
    GAGENV_CONFIG="default"
    GAGENV_TARGET="default"
    DISABLE_PYTHON=no
    gagusedir=
    gagenv_option_x11="no"
    temp=`getopt "hvpb:c:d:n:o:u:s:t:x" "$@"`
    if [ $? -ne 0 ]; then gagenv_usage; \return 1; fi
    eval set -- "$temp"
    unset temp
    while [ $1 != -- ]; do
        case $1 in
        -p) GAG_PROTO="yes" ;;
        -b) GAGENV_CCOMPILER=$2; shift ;;
        -c) GAGENV_FCOMPILER=$2; shift ;;
        -d) GAGENV_CXXCOMPILER=$2; shift ;;
        -n) gagenv_add_config no_$2; shift ;;
        -o) gagenv_add_config $2; shift ;;
        -u) if [ $2 != "default" ]; then gagusedir=$2; fi; shift ;;
        -s) GAGENV_SEARCH_PATH=$2; shift ;;
        -t) GAGENV_TARGET=$2; shift ;;
        -x) gagenv_option_x11="yes" ;;
        -v) gagenv_showversion; \return 0 ;;
        -h) gagenv_usage; \return 0 ;;
        esac
        shift # Next flag
    done
    shift # Skip double dash
    set abc; shift # This line to avoid remanence effect in a portable way
    #
    # And go on
    #
    export gagusedir
    #
    echo
    #
    #######################################################################
    #
    # Definition of gagsrcdir, gagadmdir, gagintdir, gagexedir,
    # GAG_ROOT_DIR, GAG_VERS, GAG_EXEC_SYSTEM, GAG_PROTO
    #
    if [ -z "$gagsrcdir" ]; then
        gagsrcdir=`pwd`
    elif [ ! -d "$gagsrcdir" ]; then
        gagenv_error "\$gagsrcdir=$gagsrcdir does not exist"
        gagenv_clean
        echo
        \return 1
    fi
    if [ -z "$ogagsrcdir" ]; then
        ogagsrcdir=$gagsrcdir
    fi
    export gagsrcdir ogagsrcdir
    #
    if [ -d "$gaghome/gildas-admin" ]; then
        gagadmdir=$gaghome/gildas-admin
    elif [ -d "$gagsrcdir/admin" ]; then
        gagadmdir=$gagsrcdir/admin
    else
        gagenv_error "Failed to define \$gagadmdir."
        gagenv_error "Please define \$gagsrcdir by hand and load $GAGENV_PROGNAME again."
        gagenv_clean
        echo
        \return 1
    fi
    export gagadmdir
    #
    if [ `echo $gagsrcdir | grep -c "gildas-src"` -ne 0 ]; then
        gagexedir=`echo $gagsrcdir | \sed -e "s&gildas-src&gildas-exe&g"`
        if [ `basename $gagexedir | grep -c "gildas-exe"` -eq 0 ]; then
            gagexedir=`dirname $gagexedir`
        fi
    else
        gagexedir=`dirname $gagsrcdir`/gildas-exe
    fi
    export gagexedir
    #
    if [ -z $gagusedir ]; then
        GAG_VERS=`cat $gagsrcdir/VERSION`
    else
        GAG_VERS=`cat $gagusedir/etc/VERSION`
    fi
    export GAG_VERS
    #
    . $gagadmdir/define-system.sh                                 # Load gagdefsys function
    gagdefsys -s -b $GAGENV_CCOMPILER -c $GAGENV_FCOMPILER  -d $GAGENV_CXXCOMPILER \
      -o $GAGENV_CONFIG -t $GAGENV_TARGET || \return $?  # Use it
    unset gagdefsys                                               # Remove gagdefsys function
    #
    gagintdir=$gagsrcdir/integ
    export gagintdir
    #
    GAG_ROOT_DIR=$gagintdir
    export GAG_ROOT_DIR
    #
    if [ -z "$GAG_PROTO" ]; then
        GAG_PROTO="no"
    fi
    export GAG_PROTO
    #
    gagenv_message "Selecting GILDAS version: $GAG_VERS, source tree, $GAG_EXEC_SYSTEM"
    gagenv_message ""
    if [ "$GAG_PROTO" = "yes" ]; then
        gagenv_message "Prototypes will also be compiled"
        gagenv_message ""
    fi
    if [ ! -z "$gaghome" ]; then
        gagenv_message "gaghome  :  $gaghome"
    fi
    gagenv_message "gagadmdir:  $gagadmdir"
    gagenv_message "gagsrcdir:  $gagsrcdir"
    gagenv_message "gagexedir:  $gagexedir"
    gagenv_message "gagintdir:  $gagintdir"
    if [ ! -z $gagusedir ]; then
        gagenv_message "gagusedir:  $gagusedir"
    fi
    gagenv_message ""
    #
    #######################################################################
    #
    # PRINT command
    #
    gagenv_errors=0
    gagenv_warnings=0
    #
    if \which lpr > /dev/null 2>&1; then
        GAG_LPR=`\which lpr`" -P"
    elif \which lp > /dev/null 2>&1; then
        GAG_LPR=`\which lp`" -c -d"
    else
        gagenv_message "WARNING: No printing command found (lpr,lp)"
        gagenv_message ""
        gagenv_warnings=$((gagenv_warnings+1))
        GAG_LPR="echo \"Error: Printing command not found for printer \""
    fi
    export GAG_LPR
    #
    #######################################################################
    #
    # GILDAS dependencies
    #
    unset CFITSIO_PRESENT ATM2009_PRESENT ATM2016_PRESENT OPENSSL_PRESENT
    unset FFTW3_PRESENT FFTW3F_PRESENT
    unset PNG_PRESENT GTK_PRESENT
    if [ "$DISABLE_PYTHON" = "no" ]; then
        unset PYTHON_PRESENT NUMPY_PRESENT SQLITE3_PRESENT WEEDS_PRESENT
    fi
    #
    # Default library locations
    if [ "${GAG_TARGET_KIND}" = "mingw" ]; then
        # Mingw: no libraries to be detected. Compiler searches implicitly
        # in /usr/x86_64-w64-mingw32/sys-root/mingw/lib when needed.
        LIB_PATH=
    else
        # Linux or Cygwin (32 or 64 bits: no general rule)
        LIB_PATH=/usr/lib:/usr/local/lib
        if [ $gagenv_option_x11 = "yes" ]; then
            LIB_PATH=$LIB_PATH:/usr/X11R6/lib:/usr/X11/lib
        fi
    fi
    #
    # Header locations under 32/64 bits linux. Add user's $GAG_SEARCH_PATH.
    INC_PATH=`echo $LIB_PATH:$GAGENV_SEARCH_PATH | \sed -e "s&lib&include&g"`
    #
    if [ "$GAG_MACHINE" = "x86_64" ] && [ -d "/usr/lib64" ]; then
        # Machine is 64 bits and libraries are in "lib64" directories
        LIB_PATH=`echo $LIB_PATH | \sed -e "s&lib&lib64&g"`
    elif [ "$GAG_MACHINE" = "pc" ] && [ -d "/usr/lib32" ]; then
        # Machine is 32 bits and libraries are in "lib32" directories
        LIB_PATH=`echo $LIB_PATH | \sed -e "s&lib&lib32&g"`
    fi
    # Add user's $GAG_SEARCH_PATH, but only after converting lib into lib64.
    LIB_PATH=$LIB_PATH:$GAGENV_SEARCH_PATH
    #
    # Check availability of various dependencies, and fill corresponding
    # environment variables:
    #
    unset GAG_LIB_DEP_PATH GAG_INC_DEP_PATH  # Incremented by detection functions
    #
    gagenv_detect_openmp
    gagenv_message ""
    gagenv_detect_atm
    gagenv_message ""
    gagenv_detect_python
    gagenv_detect_weeds  # Must appear after Python detection
    gagenv_message ""
    gagenv_detect_openssl
    gagenv_message ""
    gagenv_detect_cfitsio
    gagenv_message ""
    if [ $gagenv_option_x11 = "yes" ]; then
        gagenv_detect_x11    # Comes after customizable dependencies (Python and CFITSIO)
        gagenv_message ""
    fi
    gagenv_detect_gtk
    gagenv_message ""
    gagenv_detect_png
    gagenv_message ""
    # Below, the dependencies for which we only need the runtime libraries
    # (i.e. no include). This ensures that the previous dependencies have
    # their LIB_PATH and INC_PATH set symmetricaly in the corresponding
    # $GAG_LIB_*_PATH
    gagenv_detect_legacy
    gagenv_message ""
    #
    # Discard /usr/lib, /usr/lib32, and /usr/lib64 paths from $GAG_LIB_DEP_PATH
    # They are found implicitly at compilation time, and we should avoid adding
    # or move them in user's $LD_LIBRARY_PATH at execution time as this tends to
    # break user environment.
    # Note 1: do not use redefine-path which has difficulties to remove a path
    #         (or to replace it with nothing).
    # Note 2: the first trailing column below eases removal of "/usr/lib" and
    #         only "/usr/lib" (not /usr/lib/foo replaced by /foo).
    # Note 3: actually we should automatize the list of implicit paths to be
    #         removed by looking at /etc/ld.so.conf and/or use e.g. ldconfig -v
    GAG_LIB_DEP_PATH=`echo $GAG_LIB_DEP_PATH: | sed -e "s%/usr/lib:%:%g"`
    GAG_LIB_DEP_PATH=`echo $GAG_LIB_DEP_PATH  | sed -e "s%/usr/lib[36][24]:%:%g"`
    GAG_LIB_DEP_PATH=`echo $GAG_LIB_DEP_PATH  | sed -e "s%/usr/lib/x86_64-linux-gnu:%:%g"`
    #
    # Filter out directories appearing twice or more
    GAG_LIB_DEP_PATH=`${gagadmdir}/redefine-path ":" "${GAG_LIB_DEP_PATH}"`
    GAG_INC_DEP_PATH=`${gagadmdir}/redefine-path ":" "${GAG_INC_DEP_PATH}"`
    #
    export CFITSIO_PRESENT ATM2009_PRESENT ATM2016_PRESENT OPENSSL_PRESENT
    export FFTW3_PRESENT FFTW3F_PRESENT
    export PNG_PRESENT GTK_PRESENT
    if [ "$DISABLE_PYTHON" = "no" ]; then
        export PYTHON_PRESENT NUMPY_PRESENT WEEDS_PRESENT
    fi
    #
    #######################################################################
    #
    # Warnings
    #
    if [ "$GAG_MACHINE" = "pc" ]; then
        gagenv_message "You will build 32 bits binaries. THIS IS OBSOLESCENT."
        gagenv_message "CLIC (the NOEMA calibration software) will *not* be available."
        gagenv_message ""
        gagenv_warnings=$((gagenv_warnings+1))
    fi
    #
    if \which anaconda > /dev/null 2>&1; then
        # Anaconda is installed in user's $PATH
        if [ `which anaconda | grep -c "$HOME"` -eq "1" ]; then
            # This seems to be a local installation => breaks 3rd party software
            gagenv_message "WARNING: Found an anaconda installation under your user account"
            gagenv_message "This is likely to break Gildas compilation and/or execution"
            gagenv_message "See www.iram.fr/~gildas/dist/gildas.README > Troubleshooting for details"
            gagenv_message ""
            gagenv_warnings=$((gagenv_warnings+1))
        fi
    fi
    #
    #######################################################################
    #
    # Defaults
    #
    if [ "$GTK_PRESENT" = "yes" ]; then
        GAG_WIDGETS="GTK"
    else
        GAG_WIDGETS="NONE"
    fi
    gagenv_message "Default widget library used: $GAG_WIDGETS"
    if [ "$GAG_WIDGETS" = "NONE" ]; then
        gagenv_message "*** THIS MEANS NO WIDGET SUPPORT ***"
    fi
    gagenv_message ""
    export GAG_WIDGETS
    #
    #
    if [ -z "$GAG_OBSERVATORY" ]; then
        GAG_OBSERVATORY="NOEMA"
    fi
    export GAG_OBSERVATORY
    gagenv_message "Default observatory used: $GAG_OBSERVATORY"
    gagenv_message ""
    #
    #
    if [ -z "$GAG_PAPER_SIZE" ]; then
        GAG_PAPER_SIZE="A4"
    fi
    export GAG_PAPER_SIZE
    gagenv_message "Default paper size: $GAG_PAPER_SIZE"
    gagenv_message ""
    #
    #######################################################################
    #
    # Create integration tree (existing directories needed by redefine-path)
    #
    GAG_INT_ROOT_DIR=$gagintdir/$GAG_EXEC_SYSTEM
    GAG_INT_INC_DIR=$GAG_INT_ROOT_DIR/include
    mkdir -p $GAG_INT_INC_DIR
    GAG_INT_LIB_DIR=$GAG_INT_ROOT_DIR/lib
    mkdir -p $GAG_INT_LIB_DIR
    GAG_INT_BIN_DIR=$GAG_INT_ROOT_DIR/bin
    mkdir -p $GAG_INT_BIN_DIR
    GAG_INT_PYTHON_DIR=$GAG_INT_ROOT_DIR/python
    mkdir -p $GAG_INT_PYTHON_DIR
    GAG_INT_TASKTEX_DIR=$gagintdir/doc/tasks
    mkdir -p $GAG_INT_TASKTEX_DIR
    if [ ! -z "$gagusedir" ]; then
        GAG_USE_ROOT_DIR=$gagusedir
        GAG_USE_INT_ROOT_DIR=$GAG_USE_ROOT_DIR/$GAG_EXEC_SYSTEM
        GAG_USE_LIB_DIR=$GAG_USE_INT_ROOT_DIR/lib
        # define GAG_LOCAL_ROOT_DIR
        GAG_LOCAL_ROOT_DIR=$GAG_ROOT_DIR
        export GAG_LOCAL_ROOT_DIR
        # redefine GAG_ROOT_DIR
        GAG_ROOT_DIR=$GAG_USE_ROOT_DIR
    else
        unset GAG_USE_ROOT_DIR
        unset GAG_USE_INT_ROOT_DIR
        unset GAG_USE_LIB_DIR
        unset GAG_LOCAL_ROOT_DIR
    fi
    #
    #######################################################################
    #
    # (Re)define paths
    #
    # First export standard paths to avoid surprises with redefine-path
    export LD_LIBRARY_PATH PATH PYTHONPATH TEXINPUTS
    #
    gagenv_message "(Re)definition of GAG_GAG and GAG_PATH"
    GAG_GAG=$HOME/.gag
    GAG_PATH=$gagintdir/etc
    if [ "${GAG_ENV_KIND}-${GAG_TARGET_KIND}" = "cygwin-mingw" ]; then
        GAG_GAG=`cygpath.exe -w $GAG_GAG`
        GAG_PATH=`cygpath.exe -w $GAG_PATH`
    fi
    #
    # LD_LIBRARY_PATH  is used at run time
    # GAG_LIB_DEP_PATH is used to produce kernel/admin/bash_profile
    # GAG_LIB_PATH     is used to find dependencies of targets by the makefile system
    # GAG_LIB_FLAGS    is used by the link commands of the makefiles
    gagenv_message "(Re)definition of GAG_LIB_FLAGS and LD_LIBRARY_PATH"
    if [ ! -z "$GAG_USE_LIB_DIR" ]; then
        DIRLIST=$GAG_LIB_DEP_PATH:$GAG_USE_LIB_DIR:$GAG_INT_LIB_DIR # Order is important here!
    else
        DIRLIST=$GAG_LIB_DEP_PATH:$GAG_INT_LIB_DIR # Order is important here!
    fi
    LD_LIBRARY_PATH=`${gagadmdir}/redefine-path -o "${ogagsrcdir}" -n "${gagsrcdir}" -k LD_LIBRARY_PATH "${DIRLIST}"`
    GAG_LIB_PATH=`${gagadmdir}/redefine-path -o "${ogagsrcdir}" -n "${gagsrcdir}" ":" "${DIRLIST}"`
    GAG_LIB_FLAGS=`echo ${GAG_LIB_PATH} | \sed -e "s&:& -L&g" -e "s&^&-L&"`
    #
    gagenv_message "(Re)definition of GAG_INC_PATH, GAG_INC_FLAGS"
    GAG_INC_PATH=`${gagadmdir}/redefine-path ":" "${GAG_INC_DEP_PATH}"`
    GAG_INC_FLAGS=`echo ${GAG_INC_PATH} | \sed -e 's&:& -I&g' -e 's&^\(.\)&-I\1&'`
    #
    gagenv_message "(Re)definition of PATH"
    DIRLIST="admin:utilities:${GAG_INT_BIN_DIR}"
    if [ "${GAG_TARGET_KIND}" = "mingw" ] || [ "${GAG_TARGET_KIND}" = "cygwin" ]; then
        # Under MS Windows (both cygwin and mingw builds), need to put dll paths in
        # $PATH so that hershey and vsop87 (mingw) or any program (cygwin) can be
        # executed at make time.
        DIRLIST="${DIRLIST}:${GAG_INT_LIB_DIR}"
    fi
    if [ ! -z "$GAG_USE_INT_ROOT_DIR" ]; then
        DIRLIST="${GAG_USE_INT_ROOT_DIR}/bin:${DIRLIST}"
    fi
    PATH=`${gagadmdir}/redefine-path -o "${ogagsrcdir}" -n "${gagsrcdir}" -k PATH "${DIRLIST}"`
    #
    gagenv_message "(Re)definition of TEXINPUTS and BSTINPUTS"
    TEXINPUTS=":"`${gagadmdir}/redefine-path -n "${gagintdir}" -k TEXINPUTS  "etc//:$GAG_INT_TASKTEX_DIR//"`
    if [ ! -z $gagusedir ]; then
        TEXINPUTS="${TEXINPUTS}:${gagusedir}/etc//"
    fi
    BSTINPUTS=":"`${gagadmdir}/redefine-path -o "${ogagsrcdir}" -n "${gagsrcdir}" -k BSTINPUTS  "utilities//"`
    #
    if [ "$DISABLE_PYTHON" = "no" -a "$PYTHON_PRESENT" = "yes" ]; then
        gagenv_message "(Re)definition of PYTHONPATH"
        PYTHONPATH=`${gagadmdir}/redefine-path -o "${ogagsrcdir}" -n "${gagsrcdir}" -k PYTHONPATH "${GAG_INT_PYTHON_DIR}"`
        # Need to add $LD_LIBRARY_PATH to $PYTHON_LIB_DEP_PATH, because:
        # - we need $GAG_LIB_PATH (added above in $LD_LIBRARY_PATH)
        PYTHON_LIB_DEP_PATH=$LD_LIBRARY_PATH
        export PYTHONPATH PYTHON_LIB_DEP_PATH
    fi
    #
    # Error and warnings summary
    gagenv_ocode=0
    gagenv_message ""
    gagenv_message "$gagenv_errors error(s) and $gagenv_warnings warning(s) detected"
    if [ $gagenv_errors -ne 0 ]; then
        gagenv_ocode=1
        gagenv_message "GILDAS will not compile"
    elif [ $gagenv_warnings -ne 0 ]; then
        gagenv_message "GILDAS will compile with some optional features disabled"
    else
        gagenv_message "You are ready to compile GILDAS"
    fi
    #
    unset  GAG_INC_DEP_PATH
    export GAG_LIB_DEP_PATH GAG_GAG GAG_PATH
    export GAG_LIB_PATH GAG_LIB_FLAGS
    export GAG_INC_PATH GAG_INC_FLAGS
    export PATH LD_LIBRARY_PATH TEXINPUTS BSTINPUTS
    #
    #######################################################################
    #
    # Cleaning
    #
    echo
    gagenv_clean
    \return $gagenv_ocode
}
#
###########################################################################
#
gagenv $@
ocode=$?
set abc; shift # This line to avoid remanence effect in a portable way
\return $ocode
#
###########################################################################
