#!/usr/bin/env bash
# configure is a part of the PYTHIA event generator.
# Copyright (C) 2025 Torbjorn Sjostrand.
# PYTHIA is licenced under the GNU GPL v2 or later, see COPYING for details.
# Please respect the MCnet Guidelines, see GUIDELINES for details.
# Author: Philip Ilten, October 2014 - February 2024.
#
# This is is the configuration script which should be run prior to building
# PYTHIA. Example usage is:
#     ./configure --with-lhapdf5
# For help please use:
#     ./configure --help
# which will print a full list of configuration options.

################################################################################
# VARIABLES: Global variables not defined via command line arguments.
#     CFG_FILE: The Makefile configuration file.
#     USAGE:    Text printed when the --help option is passed.
#     OPTIONS:  List of valid options that can be passed by the user.
################################################################################
CFG_FILE="Makefile.inc"
read -d "" USAGE << "BLOCKTEXT"
Usage: ./configure [OPTIONS]

The available options are defined below. Defaults for the options are specified
by square brackets in the option description. Arguments to the options are
indicated in caps, i.e. DIR.

Configuration options.
--help            : Print this help message (also -h, --h, and -help).
--enable-debug    : Turn on debugging and disable optimization.
--enable-optdebug : Turn on debugging but allow optimization.
--lcg=PLATFORM    : Specify the LCG platform to use when the
                    --with-PACKAGE-version option, described below,
                    is set for a given optional package
                    [x86_64-centos7-gcc11-opt]. The packages are
                    accessed via the path
                    /cvmfs/sft.cern.ch/lcg/releases/ on CVMFS.
--lcg-version=VER : Specify the LCG version to use, when --lcg is enabled 
                    [LCG_105a].

Optional external packages.
--with-PACKAGE[=DIR]       : Use the external PACKAGE from the list below with
                             its top directory optionally set by DIR. If the
                             enabled PACKAGE requires other external packages,
                             these packages will also be enabled.
--with-PACKAGE-bin=DIR     : Set the path to the PACKAGE binaries.
--with-PACKAGE-lib=DIR     : Set the path to the PACKAGE libraries.
--with-PACKAGE-include=DIR : Set the path to the PACKAGE headers.
--with-PACKAGE-config=BIN  : Set the package configuration script BIN.
--with-PACKAGE-version=VER : When using an LCG platform, set with the option
                             --lcg above, automatically set the PACKAGE path
                             for the given version VER.
  evtgen   : Particle decays with the EvtGen decay pacakge, requires HEPMC2.
  fastjet3 : Building of jets using the FastJet package, version 3.
  	     (run fastjet-config --prefix to see which path to use.)
  hepmc2   : Export PYTHIA events to the HEPMC format, version 2.
  hepmc3   : Export PYTHIA events to the HEPMC format, version 3.
  lhapdf5  : Support the use of external PDF sets via LHAPDF, version 5.
  lhapdf6  : Support the use of external PDF sets via LHAPDF, >= version 6.2.
  powheg   : Hard process production with POWHEGBOX matrix element executables.
  rivet    : Support use of RIVET through direct interface.
  yoda     : Support linking direct booking of YODA2 histograms.
  root     : Use ROOT trees and histograms with PYTHIA.
             Note: this option automatically invokes DIR/bin/root-config to set 
             the ROOT lib/ and include/ paths. To set your ROOT paths manually
             instead, use --with-root-lib=DIR and --with-root-include=DIR.
  gzip     : Enable reading of GZIPPED files using the libz library.
  python   : Interface to use PYTHIA in Python, requires "Python.h".
  mg5mes   : MadGraph matrix element plugins for parton showers.
  openmp   : Multi-threading support via OpenMP.
  mpich    : Multi-threading support via MPICH. 
  hdf5     : Support the use of HDF5.
  highfive : HighFive headers, also needed for reading HDF5 Les Houches.

Installation directories.
--prefix=DIR           : Directory to install PYTHIA [$PWD].
--prefix-COMPONENT=DIR : Set the installation directory for each PYTHIA
                         COMPONENT from the following list.
  bin     : Binaries, including the configuration script [PREFIX/bin].
  lib     : Libraries, both shared and static [PREFIX/lib].
  include : Source headers [PREFIX/include/Pythia8].
  share   : Shared data, including configuration, READMEs, documentation, and
            examples [PREFIX/share/Pythia8].

Advanced options.
--arch=ARCH          : Architecture of the system. When not set, this
                       is determined automatically. Options are LINUX for *nix
                       systems and DARWIN for OS X.
--cxx=COMPILER       : Use this C++ compiler [g++].
--cxx-common='FLAGS' : Set the common C++ flags.
--cxx-shared='FLAGS' : Set the shared C++ flags.
--cxx-soname='FLAGS' : Use these C++ flags when setting shared library names.
--lib-suffix=SUF     : Shared library name suffix: [.so] for Linux and [.dylib]
                       for OS X.
--obj-common='FLAGS' : Set the common C++ flags used for object (.o) compilation
                       only (not linking).
BLOCKTEXT
OPTIONS="-h --h -help --help --enable-debug --enable-optdebug --lcg --lcg-ver"
OPTIONS+=" --prefix --prefix-bin --prefix-lib --prefix-include --prefix-share"
for PKG in "evtgen" "fastjet3" "hepmc2" "hepmc3" "lhapdf5" "lhapdf6" "powheg"\
    "rivet" "yoda" "root" "gzip" "python" "mg5mes" "openmp" "mpich" "hdf5"\
    "highfive"; do
    OPTIONS+=" --with-$PKG --with-$PKG-bin --with-$PKG-lib --with-$PKG-include"
    OPTIONS+="  --with-$PKG-config --with-$PKG-version"; done
OPTIONS+=" --arch --cxx --cxx-common --cxx-shared --cxx-soname --lib-suffix"
OPTIONS+=" --obj-common"

################################################################################
# FUNCTION: Configure a package.
#     configure_package <package> <LCG path> <LCG version> <config>
#                       <relative bin path> <relative include path>
#                       <relative library path> <bin deps> <header deps>
#                       <lib deps> <package deps> <global compiler flags>
#
# The following array structure stores the package configuration to the global
# variable <upper-case package name>_CFG.
#     0: Use the package.       5:  Header dependencies.
#     1: Binary directory.	6:  Library dependencies.
#     2: Include directory.     7:  Package dependencies.
#     3: Library directory.     8:  Dependency messages (empty if success).
#     4: Binary dependencies.   9:  Global compiler flags.
#                               10: Package configure script.
# Note that the global variable CXX must be defined prior to calling this
# function.
################################################################################
function configure_package() {

    # Check global package variable and set the local package variables.
    local PKG=$(echo $1 | awk '{print toupper($0)}')
    eval local PKG_CFG=\${${PKG}_CFG[0]}
    if [ "${PKG_CFG[0]}" != true ]; then PKG_CFG[0]=false; fi
    PKG_CFG[4]=$8; PKG_CFG[5]=$9; PKG_CFG[6]=${10}; PKG_CFG[7]=${11}
    PKG_CFG[8]=""; PKG_CFG[9]="";
    local LCG_DIR=$2; local LCG_VER=$3; local PKG_EXE=$4; local PKG_BIN=$5;
    local PKG_INC=$6; local PKG_LIB=$7; local PKG_FLG=${12}
    local WARN=$(warn "Disabling $PKG")" -"
    
    # Initialise binary, include, and library paths to specified user values.
    eval PKG_CFG[1]=\$${PKG}_BIN; eval PKG_CFG[2]=\$${PKG}_INCLUDE
    eval PKG_CFG[3]=\$${PKG}_LIB; eval PKG_CFG[10]=\$${PKG}_CONFIG
    eval local PKG_DIR=\$$PKG;    eval local PKG_SET=\$${PKG}_SET
    eval local PKG_VER=\$${PKG}_VERSION
    if [ "$PKG_SET" = true ] || [ -n "${PKG_CFG[1]}" ] || \
	[ -n "${PKG_CFG[2]}" ] || [ -n "${PKG_CFG[3]}" ] || \
	[ -n "${PKG_CFG[10]}" ]; then PKG_CFG[0]=true; fi
    
    # Set package path for LCG if available and requested.
    if [ "$LCG_SET" = true ] && [ "$PKG_SET" = true ] && \
        [ -z "$PKG_VER" ]; then PKG_VER=$LCG_VER; fi
    if [ -n "${PKG_CFG[2]}" ] || [ -n "${PKG_CFG[3]}" ] || \
	[ -n "${PKG_CFG[10]}" ]; then PKG_VER=""; fi
    if [ -n "$PKG_VER" ] && [ -n "$LCG_DIR" ]; then
        PKG_CFG[0]=true
	if [ ! -d $LCG_DIR/$PKG_VER ]; then
	    echo "$WARN version $PKG_VER not available via LCG."
	elif [ ! -d $LCG_DIR/$PKG_VER/$LCG ]; then
	    echo "$WARN platform $LCG not available via LCG."
	elif [ -n "$PKG_EXE" ] && [ -d $LCG_DIR/$PKG_VER/$LCG/bin ]; then
            PKG_EXE=$LCG_DIR/$PKG_VER/$LCG/bin/$PKG_EXE
            PKG_CFG[1]=$LCG_DIR/$PKG_VER/$LCG/bin
        else
	    PKG_DIR=$LCG_DIR/$PKG_VER/$LCG;
	fi
    elif [ -n "$PKG_VER" ]; then
	echo "$WARN package not available via LCG."
    fi

    # Set binary, include, and library paths from specified package path.
    if [ -n "${PKG_CFG[10]}" ]; then PKG_EXE=${PKG_CFG[10]};
    else PKG_CFG[10]=$PKG_EXE; fi
    if [ -z "${PKG_CFG[1]}" ];  then
	if [ -n "$PKG_DIR" ]; then
	    if [ -n "$PKG_BIN" ] && [ -d "$PKG_DIR/$PKG_BIN" ]; then
                PKG_CFG[1]=$PKG_DIR/$PKG_BIN
	    elif [ -d "$PKG_DIR/bin" ]; then PKG_CFG[1]=$PKG_DIR/bin
	    else PKG_CFG[1]=$PKG_DIR; fi
	    PKG_CFG[1]=$(cd ${PKG_CFG[1]} 2> /dev/null && pwd -P)
	elif $PKG_EXE $PKG_BIN &> /dev/null && [ -z "$PKG_DIR" ] &&
	   [ -n "$PKG_BIN" ]; then PKG_CFG[1]=$($PKG_EXE $PKG_BIN 2> /dev/null)
           if [ -z "${PKG_CFG[1]}" ]; then local BIN=$(command -v $PKG_EXE)
               PKG_CFG[1]=${BIN%/*}; fi
	fi
    fi
    if [ -z "${PKG_CFG[2]}" ]; then
	if [ -n "$PKG_DIR" ]; then
	    if [ -n "$PKG_INC" ] && [ -d "$PKG_DIR/$PKG_INC" ]; then
                PKG_CFG[2]=$PKG_DIR/$PKG_INC
	    elif [ -d "$PKG_DIR/include" ]; then PKG_CFG[2]=$PKG_DIR/include
	    else PKG_CFG[2]=$PKG_DIR; fi
	elif $PKG_EXE $PKG_INC &> /dev/null && [ -z "$PKG_DIR" ] &&
	   [ -n "$PKG_INC" ]; then PKG_CFG[2]=$($PKG_EXE $PKG_INC 2> /dev/null)
	fi
    fi
    if [ -z "${PKG_CFG[3]}" ]; then
	if [ -n "$PKG_DIR" ]; then
	    if [ -n "$PKG_LIB" ] && [ -d "$PKG_DIR/$PKG_LIB" ]; then
                PKG_CFG[3]=$PKG_DIR/$PKG_LIB
	    elif [ -d "$PKG_DIR/lib" ]; then PKG_CFG[3]=$PKG_DIR/lib
	    else PKG_CFG[3]=$PKG_DIR; fi
	elif $PKG_EXE $PKG_LIB &> /dev/null && [ -z "$PKG_DIR" ] &&
	   [ -n "$PKG_LIB" ]; then PKG_CFG[3]=$($PKG_EXE $PKG_LIB 2> /dev/null)
	fi
    fi

    # Format include and library paths as compiler flags.
    PKG_INC=(); PKG_LIB=()
    for INC in ${PKG_CFG[2]}; do
	INC=${INC#-I}
	if [ "${INC:0:1}" = "-" ]; then continue; fi
	PKG_INC+=("-I$(cd $INC 2> /dev/null && pwd -P)"); done
    for LIB in ${PKG_CFG[3]}; do
	LIB=${LIB#-L}
	if [ "${LIB:0:1}" = "-" ]; then continue; fi
	PKG_LIB+=("-L$(cd $LIB 2> /dev/null && pwd -P)")
	PKG_LIB+=("-Wl,-rpath,$(cd $LIB 2> /dev/null && pwd -P)")
    done
    PKG_CFG[2]="${PKG_INC[@]}"; PKG_CFG[3]="${PKG_LIB[@]}"
    
    # Check dependencies and store warnings.
    IFS=";"
    for BIN in ${PKG_CFG[4]}; do
	if [ -n "${PKG_CFG[1]}" ]; then
	    if ! type "${PKG_CFG[1]}/$BIN" &> /dev/null; then
		PKG_CFG[8]="${PKG_CFG[8]};$WARN binary $BIN missing."
	    fi
	elif ! type "$BIN" &> /dev/null; then
	    PKG_CFG[8]="${PKG_CFG[8]};$WARN binary $BIN missing."
	fi
    done
    for INC in ${PKG_CFG[5]}; do
	local TEST=$(echo "#include \"$INC\"" | $CXX -o /dev/null -c -xc - \
	    ${PKG_INC[@]} 2>&1 | grep -e "$INC: No such file" \
	    -e "'$INC' file not found")
	if [ -n "$TEST" ]; then
	    PKG_CFG[8]="${PKG_CFG[8]};$WARN header $INC missing.";
	fi
    done
    for LIB in ${PKG_CFG[6]}; do
	local TEST=$(echo "int main(){}" | $CXX -o /dev/null -xc - \
	    ${PKG_LIB[@]} -l$LIB 2>&1 | grep "\-l$LIB")
	if [ -n "$TEST" ]; then
	    PKG_CFG[8]="${PKG_CFG[8]};$WARN library $LIB missing."
	fi
    done
    IFS=" "

    # If global flags are defined, append include flags and libraries.
    IFS=";"
    for LIB in ${PKG_CFG[6]}; do PKG_CFG[3]+=" -l$LIB"; done
    IFS=" "
    if [ -n "$PKG_FLG" ]; then
	PKG_CFG[9]="$PKG_FLG ${PKG_CFG[2]}";
    fi
    
    # Export local package to global variable and update global package list.
    for IDX in ${!PKG_CFG[@]}; do
	local VAL="${PKG_CFG[$IDX]}"
	VAL="${VAL#"${VAL%%[![:space:]]*}"}"
	VAL="${VAL%"${VAL##*[![:space:]]}"}"  
	eval ${PKG}_CFG[$IDX]=\"$VAL\"
    done
    PKG_LIST+=($PKG)

    # Flag inter-package dependencies (if this package available).
    if [ "${PKG_CFG[0]}" = true ] && [ -z "${PKG_CFG[8]}" ]; then
	IFS=";"
	for PKG in ${PKG_CFG[7]}; do eval ${PKG}_CFG[0]=true; done;
	IFS=" "
    fi
}

################################################################################
# FUNCTION: Print formatted information to screen.
#     bold/error/warn <message>
# Errors are reported as white-on-red and warnings as black on yellow.
################################################################################
function bold() {
    if [ -z "$TERM" ] || ! type "tput" &> /dev/null; then echo -e $@
    else echo -e $(tput bold)$@$(tput sgr0); fi
}

function warn() {
    if [ -z "$TERM" ] || ! type "tput" &> /dev/null; then echo -e $@
    else echo -e $(tput setaf 0)$(tput setab 3)WARNING: $@$(tput sgr0); fi
}

function error() {
    if [ -z "$TERM" ] || ! type "tput" &> /dev/null; then echo -e $@
    else echo -e $(tput setaf 7)$(tput setab 1)ERROR: $@$(tput sgr0); fi
}

################################################################################
# MAIN: The main execution of the configuration script.
################################################################################

# Check if help requested.
bold "Running PYTHIA configuration script. Now is `date`"
for VAR in "$@"; do
    if [ "$VAR" = "-h" ] || [ "$VAR" = "--h" ] || [ "$VAR" = "-help" ] \
	   || [ "$VAR" = "--help" ]; then
	echo -e "$USAGE"
	exit
    fi
done

# Parse the user arguments and evaluate each as a global variable.
echo "# PYTHIA configuration file." > $CFG_FILE
echo "# Generated on" `date` "with the following command:" >> $CFG_FILE
USER_CFG=""
for VAR in "$@"; do
    if [[ $OPTIONS =~ (^| )${VAR%%=*}($| ) ]]; then USER_CFG+=" $VAR"
    else
	warn "Ignoring invalid option \"${VAR%=*}\".";
	continue; fi
    VAR=${VAR#--with-}; VAR=${VAR#--};
    KEY=${VAR%%=*}; VAL=${VAR#$KEY}; VAL=${VAL#*=}; KEY=${KEY//"-"/"_"};
    KEY=$(echo $KEY | awk '{print toupper($0)}');  VAL=$(eval echo $VAL)
    eval $KEY=\"$VAL\"; eval ${KEY}_SET=true
done
echo "# ./configure$USER_CFG" >> $CFG_FILE

# Set the compilation flags and options (order matters).
[ "$ENABLE_DEBUG_SET"    = true ] && ENABLE_DEBUG="-g "   || ENABLE_DEBUG="-O2 "
[ "$ENABLE_OPTDEBUG_SET" = true ] && ENABLE_DEBUG="-g -O "
if [ -z "$ARCH" ]; then ARCH=$(uname | grep -i -o -e Linux -e Darwin); fi
ARCH=$(echo $ARCH | awk '{print toupper($0)}')
if [ "$ARCH" != "LINUX" ] && [ "$ARCH" != "DARWIN" ]; then
    warn "Unknown architecture $ARCH, set as LINUX."; ARCH="LINUX"; fi
if [ -z "$CXX" ]; then warn "CXX not set, using g++."; CXX="g++"; fi
if [ -z "$CXX_COMMON" ]; then
    CXX_COMMON="${ENABLE_DEBUG}-std=c++11 -pedantic -W -Wall -Wshadow -fPIC"; fi
if [ -z "$CXX_SHARED" ]; then
    if [ "$ARCH" = "LINUX" ];  then CXX_SHARED="-shared"; fi
    if [ "$ARCH" = "DARWIN" ]; then CXX_SHARED="-dynamiclib"; fi; fi
if [ -z "$CXX_SONAME" ]; then
    if [ "$ARCH" = "LINUX" ];  then CXX_SONAME="-Wl,-soname,"; fi
    if [ "$ARCH" = "DARWIN" ]; then CXX_SONAME="-Wl,-dylib_install_name,@rpath/"
    fi; fi
if [ -z "$LIB_SUFFIX" ]; then
    if [ "$ARCH" = "LINUX" ];  then LIB_SUFFIX=".so"; fi
    if [ "$ARCH" = "DARWIN" ]; then LIB_SUFFIX=".dylib"; fi; fi

# Handle new versus old dynamic tags (prefer old transitive behaviour).
CXX_DTAGS=$(echo "int main(){}" | $CXX -Wl,--disable-new-dtags -o \
    /dev/null -xc - 2>&1)
if [ -z "$CXX_DTAGS" ]; then CXX_DTAGS="-Wl,--disable-new-dtags";
else CXX_DTAGS=""; fi

# Configure the installation directories (order matters).
if [ "$PREFIX_SET" != true ]; then PREFIX=$PWD; fi
if [ -z "$PREFIX_BIN" ];      then PREFIX_BIN=$PREFIX/bin; fi
if [ -z "$PREFIX_INCLUDE" ];  then PREFIX_INCLUDE=$PREFIX/include; fi
if [ -z "$PREFIX_LIB" ];      then PREFIX_LIB=$PREFIX/lib; fi
if [ -z "$PREFIX_SHARE" ];    then PREFIX_SHARE=$PREFIX/share/Pythia8; fi

# Configure the LCG setup.
if [ -z "$LCG" ]; then LCG="x86_64-centos7-gcc11-opt"; fi
if [ -z "$LCG_VERSION" ]; then LCG_VERSION="LCG_105a"; fi
LCG_PATH="/cvmfs/sft.cern.ch/lcg/releases/$LCG_VERSION"

# Configure the packages (order does not matter).
configure_package "EVTGEN" "$LCG_PATH/MCGenerators/evtgen" "2.2.1" ""\
    "" "" "lib64" "" "EvtGen/EvtGen.hh" "EvtGen;EvtGenExternal" "HEPMC3"
configure_package "FASTJET3" "$LCG_PATH/fastjet" "3.4.1"\
     "fastjet-config" "bin" "--cxxflags" "--libs"\
     "" "fastjet/config.h" "fastjet" ""
configure_package "HEPMC2" "" "" "" "" "" "" "" "HepMC/GenEvent.h" "HepMC" ""
configure_package "HEPMC3" "$LCG_PATH/hepmc3" "3.2.7" "HepMC3-config"\
    "" "--includedir" "--libdir" "" "HepMC3/GenEvent.h" "HepMC3" ""
configure_package "LHAPDF5" "" ""\
    "lhapdf-config" "" "--incdir" "--libdir" "" "" "LHAPDF" ""
configure_package "LHAPDF6" "$LCG_PATH/MCGenerators/lhapdf" "6.5.3"\
    "lhapdf-config" "" "--incdir" "--libdir" "" "LHAPDF/LHAPDF.h" "LHAPDF" ""
configure_package "POWHEG"\
    "$LCG_PATH/MCGenerators/powheg-box-v2" "r3744.lhcb3.rdynamic"\
    "" "" "" "" "" "" "hvq" ""
configure_package "RIVET" "$LCG_PATH/MCGenerators/rivet" "3.1.9"\
    "rivet-config" "bin" "--includedir" "--libdir" "rivet-config"\
    "Rivet/Rivet.hh" "Rivet" ""
configure_package "YODA" "$LCG_PATH/MCGenerators/yoda" "2.0.0"\
    "yoda-config" "bin" "--includedir" "--libdir" "yoda-config"\
    "YODA/YODA.h" "YODA" ""
configure_package "ROOT" "$LCG_PATH/ROOT" "6.30.04" "root-config"\
    "--bindir" "--incdir" "--libdir" "rootcint;root-config" "TROOT.h" "Core" ""
configure_package "GZIP" "" "" "" "" "" "" "" "zlib.h" "z" "" "-DGZIP"
configure_package "PYTHON" "$LCG_PATH/Python" "3.9.12"\
    "python-config" "" "--includes" "" "" "Python.h" "" ""
configure_package "MG5MES" "" "" "" "echo plugins/mg5mes" "" "" "" ""\
    "" ""
configure_package "OPENMP" "" "" "" "" "" "" "" "" "gomp" ""\
    "-fopenmp -DOPENMP"
configure_package "MPICH" "" "" "" "" "" "" "mpic++" "mpi.h" "mpi" ""
configure_package "HDF5" "$LCG_PATH/hdf5" "1.12.2" "" "" "" "" "" "hdf5.h"\
    "hdf5" ""
configure_package "HIGHFIVE" "$LCG_PATH/highfive" "2.0" "" "" "" "" ""\
    "highfive/H5File.hpp" "" ""

# Check package dependencies (order does not matter).
for IDX in ${!PKG_LIST[@]}; do
    PKG=${PKG_LIST[$IDX]}
    eval PKG_USE=\${${PKG}_CFG[0]}; eval PKG_WRN=\${${PKG}_CFG[8]}
    if [ "$PKG_USE" = true ] && [ -n "$PKG_WRN" ]; then
	eval ${PKG}_CFG[0]=false; IFS=";"
	for WRN in $PKG_WRN; do if [ -n "$WRN" ]; then echo $WRN; fi; done
	IFS=" "
    fi
done

# Check package inter-dependencies (order does not matter).
for IDX in ${!PKG_LIST[@]}; do
    PKG=${PKG_LIST[$IDX]}
    eval PKG_USE=\${${PKG}_CFG[0]}; eval PKG_DPS=\${${PKG}_CFG[7]}
    if [ "$PKG_USE" = true ]; then
	IFS=";"
	for DEP in $PKG_DPS; do
	    eval DEP_USE=\${${DEP}_CFG[0]}; eval DEP_INC=\${${DEP}_CFG[2]};
	    eval DEP_LIB=\${${DEP}_CFG[3]};
	    if [ -n "$DEP_INC" ]; then eval ${PKG}_CFG[2]+=\" $DEP_INC\"; fi
	    if [ -n "$DEP_LIB" ]; then eval ${PKG}_CFG[3]+=\" $DEP_LIB\"; fi
	    if [ "$DEP_USE" != true ]; then
		eval ${PKG}_CFG[0]=false
		echo $(warn "Disabling $PKG") " - requires $DEP."
	    fi
	done
	IFS=" "
    fi
    eval PKG_USE=\${${PKG}_CFG[0]}; eval PKG_FLG=\${${PKG}_CFG[9]}
    if [ "$PKG_USE" = true ] && [ -n "$PKG_FLG" ]; then
	CXX_COMMON+=" $PKG_FLG"
    fi
done

# Append the global flags.
for IDX in ${!PKG_LIST[@]}; do
    PKG=${PKG_LIST[$IDX]}
    eval PKG_USE=\${${PKG}_CFG[0]}
done
    
# Write the configuration to screen and file, update the pythia8-config script.
mkdir -p bin;
sed 's|^CFG_FILE=.*|CFG_FILE='"$PREFIX_SHARE"'/examples/Makefile.inc|' \
    pythia8-config.inc > bin/pythia8-config
chmod a+x bin/pythia8-config
echo "---------------------------------------------------------------------"
echo "|                    PYTHIA Configuration Summary                   |"
echo "---------------------------------------------------------------------"
echo "  Architecture                = "$ARCH 
echo "  C++ compiler     CXX        = "$CXX
echo "  C++ dynamic tags CXX_DTAGS  = "$CXX_DTAGS
echo "  C++ flags        CXX_COMMON = "$CXX_COMMON
echo "  C++ shared flag  CXX_SHARED = "$CXX_SHARED
echo -n "  Further options             = "
if [ "$ENABLE_DEBUG_SET" = true ];    then echo -n "--enable-debug ";    fi
if [ "$ENABLE_OPTDEBUG_SET" = true ]; then echo -n "--enable-optdebug "; fi
if [ "$LCG_SET" = true ];             then echo -n "--lcg=$LCG";         fi
if [ "$OBJ_COMMON" != "" ];     then echo -n "OBJ_COMMON = $OBJ_COMMON"; fi
echo ""
cat >> $CFG_FILE << BLOCKTEXT

# Install directory prefixes.
PREFIX_BIN=$PREFIX_BIN
PREFIX_INCLUDE=$PREFIX_INCLUDE
PREFIX_LIB=$PREFIX_LIB
PREFIX_SHARE=$PREFIX_SHARE

# Compilation flags (see ./configure --help for further documentation).
CXX=$CXX
CXX_DTAGS=$CXX_DTAGS
CXX_COMMON=$CXX_COMMON
CXX_SHARED=$CXX_SHARED
CXX_SONAME=$CXX_SONAME
LIB_SUFFIX=$LIB_SUFFIX
OBJ_COMMON=$OBJ_COMMON
BLOCKTEXT
echo -e "\nThe following optional external packages will be used:"
for IDX in ${!PKG_LIST[@]}; do
    PKG=${PKG_LIST[$IDX]}
    eval PKG_USE=\${${PKG}_CFG[0]}
    if [ "$PKG_USE" = true ]; then
	eval PKG_BIN=\${${PKG}_CFG[1]}; eval PKG_INC=\${${PKG}_CFG[2]}
	eval PKG_LIB=\${${PKG}_CFG[3]}; eval PKG_CONFIG=\${${PKG}_CFG[10]}
	PKG_DIR=$PKG_INC
	if [ -n "$PKG_BIN" ] && [ "${PKG_BIN: -1}" != "/" ]; then
	    PKG_BIN="$PKG_BIN/"; fi
	if [ -z "$PKG_DIR" ]; then PKG_DIR=$PKG_BIN; fi
	if [ -z "$PKG_DIR" ]; then PKG_DIR="system"; fi
	echo $(bold "  + $PKG")" ($PKG_DIR)"
    else
        PKG_BIN=""; PKG_INC=""; PKG_LIB=""; PKG_CONFIG=""
    fi
    cat >> $CFG_FILE << BLOCKTEXT

${PKG}_USE=$PKG_USE
${PKG}_CONFIG=$PKG_CONFIG
${PKG}_BIN=$PKG_BIN
${PKG}_INCLUDE=$PKG_INC
${PKG}_LIB=$PKG_LIB
BLOCKTEXT
done
