#!/bin/bash

#-----------------------------------------------------------------------
#        THIS BASH-SHELL SCRIPT SERVES TO COMPILE THE MCTDH PROGRAM
#-----------------------------------------------------------------------
#
#               Written by Michael Beck (10/96)
#               Revised and extended by GW and HDM (12/99)
#
########################################################################
#-----------------------------------------------------------------------
# HERE THE USER MAY SET SOME VARIABLES.
#-----------------------------------------------------------------------
# If you want to include a potential energy surface automatically,
# set surflist appropriately, e.g.:  surflist='lsth nocl1sch'
# with "surflist=", or "unset surflist", no PES will be included.

surflist='lsth' # This choice is useful, because lsth is used in both
               # the tutorial and and the elk_test.
               # Modify this line according to your demands.
               # E.g. to: surflist='lsth h4bmkp h4srf bkmp2'

# Set the default method for linking with external BLAS/LAPACK libs.
# This choice can be overriden with the -x switch.
# Possible choices:
# extlib=0    # don't use external libs, link with self-compiled reference code
# extlib=1    # use external BLAS, but LAPACK from reference code
# extlib=2    # use both external BLAS and LAPACK
extlib=0

# Permissions for the binaries to be created.
# Reasonable values are "771" or "711" or "710" or "700".
# 771 : user and group may read, write and execute; others may execute.
# 751 : user may read, write, execute, group read excecute; others execute.
# 700 : user may read, write, execute; group and others have no access.

permb=751

# Permissions for archives and object files.
# Reasonable values are "600" or "640" or "660".
# 664 : user and group may read, write; others may read.
# 640 : user may read, write; group may read; others have no access.
# 600 : user may read, write; group and others have no access.

permo=640

# Version number such that <progname> becomes '<progname><ver>':
ver=84

# By default, compile will overwrite the previous binaries.  Depending on
# the system, this can cause problems if there are still computations
# running that use the old binary -- the prime example is if the binaries
# are located on an NFS volume.  If the following is set to 1, previous
# binaries will not be overwritten; instead the actual binary name will
# include a unique identifier, and a symlink is maintained which will
# point to the most recent binary.
versioned=0

########################################################################

minus40='----------------------------------------'

#-----------------------------------------------------------------------
# FUNCTION  helpf. Print help information.
#-----------------------------------------------------------------------
helpf() {
# determine which awk is to be used.
    if [ -z "$awk1" ] ; then
        exist=`which gawk | cut -d' ' -f1 | fgrep '/bin'`
        if [ -n "$exist" ] ; then
            awk1=gawk
        fi
    fi
    if [ -z "$awk1" ] ; then
        exist=`which nawk | cut -d' ' -f1 | fgrep '/bin'`
        if [ -n "$exist" ] ; then
            awk1=nawk
        fi
    fi
    if [ -z "$awk1" ] ; then
        exist=`which awk | cut -d' ' -f1 | fgrep '/bin'`
        if [ -n "$exist" ] ; then
            awk1=awk
        fi
    fi

    objpath=$MCTDH_DIR/object/$MCTDH_PLATFORM/$MCTDH_COMPILER
    echo "$minus40$minus40"
    cat <<EOF
Purpose: Compiles the MCTDH program package.'
Usage:   compile [-a|-A] [-c compiler] [-d|-D] [-h -l -m -u -o]
                 [-n|-N name] [-p platform] [-P] [-q|-Q] [-s script]
                 [-i srf] [-j n] [-x blas|lapack|none] [-t path]
                 [-r|-z|-Z] prog
   -a:   Force compilation of all files.
   -A:   Force compilation of all files including the lib.
         (Different from -a only for prog = executable program(s).)
   -c compiler: Use compiler environment "compiler" rather than the default.
   -C:   remove unreferenced (old) versioned executables. See compile script line 50.
   -d:   Compile programs with debug options and link to optimized library.
   -D:   Compile programs with debug options and link to debug library.
   -h:   Print this help text.'
   -i srf: Include the potential energy surface "srf" when linking.
         e.g.: compile -i 'lsth nocl hoo' mctdh
         The names, when unique, will automatically be completed.
         "-i all" will link all available surfaces.'
   -j n: Run n jobs in parallel (make -j option). Useful on
         multi-processor machines.
   -l:   local. Compile files of that MCTDH-directory which is or
         lies above PWD. Do not compile the files of $MCTDH_DIR.
   -m:   Compilation for MPI runs.
   -u:   The NUMA library is used to prevent thread migration.
   -n:   Add name to archive, object, and executable files
         (e.g. mctdh<version>_<name>).
   -N:   Same as -n, only that <name> is also added to the libraries.
   -o:   Compilation info screen by screen (piped to less).
   -p platform: Store executable in directory "bin/binary/<platform>",
         rather than in "bin/binary/$MCTDH_PLATFORM".
   -P:   Enable shared-memory parallelization via OpenMP directives.
   -q:   Let make perform quietly.
   -Q:   Let make perform very quietly. ( > /dev/null)
   -r:   Remove object files or archives from:
         $objpath
         (you will be prompted for what files to remove).
   -s script: Use the script "script" rather than the default "compile.cnf".
   -t path: put CompDir in path instead of $MCTDH_DIR (useful if
         $MCTDH_DIR is on slow NFS)
   -x blas|lapack|none: Link with an external library.
         Without this option, or with "-x none", MCTDH will be linked with
         BLAS/LAPACK routines from NETLIBs reference implementation.
         With "-x blas", MCTDH will be linked with an external BLAS and the
         reference LAPACK.
         With "-x lapack", MCTDH will be linked with both an external BLAS and
         an external LAPACK.
         The location of the external libraries is specified in "compile.cnf"
         via the variables EXTERNAL_BLAS and EXTERNAL_LAPACK.
   -z:   Clean archives. (Similar to -a, but do not re-install the archive).
   -Z:   Clean archives including the library. (Similar to -A,
         but do not re-install the removed archive(s)).

 The argument prog specifies the program to be compiled.
 It may take the value of an MCTDH-executable, e.g:
 "mctdh", "potfit", "autospec", "overlap", "flux", "showd1d", ...
 which will then be compiled and linked. Or it may take the values:
 "all", "analyse", which will compile and link all the MCTDH package
 or all analyse programs.'
 The argument "lib" will compile the library and the arguments
 "libnum" or "gendvr" or "opfuncs" or ... will install these archives.

 To (re)install  the archives "oct, "mctdh" or "analyse" use the command
 "Aoct", "Amctdh" or "Aanalyse" (as "oct", "mctdh" and "analyse" will
 link programs).

 The argument "config" will not compile anything but displays
 the compile configuration, i.e. compiler options,
 environment variables and paths.
 The argument may be abreviated to the smallest unique part.
 E.g.: "compile mc" is equivalent to "compile mctdh".

 Possible arguments are:
EOF

    echo $exclist | $awk1 \
'{printf("%13s%13s%13s%13s%13s%13s\n",$1,$2,$3,$4,$5,$6)}
{printf("%13s%13s%13s%13s%13s%13s\n",$7,$8,$9,$10,$11,$12)}
{printf("%13s%13s%13s%13s%13s%13s\n",$13,$14,$15,$16,$17,$18)}
{printf("%13s%13s%13s%13s%13s%13s\n",$19,$20,$21,$22,$23,$24)}
{printf("%13s%13s%13s%13s%13s%13s\n",$25,$26,$27,$28,$29,$30)}
{printf("%13s%13s%13s%13s%13s%13s\n",$31,$32,$33,$34,$35,$36)}
{printf("%13s%13s%13s%13s%13s%13s\n",$37,$38,$39,$40,$42,$42)}
{printf("%13s%13s%13s%13s%13s%13s\n",$43,$44,$45,$46,$47,$48)}
{printf("%13s%13s%13s%13s%13s%13s\n",$49,$50,$51,$52,$53,$54)}
{printf("%13s%13s%13s%13s%13s%13s\n",$55,$56,$57,$58,$59,$60)}
{printf("%13s%13s%13s%13s%13s%13s\n",$61,$62,$63,$64,$65,$66)}
{printf("%13s%13s%13s%13s%13s%13s\n",$67,$68,$69,$70,$71,$72)}
{printf("%13s%13s%13s%13s%13s%13s\n",$73,$74,$75,$76,$77,$78)}
{printf("%13s%13s%13s%13s%13s%13s\n",$79,$80,$81,$82,$83,$84)}'
    echo $arclist | $awk1 \
   '{printf("%13s%13s%13s%13s%13s%13s\n",$1,$2,$3,$4,$5,$6)}
    {printf("%13s%13s%13s            \n",$7,$8,$9)}
    {printf("%13s%13s%13s%13s%13s%13s\n",$10,$11,$12,$13,$14,$15)}'

    echo ' '
    echo 'These are the possible arguments for the -i option (include pes):'
    cd $MCTDH_DIR/source/surfaces
    ls *.[Ff] | fgrep -v DEF_ | fgrep -v DUM | cut -d '.' -f1 | tr '\n' ' '
    echo ' '
    echo "$minus40$minus40"
    echo ' '
    exit
}

#-----------------------------------------------------------------------
# FUNCTION configf. Print compile configuration.
#-----------------------------------------------------------------------
configf() {
   echo '-------------------  compile config ' \
        '------------------------------------------'
   echo
   echo 'Operating system     : '$MCTDH_OP_SYSTEM
   echo 'Platform             : '$MCTDH_PLATFORM
   echo 'MCTDH_COMPILER       : '$MCTDH_COMPILER
   case $MCTDH_COMPILER in
     g77-2)
       echo 'Compilers (F77 / C)  : '$FC' (Version: '$MCTDH_G77_2_VERSION')    '$CC
       ;;
     g77*)
       echo 'Compilers (F77 / C)  : '$FC' (Version: '$MCTDH_G77_VERSION')    '$CC
       ;;
     gfortran*)
       echo 'Compilers (F77 / C)  : '$FC' (Version: '$MCTDH_GFORTRAN_VERSION')    '$CC
       ;;
     *)
       echo 'Compilers (F77 / C)  : '$FC'    '$CC
       ;;
   esac
   echo 'F77 flags (optimise) : '$MCTDH_FFLAGS_OPT
   echo 'F77 flags (debug)    : '$MCTDH_FFLAGS_DEB
   echo 'F77 flags (0)        : '$MCTDH_FFLAGS_0
   echo 'C flags              : '$MCTDH_CFLAGS
   echo 'Include              : '$MCTDH_FFLAGS_INC
   echo 'Modules              : '$MCTDH_FFLAGS_MOD
   echo 'OpenMP               : '$MCTDH_OMP_FLAGS
   echo 'Add Lib              : '$MCTDH_ADD_LIBS
   echo 'Flush extension      : '$MCTDH_FLUSH_EXT
   echo 'Archive command      : '$MCTDH_ARFLAGS
   echo 'Make command         : '$MCTDH_MAKE_CMD
   echo 'Fortran Symbols      : '$MCTDH_F2C_STYLE
   echo 'Pthread Symbols      : '$MCTDH_PTHREAD_STYLE
   if [ $extlib -ge 1 ] ; then
      echo 'External_BLAS        : '$EXTERNAL_BLAS
   fi
   if [ $extlib -ge 2 ] ; then
      echo 'External_LAPACK      : '$EXTERNAL_LAPACK
   fi
   echo 'Source path          : '$srcpath
   echo 'Object path          : '$objpath
   echo 'Binary path          : '$progpath
   if [ -n "$cmp_scrpt" ]; then
      echo "Using compile script : $comp_script "
   fi
   echo 'Permissions (bin/obj): '$permb'  '$permo
   echo 'Version              : '$version
   echo ' '

   echo ' '
   echo '-------  '$(date +'%a, %d %b %Y, %T')'   ---------------------------------------'
   echo ' '
   exit
}


#-----------------------------------------------------------------------
# Function runmake, wrapping the call to make, for safe parallel builds.
# ipcmd is used to serialize the calls to ar, which would otherwise lead
# to inconsistent archives.
#-----------------------------------------------------------------------
runmake () {
   if [ -n "$jobs" ]; then
      export IPCMD_SEMID=$(ipcmd semget)
      ipcmd semctl setall 1
      export AR='ipcmd semop -u -1 : ar'
      $make "$@"
      ipcrm -s $IPCMD_SEMID
   else
      export AR=ar
      $make "$@"
   fi
}


#-----------------------------------------------------------------------
# Function chkcmd, which checks whether a command is available.
#-----------------------------------------------------------------------
chkcmd () {
   echo -n "   $1... "
   which "$1" >/dev/null 2>&1
   local ret=$?
   if [ $ret -eq 0 ]; then
      echo "ok."
   else
      echo "not found."
   fi
   return $ret
}


### --------------- Actual shell script starts here -----------------------###

# set locale, so that date etc will be in uniform format.
export LC_ALL=C

DATE=$(date +'%a, %d %b %Y, %T')
pwd=`pwd`

# set version identifier
if [ $versioned -gt 0 ]; then
   verstr=$(date '+%Y%m%d%H%M%S')
fi

#-----------------------------------------------------------------------------
# SETTING UP ENVIRONMENT VARIABLE MCTDH_DIR.
# The script thus may be called form any directory.
# Option -l, find the current (local) MCTDH directory.
#-----------------------------------------------------------------------------
if [ "${*##-l*}" != "$*" ] ; then
   path=${0%/*} ; path=${path%/bin}
   if [ "$path" = "$MCTDH_DIR" ] ; then unset path ; fi
#  If compile is called by its absolute path, cd to this path.
   if [ -n "$path" ] && [ -z "${path##/*}" ] ; then cd $path ; fi
   unset MCTDH_DIR
   mdir=`pwd`
#  Remove that part from pwd, that is below the MCTDH directory.
   while [ -z "$MCTDH_DIR" ] ; do
      ls | tr '\n' ' ' | fgrep -w bin | fgrep -w elk_inputs | \
          fgrep -w inputs | fgrep -w source | fgrep -w install | \
          fgrep -w doc | fgrep -w operators | fgrep -w pinputs > /dev/null
      if [ $? = 0 ] ; then
         MCTDH_DIR=$mdir
      else
         cd ../
         mdir=`pwd`
         length=`echo "$mdir" | wc -c`
         if [ $length -le 3 ] ; then
            echo "This does not seem to be a MCTDH directory!"
            exit 1
         fi
      fi
   done
   export MCTDH_DIR
fi

#-----------------------------------------------------------------------------
# SEARCH FOR AND REMOVE OLD CompDir's (older than one day)
#-----------------------------------------------------------------------------
cd $MCTDH_DIR
find $MCTDH_DIR -mtime +1 -name 'CompDir*' -exec rm -rf {} \; >& /dev/null


#-----------------------------------------------------------------------------
# source platform.cnf
#-----------------------------------------------------------------------------
if [ -e $MCTDH_DIR/install/platform.cnf ] ; then
   source $MCTDH_DIR/install/platform.cnf
else
   echo ' '
   echo 'No platform.cnf file. First run install_mctdh. '
   echo ' '
   exit
fi

#-----------------------------------------------------------------------------
# CREATE LISTS OF ANALYSE PROGRAMS, BINARIES, AND COMMANDS.
#-----------------------------------------------------------------------------
for i in $(egrep -ih "^ *program" $MCTDH_DIR/source/analyse/*.[Ffc] \
       $MCTDH_DIR/source/analyse/*.[Ff]90 2>/dev/null | awk '{print $2}' ) ; do
       analist="$analist  "$i
done
for i in $(egrep -ih "^ *program" \
       $MCTDH_DIR/source/vcham/*.[Ff]* | awk '{print $2}') ; do
       vchlist="$vchlist  "$i
done
for i in $(egrep -ih "^ *program" \
       $MCTDH_DIR/source/oct/*.[Ff]* | awk '{print $2}') ; do
       octlist="$octlist  "$i
done
binlist=" mctdh potfit projection filter fdc mcpotfit $analist $vchlist $octlist"
arclist=" gendvr geninwf genoper opfuncs surfaces propwf Aoct "
arclist=" $arclist Amctdh Aanalyse lib libla libnum libode libsys "
exclist=" config all analyse vcham oct $binlist "
cmdlist=" $exclist $arclist "


#-----------------------------------------------------------------------------
# SET DEFAULTS
#-----------------------------------------------------------------------------
comp_script=$MCTDH_DIR/install/compile.cnf
info="cat"
makeall=0
makeALL=0
Quiet=0
quiet=0
debug=0
lsurf=0
if [ -n "$surflist" ] ; then lsurf=1 ; fi
version=$ver
ver0=$ver
ver1=$ver
nametype=0
comp=
name=
clean=
mpi=
openmp=0
compdirpath="$MCTDH_DIR"
verclean=0

#-----------------------------------------------------------------------------
#  Read the options (if any).
#-----------------------------------------------------------------------------
while getopts ":haAc:Cp:qQdDn:N:i:j:lmPuors:t:x:zZ" opt; do
    case $opt in
    h  )  helpf ;;
    a  )  makeall=1 ;;
    A  )  makeall=1
          makeALL=1 ;;
    c  )  comp=$OPTARG ;;
    C  )  verclean=1 ;;
    p  )  MCTDH_PLATFORM=$OPTARG ;;
    s  )  cmp_scrpt=$OPTARG
          if [ "${cmp_scrpt}" = "le" ]; then
             comp_script=$MCTDH_DIR/install/compile.cnf_le
          elif [ "${cmp_scrpt}" = "lenp" ]; then
             comp_script=$MCTDH_DIR/install/compile.cnf_lenp
          elif [ "${cmp_scrpt}" = "be" ]; then
             comp_script=$MCTDH_DIR/install/compile.cnf_be
          elif [ "${cmp_scrpt}" = "benp" ]; then
             comp_script=$MCTDH_DIR/install/compile.cnf_benp
          elif [ -z ${cmp_scrpt%%/*} ]; then
            comp_script=$cmp_scrpt
          elif [ -f $pwd/$cmp_scrpt ]; then
            comp_script=$pwd/$cmp_scrpt
          elif [ -f $MCTDH_DIR/install/$cmp_scrpt ]; then
            comp_script=$MCTDH_DIR/install/$cmp_scrpt
          else
            echo "$cmp_scrpt does not exist"
            exit
          fi
          echo "Using compile script $comp_script" ;;
    t  )  compdirpath="${OPTARG%/}" ;;
    d  )  debug=1
          ver=${ver}d
          ver0=${ver0}
          ver1=${ver1}d ;;
    D  )  debug=2
          ver=${ver}d
          ver0=${ver0}d
          ver1=${ver1}D ;;
    q  )  quiet=1 ;;
    Q  )  Quiet=1
          quiet=1
          info="cat >& /dev/null" ;;
    n  )  nametype=1
          name='_'$OPTARG ;;
    N  )  nametype=2
          name='_'$OPTARG ;;
    i  )  if [ "$OPTARG" = all ] ; then
            lsurf=2
          elif [ $lsurf -ne 2 ] ; then
            lsurf=1
            surflist="$surflist $OPTARG"
          fi ;;
    j  )  jobs=$OPTARG ;;
    l  )  ;; #  This option has been taken care of through lines 295-324.
    m  )  mpi=1 ;;
    P  )  openmp=1 ;;
    u  )  NUMA=1 ;;
    o  )  if [ "$Quiet" = 0 ] ; then info="less" ; fi ;;
    r  )  remove=1 ;;
    x  )  case "$OPTARG" in
          none)   extlib=0;;
          blas)   extlib=1;;
          lapack) extlib=2;;
          0)      extlib=0;;
          1)      extlib=1;;
          2)      extlib=2;;
          *)      echo "Unknown argument '$OPTARG' to option -x !"
                  helpf;;
          esac
          ;;
    z  )  makeall=1
          clean=1  ;;
    Z  )  makeall=1
          makeALL=1
          clean=1  ;;
    \? )  echo ' Unknown option!'
          helpf ;;
  esac
done
shift $(($OPTIND - 1))

if [ $openmp -gt 0 ]; then
  ver=${ver}P
  ver0=${ver0}P
  ver1=${ver1}P
fi

if [ $nametype -eq 1 ]; then
  ver=${ver}${name}
  ver1=${ver1}${name}
fi
if [ $nametype -eq 2 ]; then
  ver=${ver}${name}
  ver0=${ver0}${name}
  ver1=${ver1}${name}
fi

progname="$1"
progname="${progname%/}"           # Remove ending  / from progname
progname="${progname%.[fFcC]}"     # Remove ending .F,.f,.c,.C from progname
progname="${progname%8[1-5]}"      # Remove ending 81...85 from progname
if [ -n "$remove" ] ; then progname='all' ; fi

if [ -z "$progname" ] && [ "$comp" = "onfig" ] ; then
   progname=config
   unset comp
fi
if [ -z "$progname" ] ; then
  echo ' '
  echo '#####  No program (argument) for compilation specified !  #####'
  echo ' '
  helpf
fi

if [ -n "$2" ]; then
  echo ' '
  echo '#####  Nothing must follow the argument of compile !  #####'
  echo "#####  $1   $2   ??????"
  echo ' '
  helpf
fi

#-----------------------------------------------------------------------------
# Check prerequisites for parallel builds.
#-----------------------------------------------------------------------------
if [ "$jobs" == 1 ]; then
   # one job is not parallel
   jobs=""
fi
if [ -n "$jobs" ]; then
   have_ipcrm=1
   have_ipcmd=1
   echo "Parallel build requested, checking prerequisites."
   chkcmd ipcrm || have_ipcrm=0
   chkcmd ipcmd || ( build_ipcmd && chkcmd ipcmd ) || have_ipcmd=0
   if [ $have_ipcrm -eq 0 -o $have_ipcmd -eq 0 ]; then
      echo "Missing prerequisites for parallel builds." >&2
      if [ $have_ipcrm -eq 0 ]; then
         cat <<EOT >&2
"ipcrm" should be part of any modern Linux/Unix system by default.
Please ask your system administrator to install it.
EOT
      fi
      if [ $have_ipcmd -eq 0 ]; then
         cat <<EOT >&2
"ipcmd.c" can be found in the install/ipcmd/ subdirectory, or on
the WWW at http://code.google.com/p/ipcmd/. We tried to build the
excecutable "ipcmd" automatically, but that failed. Try to edit
install/ipcmd/Makefile_* and run bin/build_ipcmd.
EOT
      fi
      echo " " >&2
      echo -n "Do you want to do a non-parallel build (y/n)? " >&2
      read ans
      case $ans in
         [yY]*)
            jobs=""
            ;;
         *)
            echo "Aborting." >&2
            exit 1
            ;;
      esac
   fi
fi

#-----------------------------------------------------------------------------
# Check for existence of task. Make progname complete.
#-----------------------------------------------------------------------------
if ! `echo "$binlist" | fgrep  " $progname " > /dev/null `  ; then
    for i in $binlist ; do
       pgn=$i
       if [ -z "${i%$progname*}" ]; then
          pgn6=$pgn5
          pgn5=$pgn4
          pgn4=$pgn3
          pgn3=$pgn2
          pgn2=$pgn1
          pgn1=$pgn
       fi
    done
    if [ -n "$pgn2" ]; then
       echo "The abbreviated name fits more than one command:"
       echo "$pgn1  $pgn2  $pgn3 $pgn4 $pgn5 $pgn6"
       linklist="$pgn1 $pgn2  $pgn3 $pgn4 $pgn5 $pgn6"
       progname=$pgn1
       progname=$linklist
       linkmult=1
       link=1
       doneprogname=2
       echo "will compile and link them all"
    elif [ -n "$pgn1" ]; then
       echo "Progname: $progname   completed to: $pgn1"
       progname=$pgn1
       doneprogname=1
    fi
fi

if [ -z "$pgn1" ]; then    # no excecutables found, try all tasks.
  if ! `echo "$cmdlist" | fgrep  " $progname " > /dev/null `  ; then
      for i in $cmdlist ; do
          pgn=$i
          if [ -z "${i%$progname*}" ]; then
              pgn4=$pgn3
              pgn3=$pgn2
              pgn2=$pgn1
              pgn1=$pgn
          fi
      done
      if [ -n "$pgn2" ]; then
          echo "The abbreviated name fits more than one command:"
          echo "$pgn1  $pgn2  $pgn3 $pgn4"
          echo "Don't know, which one is to be excecuted. STOP."
          exit 1
      elif [ -n "$pgn1" ]; then
          echo "Progname: $progname   completed to: $pgn1"
          progname=$pgn1
      fi
  fi
fi


#-----------------------------------------------------------------------------
# CREATE linklist, THE LIST OF ALL EXCECUTBLES
#-----------------------------------------------------------------------------
if [ "$progname" = "all" ] ; then
    linklist=$binlist
    linkmult=1
elif [ "$progname" = "analyse" ] ; then
    linklist=$analist
    linkmult=1
elif [ "$progname" = "vcham" ] ; then
    linklist=$vchlist
    linkmult=1
elif [ "$progname" = "oct" ] ; then
    linklist=$octlist
    linkmult=1
elif [ -z "$linklist" ] ; then
   unset linkmult
   for i in $binlist ; do
     if [ "$i" = "$progname" ] ; then linklist="$i" ; fi
   done
fi

#-----------------------------------------------------------------------------
# Check if -m option has to be set. Set comp to mpi-<compiler>.
#-----------------------------------------------------------------------------
if [ "$mpi" = 1 ]; then
   if [ -n "$comp" ] ; then
      echo 'One can use only -c or -m option, not both!'
   elif [ -z "${MCTDH_COMPILER##g77*}" ]; then
      comp=mpi-g77
   elif [ -z "${MCTDH_COMPILER##gfortran*}" ]; then
      comp=mpi-gfortran
   elif [ -z "${MCTDH_COMPILER##intel*}" ]; then
      comp=mpi-intel
   elif [ -z "${MCTDH_COMPILER##pgf77*}" ]; then
      comp=mpi-pgf77
   else
      echo ' Your default compiler is neither g77/gfortran/pgf77 nor intel.'
      echo ' Use -c option rather than -m.'
      exit 1
   fi
fi

#-----------------------------------------------------------------------------
# Check if $comp has to be set. Reset MCTDH_COMPILER.
# source compile.cnf
#-----------------------------------------------------------------------------
if [ -n "$comp" ] ; then
    if [ "$comp" = "$MCTDH_COMPILER" ] ; then
#      Default compiler
       unset comp
    else
#      Non-default compiler
       MCTDH_COMPILER=$comp
       comp=.$comp
    fi
fi
source $comp_script || exit

if [ -n "$NUMA" ]; then
   MCTDH_ADD_LIBS="$MCTDH_ADD_LIBS -lnuma"
   MCTDH_CFLAGS="$MCTDH_CFLAGS -DNUMA"
fi


#-----------------------------------------------------------------------------
# WHEN COMPILING THE LIBRARIES OR ARCHIVES, THE VERSIONS HAVE TO BE
# SET DIFFERENTLY
#-----------------------------------------------------------------------------
if `echo "$binlist" | fgrep " $progname " > /dev/null ` || [ "$link" = 1 ] ||
  [ "$progname" = "all" ] || [ "$progname" = "analyse" ] ; then
    link=1
else
    link=0
 if [ $debug -gt 0 ] ; then
       ver0=$ver
       ver1=$ver
    fi
fi

#-----------------------------------------------------------------------------
# Adjust flags for OpenMP.
#-----------------------------------------------------------------------------
if [ $openmp -gt 0 ]; then
  if [ -z "$MCTDH_OMP_FLAGS" ]; then
    cat <<EOF >&2
I don't know how to use OpenMP with the selected compiler.
Please check or update your compile.cnf (in $MCTDH_DIR/install).
Aborted.
EOF
    exit 1
  fi
  MCTDH_FFLAGS_OPT="${MCTDH_FFLAGS_OPT} ${MCTDH_OMP_FLAGS}"
  MCTDH_FFLAGS_DEB="${MCTDH_FFLAGS_DEB} ${MCTDH_OMP_FLAGS}"
  MCTDH_FFLAGS_0="${MCTDH_FFLAGS_0} ${MCTDH_OMP_FLAGS}"
  MCTDH_CFLAGS="${MCTDH_CFLAGS} ${MCTDH_OMP_FLAGS}"
fi


#-----------------------------------------------------------------------------
# DEFINE VARIABLES
#-----------------------------------------------------------------------------
# Path to directory the executable is moved to after compilation:
progpath=$MCTDH_DIR/bin/binary/$MCTDH_PLATFORM

# Path component defining where versioned executables are stored
verpath='versions'

# Path to directory the object and archive files are stored in:
objpath=$MCTDH_DIR/object/$MCTDH_PLATFORM/$MCTDH_COMPILER

# Paths to different parts of the code
srcpath=$MCTDH_DIR/source
libsrcpath=$MCTDH_DIR/source/lib

mctdhpath=$srcpath/mctdh
incpath=$srcpath/include
dvrpath=$srcpath/gendvr
operpath=$srcpath/genoper
inwfpath=$srcpath/geninwf
proppath=$srcpath/propwf
potfitpath=$srcpath/potfit
mcpotfitpath=$srcpath/potfit
filterpath=$srcpath/fd_real
fdcpath=$srcpath/fd_cmplx
vchampath=$srcpath/vcham
analysepath=$srcpath/analyse
opfuncspath=$srcpath/opfuncs
surfpath=$srcpath/surfaces
octpath=$srcpath/oct

eigenpath=$libsrcpath/eigen
linearpath=$libsrcpath/linear
blaspath=$libsrcpath/BLAS
lapackpath=$libsrcpath/LAPACK
odepath=$libsrcpath/ode
utilitiespath=$libsrcpath/utilities

#-----------------------------------------------------------------------------
# -r option, remove specified *.o or *.a files from $objpath .
#-----------------------------------------------------------------------------
if [ -n "$remove" ] ; then
   if [ ! -e "$objpath" ]; then
      echo 'Directory "'$objpath'" does not exist!'
      exit
   fi
   cd $objpath
   echo "$minus40$minus40"
   echo " The object-directory is: "`pwd`
   if [ $debug = 0 ] ; then
      echo "If you want to remove debug-versions, set -d or -D option."
   fi
   echo ' Object files (*.o)'
   ls *${ver1}.o
   echo ' '
   echo ' Archives (*.a)'
   ls *${ver1}.a
   echo ' '
   echo ' Return or 'q' will exit.'
   while : ; do
      echo -n ' Which file do you want to remove? : '
      read rmfile
      if [ -z "$rmfile" ] || [ "$rmfile" = q ] ; then exit ; fi
      rm -f $rmfile
      if [ "$?" = 0 ] ; then  echo "$rmfile removed" ; fi
   done
   exit
fi

#-----------------------------------------------------------------------------
# -C option, remove unreferenced versioned executables
#-----------------------------------------------------------------------------
if [ $verclean -gt 0 ]; then
   if [ $versioned -eq 0 ]; then
      echo "You are not using versioned executables, so option -C doesn't apply." >&2
      exit 1
   fi
   # create directory for versions we want to keep
   verdir="$progpath/$verpath"
   keepdir="$verdir.KEEP"
   mkdir -p "$keepdir"
   # go through the list and move the current version to $keepdir
   for i in $linklist ; do
      i1="$progpath/$i$ver1$comp"
      if [ -L "$i1" ]; then
         i2=$(readlink "$i1")       # resolve symlink
         i3="$progpath/$i2"         # make it absolute
         [ -f "$i3" ] && /bin/mv "$i3" "$keepdir"/
         echo -n "Keeping executable " ; basename "$i2"
      fi
      # remove remaining versions
      /bin/rm -f  "$verdir/$i$ver1$comp--"*
   done
   # move the kept versions (if any) into place
   if ! rmdir "$keepdir" 2>/dev/null; then
      /bin/mv "$keepdir"/* "$verdir"/
      rmdir "$keepdir"
   fi
   echo "Removing unreferenced executables finished."
   exit
fi

#-----------------------------------------------------------------------------
# CREATE LISTS OF SURFACE ROUTINES
#-----------------------------------------------------------------------------
unset surfout
unset surfaces
if [ "$progname" = surfaces ] && [ $lsurf -eq 0 ] ; then lsurf=2 ; fi
if [ $lsurf -gt 0 ] ; then
    cd $surfpath
    available_surf=`ls *.[Ff] *.[Ff]90 2>/dev/null | sed -e '/DEF_/d' \
              -e '/DUMMY/d' -e 's/\.[fF]$//' -e 's/\.[fF]90$//'`
    if [ $lsurf -eq 2 ] ; then surflist=$available_surf ; fi
    for i in $surflist  ; do
       j=`echo "$available_surf" | egrep "^${i}$"`
       if [ -z "$j" ] ; then
          j=`echo "$available_surf" | egrep "^$i"`
          j=`echo $j | cut -d ' ' -f1`
       fi
       if [ -n "$j" ] ; then
          surfout="$surfout $j"
          surfaces="$surfaces ${j}.o"
#         Avoid multiple entries
          available_surf=`echo "$available_surf" | sed -e "/^${j}$/d"`
       else
          j=`echo $surfout | tr ' ' '\n' | egrep "^${i}$"`
          if [ -n "$j" ] ; then
             echo " Surface $j is already included"
          else
             echo "###########################################################"
             echo "#######  WARNING: could not find surface $i  ############"
             echo "###########################################################"
             exit 1
          fi
       fi
    done

#  Add h20 if wslfh is linked
    if [ "$surfout" != "${surfout%wslfh*}" ] &&  \
       [ "$surfout" = "${surfout%h2o*}" ] ; then
        surfout="$surfout h2o"
        surfaces="$surfaces h2o.o"
    fi
    cd $MCTDH_DIR
fi

if [ -z "$surfout" ] ; then
    surfout=none
    surfaces="DUMMYsrf.o"
# Some compilers do not like an empty surfaces list. The line above avoids this.
fi
echo 'Included surfaces (-i option): '$surfout

#-----------------------------------------------------------------------------
# Add LAPACK/BLAS libraries to MCTDH_ADD_LIBS if requested
#-----------------------------------------------------------------------------
if [ $extlib -eq 2 ]; then
    MCTDH_ADD_LIBS="$EXTERNAL_LAPACK $EXTERNAL_BLAS $MCTDH_ADD_LIBS"
elif [ $extlib -eq 1 ]; then
    MCTDH_ADD_LIBS="$EXTERNAL_BLAS $MCTDH_ADD_LIBS"
fi

#-----------------------------------------------------------------------------
# SET MACHINE DEPENDENT VARIABLES
#-----------------------------------------------------------------------------
os="$MCTDH_OP_SYSTEM"
fflagsdebug="FFLAGS=$MCTDH_FFLAGS_DEB $MCTDH_FFLAGS_MOD$objpath"
fflagsoptimize="FFLAGS=$MCTDH_FFLAGS_OPT $MCTDH_FFLAGS_MOD$objpath"
fflags0="FFLAGS_0=$MCTDH_FFLAGS_0"
fflags0db="FFLAGS_0=$MCTDH_FFLAGS_0 -g"
fflags="$fflagsoptimize"
fflagsinc="$MCTDH_FFLAGS_INC"
cflags="CFLAGS=$MCTDH_CFLAGS -DF2C_STYLE=$MCTDH_F2C_STYLE -DPTHREAD_STYLE=$MCTDH_PTHREAD_STYLE"
arflags="ARFLAGS=$MCTDH_ARFLAGS"
addlib="ADDLIB=$MCTDH_ADD_LIBS"
make="$MCTDH_MAKE_CMD -k"

#-----------------------------------------------------------------------------
# Check for existence of task. Call configf.
#-----------------------------------------------------------------------------
if [ -z "$doneprogname" ]; then
  if [ "$progname" = "config" ] || [ "$progname" = "info" ]; then configf; fi

  if ! `echo "$cmdlist" | fgrep  " $progname " > /dev/null `  ; then
     echo \
     '*************************************************************************'
     echo ' '
     echo '#####  The argument "'$progname'" is invalid!  #####'
     echo ' '
     exit 1
  fi
fi

#-----------------------------------------------------------------------------
# SET FLAGS AND VARIABLES ACCORDING TO OPTIONS.
#-----------------------------------------------------------------------------
if [ $debug -gt 0 ]; then fflags="$fflagsdebug"; fi
if [ "$debug" = 2 ]; then fflags0="$fflags0db"; fi
if [ "$quiet" = 1 ]; then make="$make -s"; fi
if [ -n "$jobs" ]; then make="$make -j $jobs"; fi

#-----------------------------------------------------------------------------
# ECHO DEFINITION OF VARIABLES
#-----------------------------------------------------------------------------
unset verp
txt='(compile and link a set of programs)'
if [ $progname = all ] ; then
   txt='(compile and link all MCTDH programs)'

elif  `echo "$binlist" | fgrep  " $progname " > /dev/null `  ; then
  verp=$ver1
  txt='(compile and link a single program)'
elif  `echo "$arclist" | fgrep  " $progname " > /dev/null `  ; then
  txt='(install archive)'
fi

echo "$minus40$minus40"
echo "  compile  $progname                      $DATE"
echo "$minus40$minus40"
echo 'Platform:             '$MCTDH_PLATFORM
echo 'Compiler environment: '$MCTDH_COMPILER
echo 'Operating system:     '$MCTDH_OP_SYSTEM
echo 'Fortran compiler:     '$FC'   '${comp#.}
echo 'C compiler:           '$CC
echo 'Make command:         '$make
echo 'Program name:         '$progname$verp$comp'   '$txt
echo ' '
echo 'Program path:         '$progpath
echo 'Object path:          '$objpath
if [ -n "$cmp_scrpt" ]; then
   echo 'Using compile script: '$comp_script
fi
echo ' '


#-----------------------------------------------------------------------------
# mkdir object, bin IF NECESSARY
#-----------------------------------------------------------------------------
if [ ! -e "$objpath" ]; then
  /bin/mkdir -p $objpath  >& /dev/null
  echo 'Directory "'$objpath'" created'
fi
if [ ! -e "$progpath" ]; then
  /bin/mkdir -p $progpath >& /dev/null
  echo 'Directory "'$progpath'" created'
fi

#-----------------------------------------------------------------------------
# Create the compile directory CompDir$$ and cd to this directory.
#-----------------------------------------------------------------------------
compdir="$compdirpath/CompDir$$"
if ! mkdir "$compdir"; then
  echo "Cannot create temporary directory '$compdir' for compilation!"
  exit 1
fi
cd "$compdir"
cp $MCTDH_DIR/install/Makefile .
cp $MCTDH_DIR/install/user_surfaces .
cp $MCTDH_DIR/install/user_surfdef .
touch user_surfaces     # In case they do not exist
touch user_surfdef

# depending on $extlib, create ./Makefile.extlib, which is going to
# be included by the Makefile
# [ if everybody used GNU make, such hackery wouldn't be necessary ]
if [ "$extlib" -eq 0 ]; then
  echo 'LIB_LA_EXT = $(LIB_LA) $(LIB_LAPACK) $(LIB_BLAS)' >Makefile.extlib
  echo 'LA_EXT = $(LA) $(LAPACK) $(BLAS)' >>Makefile.extlib
elif [ "$extlib" -eq 1 ]; then
  echo 'LIB_LA_EXT = $(LIB_LA) $(LIB_LAPACK)' >Makefile.extlib
  echo 'LA_EXT = $(LA) $(LAPACK)' >>Makefile.extlib
elif [ "$extlib" -eq 2 ]; then
  echo 'LIB_LA_EXT = $(LIB_LA)' >Makefile.extlib
  echo 'LA_EXT = $(LA)' >>Makefile.extlib
else
  echo "Can't happen."
  exit 1
fi

#To avoid unnecessary recompilation load the surface object files on CompDir$$
if [ $lsurf -gt 0 ] && [ $makeall -eq 0 ] && \
            [ -f "$objpath/surfaces${ver}.a" ] ; then
    ar xo $objpath/surfaces${ver}.a
fi

#-----------------------------------------------------------------------------
# REMOVE ARCHIVE AND OBJECT FILES IF ALL FILES ARE TO BE COMPILED
#-----------------------------------------------------------------------------
if [ ! "$progname" = "all" ]    && [ ! "$progname" = "mctdh" ]   && \
   [ ! "$progname" = "potfit" ] && [ ! "$progname" = "analyse" ] && \
   [ ! "$progname" = "flux" ]   && [ -n "${progname##show*}" ]   && \
   [ ! "$progname" = "filter" ] && [ ! "$progname" = "fdc" ]  ; then
      makeALL=0
fi

if [ "$makeALL" = 1 ]; then
  $make 'PATH_OBJ='$objpath 'VER='$ver 'VER0='$ver0 \
           clean_lib >&  /dev/null
  $make 'PATH_OBJ='$objpath 'VER='$ver 'VER0='$ver0 \
           clean_surfaces >&  /dev/null
  $make 'PATH_OBJ='$objpath 'VER='$ver 'VER0='$ver0 \
           clean_$progname >&  /dev/null
  if [ -z "$clean" ] ; then
  echo 'All "'$progname'"-files -- including the lib -- will be recompiled.'
  else
     echo 'All "'$progname'"-archives -- including the lib -- removed.'
     exit
  fi
elif [ "$makeall" = 1 ]; then
  $make 'PATH_OBJ='$objpath 'VER='$ver 'VER0='$ver0 \
    "PATH_MAIN=$mainpath" "PATH_MCTDH=$mctdhpath" \
    "PATH_GENDVR=$dvrpath" "PATH_GENOPER=$operpath" \
    "PATH_GENINWF=$inwfpath" "PATH_PROPWF=$proppath" \
    "PATH_INC=$incpath" "PATH_POTFIT=$potfitpath" \
    "PATH_FILTER=$filterpath" "PATH_FDC=$fdcpath" \
    "PATH_VCHAM=$vchampath" \
    "PATH_OCT=$octpath" "PATH_POTFIT=$potfitpath" \
    "PATH_ANALYSE=$analysepath" "PATH_EIGEN=$eigenpath" \
    "PATH_LINEAR=$linearpath" "PATH_ODE=$odepath" \
    "PATH_BLAS=$blaspath" "PATH_LAPACK=$lapackpath" \
    "PATH_UTILITIES=$utilitiespath" "PATH_OPFUNCS=$opfuncspath" \
    "PATH_SURFACES=$surfpath" "SURFACES=$surfaces" \
           clean_$progname

  echo ' '
  if [ -z "$clean" ] ; then
    if [ -z "${progname##lib*}" ] ; then
    echo 'All "'$progname'"-files will be recompiled.'
    else
    echo 'All "'$progname'"-files will be recompiled. The library is kept.'
    fi
  else
     echo 'All "'$progname'"-archive(s) removed.'
     echo ' '
     exit
  fi
else
  echo 'Only altered files will be compiled.'
fi

#-----------------------------------------------------------------------------
# WRITE TIME, DATE, AND HOSTNAME TO $compdir/cdate.inc
#-----------------------------------------------------------------------------
dline='Compiled: '$(date +'%a, %d %b %Y, %T')
dline=$(echo $dline | cut -c 1-45)
hstnm=$(hostname)
hstnm=${hstnm%%.*}
hline="; Host: $hstnm"
hline=$(echo $hline | cut -c 1-40)
surfout=$(echo $surfout | cut -c 1-60)
echo "      character*80  dateline, incsurf"       > $compdir/cdate.inc
echo "      parameter(dateline='$dline'"              >> $compdir/cdate.inc
echo "     + //' $hline')"                            >> $compdir/cdate.inc
echo "      parameter(incsurf='Included surfaces: '//">> $compdir/cdate.inc
echo "     + '$surfout')"                             >> $compdir/cdate.inc

#-----------------------------------------------------------------------------
# ECHO COMPILER OPTIONS
#-----------------------------------------------------------------------------

if [ $debug -gt 0 ]; then
  echo 'Starting compilation using debug options.'
  if [ $debug -eq 1 ] && [ "$progname" != "lib" ] ; then
     echo 'Program linked to optimised libraries.'
  elif [ $debug -eq 2 ] && [ "$progname" != "lib" ] ; then
     echo 'Program linked to debug libraries.'
  fi
else
  echo 'Starting compilation with optimization.'
fi
echo ' '

#-----------------------------------------------------------------------------
# MOVE MAIN PROGRAM'S OBJECT FILE TO SOURCE DIRECTORY (required for
# HP and CRAY).
#-----------------------------------------------------------------------------
if [ "$MCTDH_OP_SYSTEM" = "HP-UX" ] || [ "$MCTDH_OP_SYSTEM" = "UNICOS" ]
   then
   for i in $linklist ; do
      if [ -f "$objpath/$i$ver.o" ]; then
        cp -p $objpath/$i$ver.o ./$i$ver.o
        if [ "$Quiet" = "0" ] ; then
           echo "copied $objpath/$i$ver.o ./$i$ver.o"
        fi
      fi
   done
   mainpath='.'
else
   mainpath="$objpath"
fi

#-----------------------------------------------------------------------------
# Start a new shell to observe the object file.
#-----------------------------------------------------------------------------
if [ "$quiet" = 1 ] ; then
   (archive=`ls -tr $objpath/*.[ao]  2> /dev/null`
    archive=${archive##*/}
    while [ -z "$archive" ] || [ "$objpath/$archive" -ot $compdir/Makefile ]
    do
        archive=`ls -tr $objpath/*.[ao]  2> /dev/null`
        archive=${archive##*/}
    done
    echo " $(date '+%T')   Installing: $archive"
    old2=$old1
    old1=$archive
    while [ -f $compdir/Makefile ] ; do
        archive=`ls -tr $objpath/*.[ao] 2> /dev/null`
        archive=${archive##*/}
        if [ "$old1" != "$archive" ] && [ "$old2" != "$archive" ] ; then
            echo " $(date '+%T')   Installing: $archive"
            old2=$old1
            old1=$archive
        fi
        sleep 1
    done
    exit) &
fi

#-----------------------------------------------------------------------------
# In case you compile with -d option, make sure that the optimized
# library is up to date.
#-----------------------------------------------------------------------------
if [ $debug -eq 1 ] ; then
    if [ "$progname" = "mctdh" ] || [ "$progname" = "potfit" ] || \
       [ "$progname" = "filter" ] || [ "$progname" = "fdc" ] || \
       [ "$progname" = "all" ] ; then

       /bin/rm -f  ok.$$.int  >& /dev/null

     (runmake "$fflagsoptimize $fflagsinc$incpath"  "$fflags0" \
         "$cflags" "$arflags" "$addlib" "VER=$ver0" "VER0=$ver0" \
         "PATH_OBJ=$objpath" "PATH_MAIN=$mainpath" "PATH_INC=$incpath"  \
         "PATH_EIGEN=$eigenpath" "PATH_UTILITIES=$utilitiespath" \
         "PATH_LINEAR=$linearpath" "PATH_ODE=$odepath" \
         "PATH_BLAS=$blaspath" "PATH_LAPACK=$lapackpath" \
         "FLUSH_EXT=$MCTDH_FLUSH_EXT" lib || \
          touch ok.$$.int) | fgrep -v Nothing | eval $info | tee  li.$$.int

          liste=`cat li.$$.int | wc -l `
          /bin/rm  li.$$.int  >& /dev/null

          if [ -f ok.$$.int ] ; then
             /bin/rm -f  ok.$$.int
             echo ' '
             echo 'Sorry, but the re-compilation of the library failed!'
             echo ' '
             /bin/rm -rf  $compdir  >& /dev/null
             exit 1
          else
             if [ "$Quiet" = 0 ] && [ $liste -gt 0 ] ; then
                echo '### Library re-compiled ###'
                echo ' '
             fi
          fi
    fi
fi

#-----------------------------------------------------------------------------
# CALL MAKEFILE
#-----------------------------------------------------------------------------
    (runmake "$fflags $fflagsinc$compdir $fflagsinc$incpath" \
    "$fflags0" "$cflags" "$arflags" "$addlib" "VER=$ver" "VER0=$ver0" \
    "PATH_OBJ=$objpath" "PATH_MAIN=$mainpath" "PATH_MCTDH=$mctdhpath" \
    "PATH_GENDVR=$dvrpath" "PATH_GENOPER=$operpath" \
    "PATH_GENINWF=$inwfpath" "PATH_PROPWF=$proppath" \
    "PATH_INC=$incpath" "PATH_POTFIT=$potfitpath" \
    "PATH_FILTER=$filterpath" "PATH_FDC=$fdcpath" \
    "PATH_VCHAM=$vchampath" \
    "PATH_OCT=$octpath" "PATH_MCPOTFIT=$mcpotfitpath"\
    "PATH_ANALYSE=$analysepath" "PATH_EIGEN=$eigenpath" \
    "PATH_LINEAR=$linearpath" "PATH_ODE=$odepath" \
    "PATH_BLAS=$blaspath" "PATH_LAPACK=$lapackpath" \
    "PATH_UTILITIES=$utilitiespath" "PATH_OPFUNCS=$opfuncspath" \
    "PATH_SURFACES=$surfpath" "SURFACES=$surfaces" \
    "FLUSH_EXT=$MCTDH_FLUSH_EXT" \
    $progname || touch ok.$$.int) 2>&1 | eval $info

##-----------------------------------------------------------------------------
## CALL MAKEFILE AGAIN IF MAKE FINISHED WITH ERROR
##-----------------------------------------------------------------------------
#if [ -f ok.$$.int ] && [ -n "$linkmult" ]; then
#    /bin/rm -f  ok.$$.int
#    echo
#    echo '### Redo make step! (1) ###'
#    if [ -n "$jobs" ]; then  make=${make%%-j*} ; fi
#    ($make "$fflags $fflagsinc$compdir $fflagsinc$incpath" \
#    "$fflags0" "$cflags" "$arflags" "$addlib" "VER=$ver" "VER0=$ver0" \
#    "PATH_OBJ=$objpath" "PATH_MAIN=$mainpath" "PATH_MCTDH=$mctdhpath" \
#    "PATH_GENDVR=$dvrpath" "PATH_GENOPER=$operpath" \
#    "PATH_GENINWF=$inwfpath" "PATH_PROPWF=$proppath" \
#    "PATH_INC=$incpath" "PATH_POTFIT=$potfitpath" \
#    "PATH_FILTER=$filterpath" "PATH_FDC=$fdcpath" \
#    "PATH_VCHAM=$vchampath" \
#    "PATH_OCT=$octpath" \
#    "PATH_ANALYSE=$analysepath" "PATH_EIGEN=$eigenpath" \
#    "PATH_LINEAR=$linearpath" "PATH_ODE=$odepath" \
#    "PATH_BLAS=$blaspath" "PATH_LAPACK=$lapackpath" \
#    "PATH_UTILITIES=$utilitiespath" "PATH_OPFUNCS=$opfuncspath" \
#    "PATH_SURFACES=$surfpath" "SURFACES=$surfaces" \
#    "FLUSH_EXT=$MCTDH_FLUSH_EXT" \
#    $progname || touch ok.$$.int) 2>&1 | eval $info
#fi

#-----------------------------------------------------------------------------
# CHECK WHETHER MAKE COMMAND WAS SUCCESSFUL
#-----------------------------------------------------------------------------
cfailed=0
if [ "$quiet" = 1 ] ; then rm -f $compdir/Makefile ; sleep 1 ; fi
if [ -f ok.$$.int ] ; then
   /bin/rm -f  ok.$$.int
   exitcode=1
   cfailed=1
   echo ' '
   echo 'Sorry, but the compilation failed! Better luck next time!'
   if [ "$progname" = all ] || [ "$progname" = analyse ] ; then
     echo 'Some or all executables are not created!'
   elif [ "$progname" = lib ] ; then
     echo '### The library is not installed!'
   elif [ "$link" = 0 ] ; then
     echo '### '$objpath/$progname$ver'.a is not installed!'
   fi
   echo ' '
else
   exitcode=0
   echo ' '
   if [ "$progname" = lib ] ; then
     echo 'The library is installed!'
   elif [ "$link" = 0 ] ; then
     echo 'The archive '$objpath/$progname$ver'.a is installed!'
   fi
   echo ' '
fi

#-----------------------------------------------------------------------------
# CHANGE PERMISSIONS OF ARCHIVE AND OBJECT FILES
#-----------------------------------------------------------------------------
chmod  $permo $objpath/{*.a,*.o}   >&  /dev/null

#-----------------------------------------------------------------------------
# RENAME AND MOVE THE EXECUTABLE FILE
#-----------------------------------------------------------------------------
created=0
notcrea=0

# create directory for versioned executables
if [ $versioned -gt 0 ]; then
   mkdir -p "$progpath/$verpath"
fi

for i in $linklist ; do
   if [ -e ./$i ]; then
     chmod $permb ./$i
     [ -e "$progpath/$i$ver1$comp" ] && /bin/rm -f "$progpath/$i$ver1$comp"
     if [ $versioned -gt 0 ]; then
        /bin/mv  ./$i  "$progpath/$verpath/$i$ver1$comp--$verstr"
        /bin/ln -sf  "$verpath/$i$ver1$comp--$verstr"  "$progpath/$i$ver1$comp"
     else
        /bin/mv  ./$i  "$progpath/$i$ver1$comp"
     fi
     echo "Executable $progpath/$i$ver1$comp created."
     created=$((created+1))
   else
     echo "### $progpath/$i$ver1$comp not created."
     notcrea=$((notcrea+1))
   fi
done

if [ $notcrea -gt 0 ] ; then
    exitcode=1
    echo ' '
    echo "Sorry, $notcrea  executables are not created."
    echo "       $created  executables are created."
elif [ $cfailed = 0 ] ; then
    echo ' '
    echo 'Congratulations, the compilation was successful.'
    if [ $created -gt 1 ] ; then
       echo " $created executables are created."
    fi

    if [ $openmp -gt 0 ]; then
       cat << EOF

########################################################################

NOTE: Some executables are enabled to use shared-memory parallelization
      via OpenMP directives. To make use of this, you should set the
      following environment variables in your *execution* environment:

      OMP_NUM_THREADS=<n>       # number of CPU cores to use

      OMP_SCHEDULE="dynamic,1"  # threading schedule
                                # (consider other schedules as well)

      OMP_STACKSIZE="64M"       # stack size per thread
                                # (you might need to increase this)

NOTE: Within MCTDH 8.4 at present, only the programs 'vminmax',
      'mcpotfit' and 'potfit' support OpenMP. The latter only when re-
      fitting a PES file. For all other programs the -P option
      makes no difference.

########################################################################
EOF
    fi



fi

#-----------------------------------------------------------------------------
# REMOVE CompDir$$ AND EXIT THE SHELL SCRIPT
# SEARCH FOR AND REMOVE OLD CompDir's (older than one day)
#-----------------------------------------------------------------------------
cd $MCTDH_DIR # leave $compdir
rm -rf  $compdir  >& /dev/null
find $MCTDH_DIR -mtime +1 -name 'CompDir*' -exec rm -rf {} \; >& /dev/null
echo ' '
echo '------  compile  ---  '$(date +'%a, %d %b %Y, %T')' ---  good bye!  '$minus40 \
 | cut -c 1-80
echo "$minus40$minus40"
echo ' '

#-----------------------------------------------------------------------------
# Set the link to python scripts if they do not exist
#-----------------------------------------------------------------------------
cwd=$(pwd)
cd $MCTDH_DIR/bin/
if [ ! -e 'optcntrl' ]; then
    echo "(Re-)Installing symbolic link 'optcntrl'"
    ln -sf python/oct/optcntrl.py optcntrl
elif [ ! -h 'optcntrl' ]; then
    echo 'There is a file "optcntrl" in'
    echo "  \$MCTDH_DIR/bin/"
    echo 'which is not a symbolic link to '
    echo "  \$MCTDH_DIR/bin/python/oct/optcntrl.py."
    echo "Shall I backup and overwrite? (y|n)"
    read ans
    if [ $ans = "y" ]; then
        date=$(date +'%d %b %Y %T' | sed 's/[ :]/_/g')
        mv optcntrl optcntrl.bak.$date
        ln -sf python/oct/optcntrl.py optcntrl
        echo "The old optcntrl has been copied to optcntrl.bak.$date"
    else
        echo 'The command "optcntrl" will not be available'
        echo "Instead you may use \$MCTDH_DIR/bin/python/oct/optcntrl.py."
    fi
fi
if [ ! -e 'clusterstat' ]; then
    echo "(Re-)Installing symbolic link 'clusterstat'"
    ln -sf python/clusters/clusterstat.py clusterstat
elif [ ! -h 'clusterstat' ]; then
    echo 'There is a file "clusterstat" in'
    echo "  \$MCTDH_DIR/bin/"
    echo 'which is not a symbolic link to '
    echo "  \$MCTDH_DIR/python/clusters/clusterstat.py"
    echo "Shall I backup and overwrite? (y|n)"
    read ans
    if [ $ans = "y" ]; then
        date=$(date +'%d %b %Y %T' | sed 's/[ :]/_/g')
        mv clusterstat clusterstat.bak.$date
        ln -sf python/clusters/clusterstat.py clusterstat
        echo "The old clusterstat has been copied to clusterstat.bak.$date"
    else
        echo 'The command "clusterstat" will not be available'
        echo "Instead you may use \$MCTDH_DIR/bin/python/clusters/clusterstat.py."
    fi
fi
if [ ! -e 'clusterana' ]; then
    echo "(Re-)Installing symbolic link 'clusterana'"
    ln -sf python/clusters/clusterana.py clusterana
elif [ ! -h 'clusterana' ]; then
    echo 'There is a file "clusterana" in'
    echo "  \$MCTDH_DIR/bin/"
    echo 'which is not a symbolic link to '
    echo "  \$MCTDH_DIR/python/clusters/clusterana.py"
    echo "Shall I backup and overwrite? (y|n)"
    read ans
    if [ $ans = "y" ]; then
        date=$(date +'%d %b %Y %T' | sed 's/[ :]/_/g')
        mv clusterana clusterana.bak.$date
        ln -sf python/clusters/clusterana.py clusterana
        echo "The old clusterana has been copied to clusterana.bak.$date"
    else
        echo 'The command "clusterana" will not be available'
        echo "Instead you may use \$MCTDH_DIR/bin/python/clusters/clusterana.py."
    fi
fi

if [ ! -e 'clusterbuild' ]; then
    echo "(Re-)Installing symbolic link 'clusterbuild'"
    ln -s -f python/clusters/clusterbuild.py clusterbuild
elif [ ! -h 'clusterbuild' ]; then
    echo 'There is a file "clusterbuild" in'
    echo "  \$MCTDH_DIR/bin/"
    echo 'which is not a symbolic link to '
    echo "  \$MCTDH_DIR/python/clusters/clusterbuild.py"
    echo "Shall I backup and overwrite? (y|n)"
    read ans
    if [ $ans = "y" ]; then
        date=$(date +'%d %b %Y %T' | sed 's/[ :]/_/g')
        mv clusterbuild clusterbuild.bak.$date
        ln -sf python/clusters/clusterbuild.py clusterbuild
        echo "The old chkpes has been copied to clusterbuild.bak.$date"
    else
        echo 'The command "clusterbuild" will not be available'
        echo "Instead you may use \$MCTDH_DIR/bin/python/clusters/clusterbuild.py."
    fi
fi

if [ ! -e 'chkpes' ]; then
    echo "(Re-)Installing symbolic link 'chkpes'"
    ln -s -f python/clusters/chkpes.py chkpes
elif [ ! -h 'chkpes' ]; then
    echo 'There is a file "chkpes" in'
    echo "  \$MCTDH_DIR/bin/"
    echo 'which is not a symbolic link to '
    echo "  \$MCTDH_DIR/python/clusters/chkpes.py"
    echo "Shall I backup and overwrite? (y|n)"
    read ans
    if [ $ans = "y" ]; then
        date=$(date +'%d %b %Y %T' | sed 's/[ :]/_/g')
        mv chkpes chkpes.bak.$date
        ln -sf python/clusters/chkpes.py chkpes
        echo "The old chkpes has been copied to chkpes.bak.$date"
    else
        echo 'The command "chkpes" will not be available'
        echo "Instead you may use \$MCTDH_DIR/bin/python/clusters/chkpes.py."
    fi
fi


cd $cwd
echo

exit $exitcode

