#!/bin/bash
#
# This script coordinates the installation of ESP-r executables,
# databases, example models and support materials. It can be used
# on linux, cygwin, mingw, OS X and Windows platforms.

# Source and target directories.
HOMEdir=`pwd`			# Current directory.
DESTdir=/opt/esp-r		# Installation directory.
ESPdir=$DESTdir
DATdir="${HOMEdir}/data"	# Source data directory.
DOCdir="${HOMEdir}/doc"		# Source documents directory.
SCRIPTdir="${HOMEdir}/src/bin"	# Source scripts directory.
MODdir="${HOMEdir}/models"	# Source models directory.
TRAdir="${MODdir}/training"	# Source training models.
VALdir="${MODdir}/validation"	# Source validation models.
SRCdir="${HOMEdir}/src"         # Source code directory.
COSIMdir=" "		        # Harmonizer installation directory.

# Compilation settings.
mode="interactive"         # Feedback during installation. 
xml_support="yes"          # Support for XML output.
SQLite_support="no"        # Support for SQLite output.
FMI_support="no"           # Support for FMI connectivity.
debugging="no"             # Support for debugging symbols.
EXE=""                     # Executable file extension.
opt="-O1"                  # Optimisation to be applied
FFLAGS="-I../include "     # Fortran compiler flags.
CFLAGS="-I../include "     # C compiler flags.
LD_FLAGS=" "               # Link-loader flags.
complexity="2"             # Model complexity (medium by default).
platform="auto-detect"     # Installation platform.
install_dbs="yes"          # Install databases.
install_training="yes"     # Install training models.
install_exes="yes"         # Install executables.
delete_temp_files="yes"    # Delete temporary files.
preserve_espr_dir="yes"    # Preserve installation directory.
gnu_version="gcc4"         # Required gcc version.
make_msg_file=".make_msg"  # Dump messages from 'make' to file.
compiler_version="none"    # Compiler version.
xLibs="X11"                # Required x-library.
enable_cosim="no"          # TRNSYS co-simulation. 
extendedDebug="no"         # Extended debugging.
use_intel="no"             # Use Intel compilers.
skip_ish_calcs="yes"       # Binary shading file creation.
reuse_ish_calcs="no"       # Map ascii shading files to binary.
clean="yes"                # Clean object files after compilation.
unversioned="no"           # Check for versioning info.

# ESP-r executables (bld & plt not included by default because their
# functionality is automatically encapsulated in bps).
programs="aco b2e bps dfs dfv cdb c2e clm e2r ecnv eco enet grd ish mfs mld mrt pdb prj res vew"
programs=" ${programs} "   # Leading/ trailing space added for regexp matching.
targets=" "	           # Will be overwitten later.
third_party="no"           # Suggest installation of third party tools at end of script.

# Determine computer architecture and availability of stat.
architecture=`uname -s`	   # Kernel name.
machine=`uname -m`	   # Hardware name.
case $machine in
  x86_64) echo "Detected Intel chipset";;
  arm64)  echo "Detected M1 chipset";;
  aarch64)echo "Detected arm chipset";;
esac
if [ -x /usr/bin/stat ]; then
   stat_avail="yes"
elif [ -x /bin/stat ]; then
   stat_avail="yes"
else
   stat_avail="no"
fi

# Process Install script command line options.
help=0
input="no"
if [ $# -ne 0 ]; then
   for i do
      if [ "${input}" = "yes" ]; then
         input="no"
      else
        case "$i" in
        -h | --help)    help=1;                    shift;;
        --debug)        debugging=yes; clean=no;   shift;;
        -d) shift;      DESTdir=$1; input="yes";
                        ESPdir=$DESTdir;           shift;;
        --force)        preserve_espr_dir="no";    shift;;
        --no_training | --no-training)
                        install_training="no";     shift;;
        --no_dbs | --no-dbs)
                        install_dbs="no";          shift;;
        --no_exes | --no-exes)
                        install_exes="no";         shift;;
        --extra-debug | --extra_debug)
                        debugging="yes"; clean=no;
                        extendedDebugging="yes";   shift;;
        --silent)       mode="silent";             shift;;
        --xml)          xml_support=yes;           shift;;
        --SQLite)       SQLite_support="yes";      shift;;
        --FMI)          FMI_support="yes";         shift;;
        --co-sim)       shift;
                        COSIMdir=$1;
                        input="yes";
                        enable_cosim="yes";        shift;;
        --gcc4)         gnu_version="gcc4";        shift;;
        --opt0)         opt="-O0";        shift;;
        --opt1)         opt="-O1";        shift;;
        --opt2)         opt="-O2";        shift;;
        --opt3)         opt="-O3";        shift;;
        --small)        complexity="1";   shift;;
        --medium)       complexity="2";   shift;;
        --complex)      complexity="3";   shift;;
        --intel)        use_intel="yes";           shift;;
        --X11)          xLibs="X11";               shift;;
        --GTK)          xLibs="GTK";               shift;;
        --noX)          xLibs="noX";               shift;;
        --compiler_version | --compiler-version)
                        shift;
                        input="yes";
                        compiler_version=$1;       shift;;
        -v | --verbose) make_msg_file="";          shift;;
        --reuse_ish_calcs) reuse_ish_calcs="yes";  shift;;
        --unversioned)     unversioned="yes";      shift;;
        --quick_rebuild)   clean="no";             shift;;
        --skip_ish_calcs | --skip-ish-calcs )
                        skip_ish_calcs="yes";      shift;;
        --quick_rebuild | --quick-rebuild )
                        clean="no";                shift;;
        --no-svn-query | --no_svn_query)
                        unversioned="yes";         shift;;
        clean)          targets="${targets} clean" shift;;
        *)
              # Check if target is buildable.
              match="no"
              position=`expr match " $programs " ".* ${i} .*"`
              if  [ "${position}" != 0 ]; then
                 targets="${targets} ${i}"
                 shift
              else
                 # Trap unsupported arguments.
                 echo " "
                 echo " Error: argument $i is not supported."
                 echo " Run ./Install --help."
                 echo " "
                 exit
              fi
           ;;
        esac
      fi
   done
fi

# If Targets is empty, build all programs.
if [ "${targets}" = " " ]; then
  targets="${programs}"
  third_party="yes"
else
  # Add a trailing space for regexp search.
  targets="${targets} "
fi

if [ "$enable_cosim" == "yes" ]; then
  targets="harmonizer harmonizerdll bpsdll"
fi

# Install script help.
if [ $help -eq 1 ]; then
  echo " "
  echo " Usage: ./Install [OPTIONS] [NAME]"
  echo " "
  echo " This script will install all or parts of ESP-r"
  echo " on your computer. A complete default installation"
  echo " is typically achieved by executing the script with"
  echo " no arguments:"
  echo " "
  echo "   $ ./Install"
  echo " "
  echo " Alternatively, command line arguments can be used"
  echo " to control specific aspects; some examples follow."
  echo " "
  echo " To install ESP-r in a directory other than the"
  echo " default (/opt/esp-r):"
  echo " "
  echo "   $ ./Install -d <directory>"
  echo " "
  echo " To build specific executables (bps, prj etc.):"
  echo " "
  echo "   $ ./Install <program list>"
  echo " "
  echo " To build and install in a specific location:"
  echo " "
  echo "   $ ./Install -d <directory> <program list>"
  echo " "
  echo " To install ESP-r in silent mode:"
  echo " "
  echo  "  $ ./Install --silent"
  echo " "
  echo " Command line arguments:"
  echo " "
  echo "    <NAME>"
  echo "           Install one or more named programs"
  echo "           (e.g.'./Install clm')"
  echo " "
  echo "    --compiler-version <STRING>"
  echo "           Append STRING to the default compiler"
  echo "           (e.g. '--compiler_version -4.3')"
  echo " "
  echo "    -d <PATH>, --destination <PATH>"
  echo "           Install ESP-r components in directory PATH"
  echo "           (default is ${DESTdir})."
  echo " "
  echo "    --debug"
  echo "           Include debugging symbols in ESP-r binaries"
  echo "           (preserves object files allowing an executable"
  echo "           to be rapidly rebuilt during development)."
  echo " "
  echo "    --extra-debug"
  echo "           Adds pedantic range checking, floating-point"
  echo "           exception handling and stack dump capabilities"
  echo "           (supported by Intel and gcc compilers)."
  echo " "
  echo "    --quick_rebuild"
  echo "           Preserve object files after running the Install"
  echo "           script to facilitate rapid recompilation in cases"
  echo "           where a limited number of source files are being"
  echo "           modified."
  echo " "
  echo "    --force"
  echo "           Overwrite a corrupted installation."
  echo " "
  echo "    --gcc4"
  echo "           Use the gcc4 or newer compilers (gcc, g++ and gFortran)."
  echo "           (the default)."
  echo " "
  echo "    --opt0"
  echo "           No compiler optimisation"
  echo " "
  echo "    --opt1"
  echo "           -O1 compiler optimisation ~x1.5 speed"
  echo " "
  echo "    --opt2"
  echo "           -O2 compiler optimisation ~x1.7 speed"
  echo " "
  echo "    --opt3"
  echo "           -O3 compiler optimisation ~x1.8 speed"
  echo " "
  echo "    --small"
  echo "           Smallest executable size for computers with"
  echo "           limited memory, e.g. a virtual machine."
  echo " "
  echo "    --medium"
  echo "           Medium executable size (default)."
  echo " "
  echo "    --complex"
  echo "           Large executable size to accommodate complex"
  echo "           models (requires high memory and disk capacity)."
  echo " "
  echo "    -h, --help"
  echo "           Display this help message."
  echo " "
  echo "    --intel"
  echo "           Use the Intel compiler suite (icc,ifort,icpc)."
  echo " "
  echo "    --no-dbs"
  echo "           Skip installation of database."
  echo " "
  echo "    --no-exes"
  echo "           Do not copy executable files to the"
  echo "           installation directory."
  echo " "
  echo "    --no-training"
  echo "           Skip installation of training models."
  echo " "
  echo "    --no-svn-query"
  echo "           Do not query svn for versioning information."
  echo " "
  echo "    --skip-ish-calcs"
  echo "           Skip recalculation of shading files associated"
  echo "           with example and validation models."
  echo " "
  echo "    --reuse_ish_calcs"
  echo "           Convert existing ascii shading files associated"
  echo "           with example and validation models."
  echo " "
  echo "    --silent"
  echo "           Invoke a silent installation using default"
  echo "           options (perhaps replaced by command-line"
  echo "           alternatives)."
  echo " "
  echo "    --X11, --GTK, --noX"
  echo "           Use the specified graphics library."
  echo " "
  echo "    --xml"
  echo "           Compile bps with support for results exporting"
  echo "           in xml and csv formats (requires the GNU libxml2"
  echo "           and libstdc++ libraries)."
  echo " "
  echo "    --SQLite"
  echo "           Compile bps with support for results exporting"
  echo "           to a SQLite database (requires the libsqlite3.so"
  echo "           library)."
  echo " "
  echo "    --FMI"
  echo "           Add Functional Mockup Interface functionality"
  echo "           to prj and bps (the required header files and"
  echo "           libraries must be available - see the FMI"
  echo "           developers guide in doc/manual/FMI/Developers)."
  echo " "
  echo "    --co-sim <PATH>"
  echo "           Compile Harmonizer.exe, Harmonizer.dll and bps.dll"
  echo "           for ESP-r/ TRNSYS co-simulation and install the"
  echo "           executable in PATH (works only under MinGW)."
  echo " "
  echo "    -v, --verbose"
  echo "           Print compilation messages to screen."
  echo " "
  echo "    --platform <OS>"
  echo "           Specify platform operating system (e.g. '--platform Linux')"
  echo " "
  echo " Notes:"
  echo " "
  echo " 1. From ESP-r Version 12.3 on it is not possible to compile"
  echo "    with gcc3/ g77, which are obsolete. Use gcc4/ gFortran."
  echo " "
  echo " 2. There are two flavours of ESP-r: the full distribution"
  echo "    based on X11 graphic libraries and a version based on"
  echo "    GTK graphic libraries that lacks some features."
  exit
fi

# xml support.
if [ "$xml_support" = "yes" ] || [ "$xml_support" = "prompt" ]; then
   if [ ! -d /usr/include/libxml2 ] && [ ! -d /usr/local/include/libxml2 ] && [ ! -d /usr/local/opt/libxml2 ]; then
      xml_support="no"
      xml_libs_found="no"
      if [ "$mode" = "silent" ]; then
         echo " "
         echo "Warning: libxml2 headers not found in /usr/include"
         echo "or /usr/local/include - xml output support disabled."
      fi
   else
    xml_libs_found="yes"
    LIBXML2_INCLUDE="-I/usr/include -I/usr/include/libxml2 -I/usr/local/include/libxml2 -I/usr/include/libxslt -I/local/include/libxslt"
    # xml support may optionally include support for xslt & exslt
    # (following code tested only with GNU ld).
    if [ "${architecture:0:6}" = "CYGWIN" ]; then
        ld_output=`cygcheck -c libxslt | grep libxslt`
    elif [ "${architecture:0:5}" = "MINGW" ] || [ "${architecture:0:4}" = "MSYS" ]; then
        ld_output=`ld -l libxslt`
    else
        ld_output=`ldconfig -p | grep libxslt`
    fi
    case $ld_output in
      "") xsl_libs_available="no";;
      *)  xsl_libs_available="yes";;
    esac
   fi
fi

# SQLite support.
if [ "$SQLite_support" = "yes" ]; then
   if [ "${architecture:0:6}" = "CYGWIN" ]; then
       ld_output=`cygcheck -c libsqlite | grep libsqlite`
   elif [ "${architecture:0:5}" = "MINGW" ] || [ "${architecture:0:4}" = "MSYS" ]; then
       ld_output=`ld -l libsqlite`
   else
       ld_output=`ldconfig -p | grep libsqlite`
   fi
   case $ld_output in 
     "" ) SQLite_libs_found="no"; 
          SQLite_support="no"; 
          if [ "$mode" = "silent" ]; then
             echo " "
             echo "Warning: Library libsqlite3 not found."
             echo "SQLite support disabled."
          fi
          ;;
     *  ) SQLite_libs_found="yes";
          if [ "$xml_support" = "no" ]; then
             SQLite_support="no"
             if [ "$mode" = "silent" ]; then
                echo " "
                echo "Warning: SQLite requires the xml option which"
                echo "has not been enabled. SQLite support disabled."
             fi
          else
            LIBSQLITE3_INCLUDE="-I/usr/lib -lsqlite3"
          fi
          ;;
   esac
fi

# FMI support.
if [ "$FMI_support" = "prompt" ]; then
  found=true 
  if [ ! -f "/usr/lib/libfmilib_shared.so" ]; then
    found=false
    if [ "$mode" = "silent" ]; then
      echo " "
      echo "Warning: FMI library libfmilib_shared.so not"
      echo "found in /usr/lib. FMI support disabled."
    fi
  fi
  if [ ! -d "/usr/include/FMI" ] && 
     [ ! -d "/usr/include/FMI1" ] &&
     [ ! -d "/usr/include/FMI2" ] &&
     [ ! -d "/usr/include/JM" ] &&
     [ ! -f "/usr/include/fmilib.h" ] &&
     [ ! -f "/usr/include/fmilib_config.h" ]; then
    found=false
    if [ "$mode" = "silent" ]; then
      echo " "
      echo "Warning: FMI header files not found in"
      echo "in /usr/include. FMI support disabled."
    fi
  fi
  if $found; then
    FMI_libs_found="yes"
  else
    FMI_libs_found="no"
  fi
elif [ "$FMI_support" = "yes" ]; then
  # Assume FMI library resources are within linker/ compiler paths.
  FMI_libs_found="assume"
fi

# Determine computer architecture.
if [ "$platform" = "auto-detect" ]; then
   if [ "$architecture" != "Linux" ] &&
      [ "$architecture" != "CYGWIN_NT-5.1" ] &&
      [ "$architecture" != "CYGWIN_NT-5.0" ] &&
      [ "$architecture" != "CYGWIN_NT-5.2" ] &&
      [ "$architecture" != "CYGWIN_NT-6.0" ] &&
      [ "$architecture" != "CYGWIN_NT-6.1" ] &&
      [ "$architecture" != "CYGWIN_NT-6.1-WOW64" ] &&
      [ "$architecture" != "CYGWIN_NT-10.0" ] &&
      [ "$architecture" != "MINGW32_NT-5.1" ] &&
      [ "$architecture" != "MINGW32_NT-5.2" ] &&
      [ "$architecture" != "MINGW32_NT-6.1" ] &&
      [ "$architecture" != "MINGW64_NT-6.1" ] &&
      [ "$architecture" != "MINGW64_NT-10.0" ] &&
      [ "$architecture" != "MSYS_NT-6.1" ] &&
      [ "$architecture" != "Darwin" ] &&
      [ "$architecture" != "SunOS" ]; then
      platform="prompt";
      if [ "$mode" = "silent" ]; then
         echo " "
         echo "Error: could not determine computer architecture"
         echo "${architecture}. Specify using the --platform switch"
         echo "or run script in interactive mode."
         exit
       fi
   fi
fi

echo " "
echo "Executing ESP-r installation script."
echo " "
echo "This creates the ESP-r system based on the source files found in"
echo "directory ${HOMEdir}"
echo "and installs the result in directory ${DESTdir}."
echo " "
echo "If you are new to this procedure, please consult"
echo "file ${SRCdir}/Readme before proceeding."
echo " "
echo "Use Install --help to obtain a list of the avaiable options."

# Prompt user for basic options if script is running interactively.
if [ "$mode" = "interactive" ]; then
   echo " "
   echo "Please answer the following questions. Default answers"
   echo "are in []; press return to accept."
   if [ "${platform}" = "auto-detect" ]; then
      YN=none;
      echo " "
      echo "Your computer identifies itself as ${architecture} with"
      echo "${machine} processor. Is this correct (y/n)? [y]"
      while [ "$YN" != "y" ] && [ "$YN" != "n" ] && [ "$YN" != "" ]
      do
         if [ "$YN" != "none" ]; then
            echo " "
            echo "Please answer 'y' or 'n' [y]."
         fi
         read YN
      done
      if [ "$YN" = "n" ]; then
         platform="prompt"  # Ask user.
      fi
   fi
   if [ "${platform}" = "prompt" ]; then
      A=none;
      while [ $A != "1" ] &&
            [ $A != "2" ] &&
            [ $A != "3" ] &&
            [ $A != "4" ] &&
            [ $A != "5" ] &&
            [ $A != "6" ]
      do
         if [ $A != "none" ]; then
            echo " "
            echo "Choose an option from the list."
         fi
         echo " "
         echo "Computer type:"
         echo " (1) Solaris;"
         echo " (2) Linux;"
         echo " (3) Cygwin;"
         echo " (4) MinGW;"
         echo " (5) MacOS X (10.4 or later)."
         read A
         # Use the 'known_host' keyword to permit compilation
         # on frequently used, nonstandard hosts.
         if [ "$A" = "known_host" ]; then
          echo " "
          echo "Host: "
          echo " (1) nrn7 (SunOS)"
          read A
          case $A in
            1) custom_host="nrn7"
               A=1
               mode="silent";;
            *) echo "Error: unknown host."
               exit;;
          esac
         fi
      done
      case "$A" in
         1) platform=sun;;
         2) platform=linux;;
         3) platform=cygwin;;
         4) platform=mingw;;
         5) platform=mac;;
      esac
   fi
fi
if [ "$platform" = "auto-detect" ]; then
   case $architecture in
      Linux)                           platform="linux";;
      CYGWIN_NT-5.2  | CYGWIN_NT-5.1  | CYGWIN_NT-5.0  | CYGWIN_NT-6.0 | CYGWIN_NT-6.1 | CYGWIN_NT-6.1-WOW64 | CYGWIN_NT-10.0 ) platform="cygwin";;
      MINGW64_NT-10.0 | MINGW64_NT-6.1 | MINGW32_NT-6.1 | MINGW32_NT-5.2 | MINGW32_NT-5.1 | MSYS_NT-6.1 ) platform="mingw";;
      Darwin)                          platform="mac";;
      SunOS)                           platform="sun";;
   esac
fi

# If architecture is sun, prompt for compiler; otherwise use the GNU set.
if [ "$mode" = "interactive" ]; then
  if [ "$platform" = "sun" ] || [ "$platform" = "linux" ]; then
    compiler="prompt"
  fi
fi
if [ "$compiler" != "prompt" ]; then
  if [ "$use_intel" = "yes" ]; then
    compiler="intel"
  else
    compiler="GNU"
  fi
fi
if [ "$compiler" = "prompt" ] && [ "$mode" = "interactive" ]; then
  A=none;
  while [ $A != "1" ] &&
        [ $A != "2" ] &&
        [ $A != "3" ]
  do
     if [ $A != "none" ]; then
        echo " "
        echo "Please select a compiler set [2]."
     fi
     echo "Select a compiler set [2]:"
     echo " (1) Sun 90 (cc and f90);"
     echo " (2) GNU (gcc 4.X and gfortran);"
     echo " (3) Intel (icc, icpc and ifort)."
     read A
     if [ "$A" = "" ]; then
       A="2"
     fi
  done
  case "$A" in
     1) compiler=sunF90;;
     2) compiler=GNU;;
     3) compiler=intel;;
  esac
else
  echo " "
  echo "The $compiler compiler set will be used."
fi

# Prompt for inclusion of H3K reports (in xml output)
# on supported platforms (presently linux, cygwin and mingw).
if [ "$mode" = "interactive" ]; then
   if [ "$platform" = "linux" ]  ||
      [ "$platform" = "cygwin" ] ||
      [ "$platform" = "mingw" ]  ||
      [ "$platform" = "mac" ]  ||
      [ "$platform" = "sun" ] ; then
      if [ "${xml_libs_found}" = "no" ]; then
         echo " "
         echo "Error: libxml2 library not found in /usr/include"
         echo "or /usr/local/include. Support for xml output will be"
         echo "disabled but the rest of the installation will"
         echo "proceed normally."
      else
        case "${xml_support}" in
          yes) echo "xml support included.";;
          no)  echo "xml support not included.";;
        esac
      fi
   else
       echo " "
       echo "xml output support not available on ${platform}"
       echo "and is therefore disabled."
       xml_support="no"
       SQLite_support="no"
   fi
else
  if [ "$xml_support" = "prompt" ]; then
    xml_support="no"
    SQLite_support="no"
  fi
fi

# FMI support.
if [ "$mode" = "interactive" ]; then
  if [ "${FMI_libs_found}" = "no" ]; then
    echo " "
    echo "FMI library resources could not be located. Please"
    echo "follow instructions in manual/FMI/Users.txt. FMI"
    echo "will be disabled but the rest of the installation"
    echo "will proceed normally."
    echo
    FMI_support="no"
  elif [ "${FMI_libs_found}" = "yes" ]; then
    if ! [ "$platform" = "linux" ] && 
       ! [ "$machine" = "x86_64" ] &&
       ! [ "$machine" = "i386" ] &&
       ! [ "$machine" = "i686" ]; then
      echo " "
      echo "FMI not supported on $platform $machine."
      echo "Only advanced users should proceed with"
      echo "FMI enabled."
      echo 
    fi
    if [ "$FMI_support" = "prompt" ]; then
      B="none"
      while [ "$B" != "y" ] && [ "$B" != "n" ] && [ "$B" != "Y" ] && [ "$B" != "N" ]
      do
        if [ "$B" != "none" ]; then
          echo " "
          echo "Please answer 'y' or 'n'."
        fi
        echo " "
        echo "Include FMI support (y/n)? [n]"
        read B
        if [ "$B" = "" ]; then
          case "${FMI_support}" in
            yes) B="y";;
            *)   B="n";;
          esac
        fi
      done
      if [ "$B" = "y" ]; then
        FMI_support="yes"
        echo " "
        echo "FMI enabled."
      else
        FMI_support="no"
        echo " "
        echo "FMI disabled."
      fi
    fi
  elif [ "${FMI_libs_found}" = "assume" ]; then
    echo
    echo "FMI headers and library are assumed to be"
    echo "within the compiler/ linker paths. No checks"
    echo "will be made for these resources before"
    echo "compiling with FMI support enabled."
  fi
else
  if [ "$FMI_support" = "prompt" ]; then
    FMI_support="no"
  fi
fi

# Graphics libraries
if [ "$mode" = "interactive" ]; then
  case "${xLibs}" in
     X11) echo " "
          echo "Building with X11 interface.";;
     GTK) echo " "
          echo "Building with GTK interface.";;
     noX) echo " "
          echo "Building with text only interface.";;
  esac
else
  # Assume X11 is available on all systems except mingw.
  if [ "$platform" = "mingw" ]; then
    xLibs=noX
    echo " "
    echo "Text only applications will be compiled."
  else
    echo " "
    echo "The $xLibs libraries will be used."
  fi
fi
# Prepend grapics library to target list.
case $xLibs in
  X11) targets=" libX11 $targets";;
  GTK) targets=" libGTK $targets";;
  noX) targets=" libnoX $targets";;
esac

# Level of model complexity supported.
small_prompt="1"
medium_prompt="2"
large_prompt="3"
default="$medium_prompt"

case "$complexity" in
   "$small_prompt") 
     cp ${SRCdir}/include/building_small.h ${SRCdir}/include/building.h
     ;;
   "$medium_prompt") 
     cp ${SRCdir}/include/building_medium.h ${SRCdir}/include/building.h
     ;;
   "$large_prompt") 
     cp ${SRCdir}/include/building_large.h ${SRCdir}/include/building.h
     ;;
esac

# Debugging symbols required?
if [ "$mode" = "interactive" ]; then
  case "${debugging}" in
    yes) echo " "
         echo "Building with debug symbols.";;
    no)  echo " "
         echo "Building without debug symbols.";;
  esac

# Installation of databases required?
  B="none"
  while [ "$B" != "y" ] && [ "$B" != "n" ] && [ "$B" != "Y" ] && [ "$B" != "N" ]
  do
    if [ "$B" != "none" ]; then
        echo " "
        echo "Please answer 'y' or 'n'."
    fi
    case "${install_dbs}" in
      yes) echo " "
           echo "Install databases (y/n)? [y]";;
      *)   echo " "
           echo "Install databases (y/n)? [n]";;
    esac
    read B
    if [ "$B" = "" ]; then
      case "${install_dbs}" in
        yes) B="y";;
        *)   B="n";;
      esac
    fi
  done
  if [ "$B" = "y" ] || [ "$B" = "Y" ]; then
    install_dbs="yes"
  else
    install_dbs="no"
  fi

# Install training models?
  B="none"
  while [ "$B" != "y" ] && [ "$B" != "n" ] && [ "$B" != "Y" ] && [ "$B" != "N" ]
  do
    if [ "$B" != "none" ]; then
        echo ""
        echo "Please answer 'y' or 'n'."
    fi
    case "${install_training}" in
      yes) echo "Install training models (y/n)? [y]";;
      *)   echo "Install training models (y/n)? [n]";;
    esac
    read B
    if [ "$B" = "" ]; then
      case "${install_training}" in
        yes) B="y";;
        *)   B="n";;
      esac
    fi
  done
  if [ "$B" = "y" ] || [ "$B" = "Y" ]; then
    install_training="yes"
  else
    install_training="no"
  fi
fi

if [ "$debugging" = "yes" ]; then
    debug_flag="-g"
else
    debug_flag=" "
fi

# Header files.
LOCAL_INCLUDES="-I../include -I../shocc -I/usr/local/include -I../cetc/h3kreports"

# Architecture types.
case $platform in
   sun)      MCTYPE=sun ;;
   linux)    MCTYPE=lin ;;
   cygwin)   MCTYPE=cygw;;
   mac)      MCTYPE=osx ;;
   mingw)    MCTYPE=mingw ;;
# Custom hosts follow:
   nrn7)     MCTYPE=sun;;
esac

# Location of X libraries.
case $xLibs in
  GTK) XINSTALLDIR="`pkg-config gtk+-2.0 --cflags --libs`";;
  X11) X11_found="no"
       case $platform in
         sun)
            XDEFDIR="/usr/openwin"
            if [ -d /usr/openwin/lib/X11 ]; then
               X11_found="yes"
               XINSTALLDIR="/usr/openwin"
            fi
            ;;
         *)
            # linux/mac/cygwin/arm: search for the X11 libraries.
            XDEFDIR="/usr/X11R6 or /usr"
            # Try /usr/X11R6
            case $machine in
              x86_64)
                case $platform in
                  mac) if [ -d /usr/X11R6/lib/X11 ] ; then
                         X11_found="yes"
                         XINSTALLDIR="/usr/X11R6"
                       else
                         if [ -d /opt/X11/lib/X11 ] ; then
                           X11_found="yes"
                           XINSTALLDIR="/opt/X11"
                         fi
                    fi;;
                  *) if [ -d /usr/X11R6/lib64/X11 ] ; then
                       X11_found="yes"
                       XINSTALLDIR="/usr/X11R6"
                     else
                       if [ -d /usr/lib64/X11 ] ; then
                         X11_found="yes"
                         XINSTALLDIR="/usr/lib64"
                       fi
                     fi;;
                esac;;
              sun4u)
                if [ -d /usr/X11R6/lib/64 ] ; then
                  X11_found="yes"
                  XINSTALLDIR="/usr/X11R6"
                fi;;
              armv6l)
                if [ -d /usr/lib/arm-linux-gnueabihf ] ; then
                  X11_found="yes"
                  XINSTALLDIR="/usr/lib/arm-linux-gnueabihf"
                fi;;
              armv7l)
                if [ -d /usr/lib/X11 ] ; then
                  X11_found="yes"
                  XINSTALLDIR="/usr/lib/X11"
                fi;;
              aarch64)
                if [ -d /usr/lib/X11 ] ; then
                  X11_found="yes"
                  XINSTALLDIR="/usr/lib/X11"
                fi;;
              arm64)
                case $platform in
                  mac) if [ -d /usr/X11R6/lib/X11 ] ; then
                         X11_found="yes"
                         XINSTALLDIR="/usr/X11R6"
                       else
                         if [ -d /opt/X11/lib/X11 ] ; then
                           X11_found="yes"
                           XINSTALLDIR="/opt/X11"
                         fi
                    fi;;
                  *) if [ -d /usr/X11R6/lib64/X11 ] ; then
                       X11_found="yes"
                       XINSTALLDIR="/usr/X11R6"
                     else
                       if [ -d /usr/lib64/X11 ] ; then
                         X11_found="yes"
                         XINSTALLDIR="/usr/lib64"
                       fi
                     fi;;
                esac;;
              *)
                if [ -d /usr/X11R6/lib/X11 ] ; then
                  X11_found="yes"
                  XINSTALLDIR="/usr/X11R6"
                fi;;
            esac

            # Try /usr
            if [ -d /usr/lib/X11 ] && [ "$X11_found" = "no" ]; then
              X11_found="yes"
              XINSTALLDIR="/usr"
            fi
            if [ -d /usr/lib64/X11 ] && [ "$X11_found" = "no" ]; then
              X11_found="yes"
              XINSTALLDIR="/usr/lib64"
            fi
         ;;
       esac
       # If X11 not found, ask user for location.
       if [ "$X11_found" = "no" ] && [ "$mode" = "interactive" ]; then
         echo " "
         echo "X11 libraries not found in ($XDEFDIR)."
         try_agian="y"
         while [ "$try_agian" == "y" ] || [ "$try_agian" == "Y" ]
         do
           echo "Search for the X11 libraries at"
           echo "an alternative location?"
           read try_again
           if [ "$try_agian" = "" ]; then
             try_again="y"
           fi
           if [ "$try_again" = "y" ] || [ "$try_agian" = "Y" ]; then
             echo " Location of X11 installation?"
             read XINSTALLDIR
             if [ -d $XINSTALLDIR/lib/X11 ]; then
               echo " X11 was found at $XINSTALLDIR."
               X11_found="yes"
               try_agian="no"
             else
               echo "X11 libraries not found in $XINSTALLDIR!"
             fi
           fi
         done
       fi
       # If X11 not found, issue an error and quit.
       if [ "$X11_found" = "no" ]; then
         echo " "
         echo "Error: X11 libraries not found ... exiting."
         echo " "
         exit
       fi
       # Check if the required include files are installed.
       if [ -r $XINSTALLDIR/include/X11/X.h ]; then
         X11INCLUDEDIR=$XINSTALLDIR/include
       else
         if [ -r /usr/include/X11/X.h ]; then
           X11INCLUDEDIR=/usr/include
         else
           echo " "
           echo "Error: the X11 libraries were found at $XINSTALLDIR but"
           echo "the corresponding header files (e.g. X.h) could not be"
           echo "located at $XINSTALLDIR/include/X11. Please check if"
           echo "the X11 development package is installed (usually called"
           echo "xfree86-devel, xorg-X11-devel or libX11-devel.)"
           exit
         fi
       fi
     ;;
  noX) XINSTALLDIR="";;
esac

# Assign compilers.
case $compiler in
   sunF90)   CC=cc;  CPL=CC;  FC=f90  ;;
   GNU) case $gnu_version in
           gcc4)     CC=gcc;   CPL=g++;    FC=gfortran  ;;
        esac;;
   intel)    CC=icc;  CPL=icpc;  FC=ifort ;;
esac
if [ "$compiler_version" != "none" ]; then
  CC="$CC$compiler_version"
  CPL="$CPL$compiler_version"
  FC="$FC$compiler_version"
fi

# Extended debugging.
ExtendedDebugFlags=""
if [ "$extendedDebugging" == "yes" ]; then
  case $compiler in
    sunF90) ExtendedDebugFlags="$ExtendedDebugFlags";;
    GNU) case $gnu_version in
            gcc4)     ExtendedDebugFlags="$ExtendedDebugFlags -fbounds-check -Wunderflow -Wconversion -frange-check -ffpe-trap=zero,invalid,overflow,underflow"  ;;
          esac;;
    intel)  ExtendedDebugFlags="$ExtendedDebugFlags -debug all -C -fp-stack-check -traceback -inline-debug-info -fpe0 "  ;;
  esac
fi

# Assign wwlink variable.
case $compiler in
   sunF90)   WWLINK="shared_solaris" ;;
   GNU)      WWLINK="unshared"       ;;
esac

# FFLAGS: Establish platform specific ifdef variables for inserted into
# Fortran compiler flags (for OSX 10.6 and x86_64 force -m64 otherwise -m32).
case $platform in
   sun) case $machine in
          sun4u)   fDefType="-DSUN -DOSI";;
          i86PC)   fDefType="-DSUN";;
          i386)    fDefType="-DSUN";;
        esac;;
   linux) case $machine in
          i386)    fDefType="-DLIN";;
          i686)    fDefType="-DLIN";;
          x86_64)  fDefType="-DLIN";;
          armv6l)  fDefType="-DLIN";;
          armv7l)  fDefType="-DLIN";;
          aarch64)  fDefType="-DLIN";;
        esac;;
   cygwin)     fDefType="-DCYGW";;
   mac) case $machine in
          i386)    fDefType="-DOSX -DOSI -DLIN -m32";;
          x86_64)  fDefType="-DOSX -DLIN -m64";;
          arm64)   fDefType="-DOSX -DLIN -DM1 -m64";;
        esac;;
   mingw)      fDefType="-DMINGW";;
esac

# Append -DX11 flag as necessary
if [ "$xLibs" = "X11" ]; then
  fDefType="$fDefType -DX11"
fi
if [ "$xLibs" = "GTK" ]; then
  fDefType="$fDefType -DGTK"
fi
# Append optimization flag as necessary
if [ "$opt" = "-O0" ]; then
  fDefType="$fDefType -O0"
fi
if [ "$opt" = "-O1" ]; then
  fDefType="$fDefType -O1"
fi
if [ "$opt" = "-O2" ]; then
  fDefType="$fDefType -O2"
fi
if [ "$opt" = "-O3" ]; then
  fDefType="$fDefType -O3"
fi

# Assign Fortran compilation flags.
case $compiler in
   # Note '-C' flag causes grief on older sun F90 compilers.
   sunF90) FFLAGS="$LOCAL_INCLUDES $fDefType -DF90 $debug_flag $ExtendedDebugFlags -C " ;;
   GNU)    FFLAGS="$LOCAL_INCLUDES $fDefType $debug_flag $ExtendedDebugFlags -fno-automatic";
# mcmodel=medium (needed for larger data structures) is only available on 64-bit machines.
           if [ "$machine" = "x86_64" ]; then
             if [ "$complexity" = "$medium_prompt" ]; then 
               FFLAGS="$FFLAGS -mcmodel=medium"
             elif [ "$complexity" = "$large_prompt" ]; then 
               FFLAGS="$FFLAGS -mcmodel=medium"
             fi
           fi
           case $gnu_version in
             gcc4) FFLAGS="$FFLAGS -DGCC4"            ;;
           esac ;;
   intel) FFLAGS="$LOCAL_INCLUDES $fDefType -save -zero -assume byterecl $debug_flag $ExtendedDebugFlags -O0" ;;
esac

if [ "$platform" = "mingw" ] && [ "$xLibs" = "GTK" ]; then
   FFLAGS="$FFLAGS -mwindows -mms-bitfields"
fi

if [ "$enable_cosim" == "yes" ] && [ "$platform" == "mingw" ]; then
   FFLAGS="$FFLAGS -fcray-pointer -mrtd"
fi

# CFLAGS: set up paths to c/c++ include files and append X11 include path.
case $xLibs in
  X11)  cINCLUDES="$LOCAL_INCLUDES -I$X11INCLUDEDIR -I$X11INCLUDEDIR/freetype2";;
  *)    cINCLUDES="$LOCAL_INCLUDES";;
esac

# Append XML include paths if needed.
case $xml_support in
  yes)  cINCLUDES="$cINCLUDES $LIBXML2_INCLUDE";;
  no)   cINCLUDES="$cINCLUDES";;
esac

# Append SQLite include path if needed.
case $SQLite_support in
  yes)  cINCLUDES="$cINCLUDES $LIBSQLITE3_INCLUDE";;
  no)   cINCLUDES="$cINCLUDES";;
esac

# Assign c/c++ IDFEF flags.
cDefType="$fDefType"

# Set xsl ifdef flag depending on whether xslt libraries are available
# and XML support is active.
if [ "$xml_support" = "yes" ] && [ "$xsl_libs_available" = "yes" ]; then
  cDefType="$cDefType -DXSL"
fi

# Set SQLite ifdef flag depending on whether sqlite libraries are available
# and XML support is active.
if [ "$xml_support" = "yes" ] && [ "$SQLite_support" = "yes" ]; then
  cDefType="$cDefType -DSQLITE"
fi

# Set c compilation flags.
case $compiler in
   sunF90)  CFLAGS="$cINCLUDES $cDefType $debug_flag $ExtendedDebugFlags";;
   GNU)     CFLAGS="$cINCLUDES $cDefType $debug_flag $ExtendedDebugFlags";;
   intel)     CFLAGS="$cINCLUDES $cDefType -save -zero $debug_flag $ExtendedDebugFlags";;
esac

# Add '-mms-bitfields' and '-mwindows' on Mingw+GTK
if [ "$platform" = "mingw" ] && [ "$xLibs" = "GTK" ]; then
   CFLAGS="$CFLAGS -mwindows -mms-bitfields"
fi

# ULIBS: Assign library paths.
case $platform in
   sun)      ULIBS="-L${SRCdir}/lib ";;
   linux)    ULIBS="-L${SRCdir}/lib ";;
   cygwin)   ULIBS="-L${SRCdir}/lib ";;
   mac)      ULIBS="-L${SRCdir}/lib ";;
   mingw)    ULIBS="-L${SRCdir}/lib -L/usr/local/lib -L/local/lib -L/usr/lib";;
esac

# Append versioning information library.
ULIBS="$ULIBS -lversion"

# Append X11 library paths to ULIBS (for OSX 10.6 and x86_64 look
# in lib rather than lib64.
case $xLibs in
  X11) case $machine in
         sun4u) ULIBS="$ULIBS -lxesru -L${XINSTALLDIR}/lib -lX11 -lXft";;
         i386) ULIBS="$ULIBS -lxesru -L${XINSTALLDIR}/lib -lX11 -lXft";;
         i86pc) ULIBS="$ULIBS -lxesru -L${XINSTALLDIR}/lib -lX11 -lXft";;
         i686) ULIBS="$ULIBS -lxesru -L${XINSTALLDIR}/lib -lX11 -lXft";;
         armv6l) ULIBS="$ULIBS -lxesru -L${XINSTALLDIR} -lX11 -lXft";;
         armv7l) ULIBS="$ULIBS -lxesru -L${XINSTALLDIR} -lX11 -lXft";;
         aarch64) ULIBS="$ULIBS -lxesru -L${XINSTALLDIR} -lX11 -lXft";;
         arm64) ULIBS="$ULIBS -lxesru -L${XINSTALLDIR}/lib -lX11 -lXft";;
         x86_64) case $platform in
                 mac) ULIBS="$ULIBS -lxesru -L${XINSTALLDIR}/lib -lX11 -lXft";;
                 *) ULIBS="$ULIBS -lxesru -L${XINSTALLDIR}/lib64 -lX11 -lXft";;        
                 esac;;
       esac;;
  GTK) ULIBS="$ULIBS -lgtkesru -L${XINSTALLDIR}";;
  noX) ULIBS="$ULIBS -lnoxesru";;
esac

# Append XML output libraries (libxml2 and libstdc++) to ULIBS if required. 
case $xml_support in
  yes)
       case $compiler in
         sunF90)  ULIBS="$ULIBS -lXML -lCstd";;
         GNU)     ULIBS="$ULIBS -lXML -lstdc++";;
         intel)   ULIBS="$ULIBS -lXML -lstdc++";;
       esac;
       case $xsl_libs_available in
         "yes") ULIBS="$ULIBS -lxslt";;
         "no")  ULIBS="$ULIBS ";;
         esac;

       # Link to libxml2 must follow -lxslt for cygwin/mingw.
       ULIBS="$ULIBS -lxml2";

       case $platform in
            mingw)    ULIBS="$ULIBS -lws2_32";;
            sun)    ULIBS="$ULIBS -lCrun";;
            *)        ULIBS="$ULIBS";;
       esac;
       targets="enableXML $targets";;
  no)  ULIBS="$ULIBS -lXML ";
       targets="disableXML $targets";;
esac

# Append SQLite database library (libsqlite3) to ULIBS if required.
case $SQLite_support in
  yes)
       case $compiler in
         sunF90)  ULIBS="$ULIBS -L/usr/local/lib -lSQLite -lsqlite3 -lCstd";;
         GNU)     ULIBS="$ULIBS -L/usr/local/lib -lSQLite -lsqlite3 -lstdc++";;
         intel)   ULIBS="$ULIBS -L/usr/local/lib -lSQLite -lsqlite3 -lstdc++";;
       esac;
       case $platform in
            mingw)    ULIBS="$ULIBS -lws2_32";;
            sun)    ULIBS="$ULIBS -lCrun";;
            *)        ULIBS="$ULIBS";;
       esac;
       targets="enableSQLite $targets";;
  no)  ULIBS="$ULIBS -lSQLite ";
       targets="disableSQLite $targets";;
esac

# Append FMI library if required (currently only tested with GNU compilers).
case $FMI_support in
  yes)
    case $compiler in
      sunF90)  ULIBS="$ULIBS -Wl,--no-as-needed -lCstd -lfmilib_shared";;
      GNU)     ULIBS="$ULIBS -Wl,--no-as-needed -lstdc++ -lfmilib_shared ";;
      intel)   ULIBS="$ULIBS -Wl,--no-as-needed -lstdc++ -lfmilib_shared ";;
    esac;
    FMIarg="enableFMI";;
  no)
    FMIarg="disableFMI";;
esac

# LDFLAGS: Directives for the link-loader (ld). The reduce-memory-overheads
# speeds up linking if machine memory is limited with little impact otherwise.
case $platform in
   mingw)    LD_FLAGS="-DMINGW -Wl,--reduce-memory-overheads";;
   mac)      LD_FLAGS="";;
   *)  case $machine in
      armv6l) LD_FLAGS="-Wl,--reduce-memory-overheads";;
      armv7l) LD_FLAGS="-Wl,--reduce-memory-overheads";;
      aarch64) LD_FLAGS="-Wl,--reduce-memory-overheads";;
      arm64) LD_FLAGS="-Wl,--reduce-memory-overheads";;
      *)      LD_FLAGS="-Wl,--reduce-memory-overheads";;
      esac;;
esac
    if [ "$enable_cosim" == "yes" ] ; then
       LD_FLAGS="-DMINGW -shared";
    fi

# EXE: Set exe file extention.
case $platform in
   sun)      EXE="";;
   linux)    EXE="";;
   cygwin)   EXE=".exe";;
   mac)      EXE="";;
   mingw)    EXE=".exe";;
   nrn7)     EXE="" ;;
esac
if [ "$enable_cosim" == "yes" ] && [ "$platform" == "mingw" ]; then
   EXE=".dll"
fi

# Create ESP-r installation directory tree.
create_espr_dir="no"
# Does top-level installation directory exist?
if [ ! -d $DESTdir ]; then
  # No! Is script running interactively or has user specified a 'force?'
  if [ $mode = "interactive" ] && [ "$preserve_espr_dir" == "yes" ] ; then
    echo " "
    echo "Installation directory ${DESTdir} does not exist."
    A=none
    while [ "$A" != "y" ] && [ "$A" != "n" ]
    do
      echo " "
      echo "Do you wish to create it (y/n)? [y]"
      read A
      if [ "$A" = "" ]; then
        A="y"
      fi
    done
    if [ "$A" = "n" ]; then
      create_espr_dir="no"
    else
      create_espr_dir="yes"
      preserve_espr_dir="no"
    fi
  else
    create_espr_dir="yes"
    preserve_espr_dir="no"
  fi
  if [ "$create_espr_dir" = "yes" ]; then
    # Attempt to create directory
    mkdir ${DESTdir}
    if [ ! -d ${DESTdir} ]; then
      # User may not have write permissions, warn and exit.
      echo " "
      echo "Destination directory ${DESTdir} could not be"
      echo "created ... installation aborted."
      exit
    fi
  else
    # User does not want to create directory and it does not exist.
    echo " "
    echo "Destination directory ${DESTdir} does not exist ..."
    echo "installation aborted."
    exit
  fi
fi

# Confirm installation directory is writable.
if [ ! -w $DESTdir ] || [ ! -d $DESTdir ]; then
  echo " "
  echo "Cannot write to installation directory $DESTdir ..."
  echo "installation aborted."
  exit
fi

# Co-simulation directory.
if [ "$enable_cosim" == "yes" ]; then
	# If co-simulation installation directory not specified
	# set it to the ESP-r installation directory.
	if [ $COSIMdir == " " ]; then
	    ${COSIMdir} = ${DESTdir}/bin 
	    echo "Co-simulation directory is ${DESTdir}."
	fi
	# Check if co-simulation installation directories exists and
        # create it if necessary.
	create_harmonizer_dir="no"
	if [ ! -d $COSIMdir ]; then
	  if [ $mode = "interactive" ] ; then
	    echo " "
	    echo "Co-simulation installation directory"
            echo "${COSIMdir} does not exist."
	    A=none
	    while [ "$A" != "y" ] && [ "$A" != "n" ]
	    do
	      echo " "
	      echo "Do you wish to create it (y/n)? [y]"
	      read A
	      if [ "$A" = "" ]; then
	        A="y"
	      fi
	    done
	    if [ "$A" = "n" ]; then
	      create_harmonizer_dir="no"
	    else
	      create_harmonizer_dir="yes"
	      preserve_harmonizer_dir="no"
	    fi
	  else
	    create_espr_dir="yes"
	    preserve_espr_dir="no"
	  fi
	  if [ "$create_harmonizer_dir" = "yes" ]; then
            # Create directory
	    mkdir ${COSIMdir}
	    if [ ! -d ${COSIMdir} ]; then
	      # User may not have write permission.
	      echo " "
	      echo "Destination directory ${COSIMdir} could not"
	      echo "be created ... installation aborted."
	      exit
	    fi
	  else
	    # User does not want to create directory and it does not exist.
	    echo " "
	    echo "Destination directory ${COSIMdir} does not"
	    echo "exist ... installation aborted."
	    exit
	  fi
	fi
	if [ ! -w $COSIMdir ] || [ ! -d $COSIMdir ]; then
	  echo " "
	  echo "Cannot write to co-simulation installation directory"
	  echo "${COSIMdir} ... installation aborted."
	  exit
	fi
fi

# Check if ESP-r installation directory tree exists.
# Strip trailing space from DESTdir.
DESTdir=`echo "$DESTdir" | sed "s/\/$//"`

ESPbin=${ESPdir}/bin
ESPBinDir=${ESPdir}/bin
corrupted_tree="no"
if [ "$create_espr_dir" = "no" ]; then
  if [ ! -d $ESPdir ]                   ||
     [ ! -d $ESPdir/bin ]               ||
     [ ! -d $ESPdir/climate ]           ||
     [ ! -d $ESPdir/databases ]         ||
     [ ! -d $ESPdir/electric_loads ]    ||
     [ ! -d $ESPdir/lib ]               ||
     [ ! -d $ESPdir/manual ]            ||
     [ ! -d $ESPdir/xsl ]; then

     # ESP-r directory tree does not exist, or has been corrupted.
     corrupted_tree="yes"
     if [ "$create_espr_dir" = "no" ]; then
      echo " "
      echo "The ESP-r installation directory tree does not exist at"
      echo "${DESTdir} or may have been corrupted. The following directories"
      echo "are required."
      echo "   $ESPdir"
      echo "   $ESPdir/bin "
      echo "   $ESPdir/climate "
      echo "   $ESPdir/databases "
      echo "   $ESPdir/electric_loads "
      echo "   $ESPdir/lib "
      echo "   $ESPdir/manual "
      echo "   $ESPdir/xsl "
    fi

    if [ "$mode" = "interactive" ] && [ "$preserve_espr_dir" = "yes" ] ; then
      A=none
      while [ "$A" != "y" ] && [ "$A" != "n" ]
      do
        echo " "
        echo "Create this directory tree (y/n)? [y]"
        read A
        if [ "$A" = "" ]; then
          A="y"
        fi
      done
      if [ "$A" = "y" ]; then
        preserve_espr_dir="no"
      else
        preserve_espr_dir="yes"
      fi
    fi
  fi
fi

# Now create installation directory tree if necessary.
if [ "$corrupted_tree" = "yes" ] || [ "$create_espr_dir" = "yes" ]; then
  if [ "$preserve_espr_dir" = "yes" ]; then
    echo " "
    echo " Installation error: cannot overwrite ESP-r installation"
    echo " directory tree at ${DESTdir}. Installation aborted."
    if [ "$mode" = "silent" ]; then
      echo " "
      echo "Use the '--force' option to overwrite the directory"
      echo "structure. Run 'Install --help' for more information."
      exit
    fi
  fi
  rm -rf $ESPdir
  mkdir $ESPdir
  mkdir $ESPdir/bin
  mkdir $ESPdir/climate
  mkdir $ESPdir/databases
  mkdir $ESPdir/electric_loads
  mkdir $ESPdir/lib
  mkdir $ESPdir/manual
  mkdir $ESPdir/xsl
fi

# Create an installdir.h file so startup.F knows where to look.
  echo "c this is where esp-r is installed" 	> ${SRCdir}/include/espinstalldir.h
  echo "       character instpath*60" 		>> ${SRCdir}/include/espinstalldir.h
  echo "       instpath = " 			>> ${SRCdir}/include/espinstalldir.h
  echo "     & '${ESPdir}'" 			>> ${SRCdir}/include/espinstalldir.h

# Initiate make.
if [ "${make_msg_file}" = "" ]; then
  echo " "
  echo "Intended shell command:"
  echo "make MCTYPE=${MCTYPE} MCC=${CC} MCPL=${CPL} MFC=${FC} DESTdir=${DESTdir} ESPdir=${ESPdir} ESPBinDir=${ESPBinDir} WWLINK=${WWLINK} EXE="${EXE}" XINSTALLDIR=${XINSTALLDIR} CFLAGS=${CFLAGS} FFLAGS=${FFLAGS} LD_FLAGS=${LD_FLAGS} ULIBS=${ULIBS} xml_status=${xml_status} $targets"
  echo " "
  echo "where the $xlibs libraries are in ${XINSTALLDIR}."
fi

if [ "$mode" = "interactive" ]; then
  A=x
  while [ "$A" != y ] && [ "$A" != n ] && [ "$A" != "" ]
  do
    echo "Proceed with installation (y/n)? [y]"
    read A
  done
  if [ "$A" = "n" ]; then
    echo " "
    echo "Aborting ESP-r installation."
    exit
  fi
fi
cd ${SRCdir} 
# Establish if this is a copy from svn or git.  
NotAnSvnWorkingCopy=`svn info 2>&1 | grep "is not a working copy"`
NotAGitRepo=`git status 2>&1 | grep "fatal: Not a git repository"`
 
#echo "> SVN query > ${NotAnSvnWorkingCopy} <" 
#echo "> GIT query > ${NotAGitRepo} <"
 
if [ "${NotAnSvnWorkingCopy}" != "" ] && 
   [ "${NotAGitRepo}"         != "" ] ; then 
   VersioningScheme="none" 
else
  if [ "${NotAnSvnWorkingCopy}" == "" ]; then 
    VersioningScheme="svn"
  else 
    VersioningScheme="git"
  fi 
fi    
 
#echo -n "${VersioningScheme}) ..."
 
# Ensure that build information is always recompiled into
# every binary - touch common file version.F.
touch ${SRCdir}/lib/version.F >/dev/null 2>&1

# Time of build
time=`date`

# System information.
architecture=`uname -m`
system=`uname -s`
os_flavour=`uname -r`
host=`uname -n`

# Copy version information to Version text file.
release=`cat ${HOMEdir}/Version | grep "ESP-r " | sed "s/ESP-r //g"`
echo " Installing components of ESP-r version ${release}"
echo " to ${DESTdir} from source in ${SRCdir}."
if [ "${VersioningScheme}" == "svn" ]; then 
    versioned_repository="yes"
    revision_number=`svn info 2>&1 | grep "Revision:"` 
fi
if [ "${VersioningScheme}" == "git" ]; then
    versioned_repository="yes"
fi 

# Write build information to header file.
echo "C      build_info.h"                                              >  ${SRCdir}/include/build_info.h
echo "C      "                                                          >> ${SRCdir}/include/build_info.h
echo "C      This file contains versioning and build information"       >> ${SRCdir}/include/build_info.h
echo "C      for the ESP-r system. It is generated automatically"       >> ${SRCdir}/include/build_info.h
echo "C      by the Install script each time ESP-r is recompiled."      >> ${SRCdir}/include/build_info.h
echo "C      Changes should be made in the Install scipt and not"       >> ${SRCdir}/include/build_info.h
echo "C      not in this file"                                          >> ${SRCdir}/include/build_info.h
echo "C      "                                                          >> ${SRCdir}/include/build_info.h
echo "C      The following Fortran variable assignments are used"       >> ${SRCdir}/include/build_info.h
echo "C      by ESPrVersion() in common/Startup.F"                      >> ${SRCdir}/include/build_info.h
echo "       "                                                          >> ${SRCdir}/include/build_info.h
echo "       logical  bRelease,bVersioned,bModified"                    >> ${SRCdir}/include/build_info.h
echo "       character cBuilder*32       ! User who compiled system"    >> ${SRCdir}/include/build_info.h
echo "       character cArchitecture*32  ! Machine architecture"        >> ${SRCdir}/include/build_info.h
echo "       character cOperSystem*32    ! Operating system"            >> ${SRCdir}/include/build_info.h
echo "       character cOSversion*32     ! Operating system version"    >> ${SRCdir}/include/build_info.h
echo "       character cHost*256         ! Host name"                   >> ${SRCdir}/include/build_info.h
echo "       character cRelease_Num*30   ! Release version"             >> ${SRCdir}/include/build_info.h
echo "       character cSource*32        ! Repository version"          >> ${SRCdir}/include/build_info.h
echo "       character cBranch*48        ! Branch name"                 >> ${SRCdir}/include/build_info.h
echo "       character cRevision*32      ! Revision number"             >> ${SRCdir}/include/build_info.h
echo "       character cState*32         ! Flag for repository state"   >> ${SRCdir}/include/build_info.h
echo "       character cCC*32            ! Flags for C compiler"        >> ${SRCdir}/include/build_info.h
echo "       character cFC*32            ! Flags for Fortran compiler"  >> ${SRCdir}/include/build_info.h
echo "       character cCPL*32           ! Flags for C++ compiler"      >> ${SRCdir}/include/build_info.h
echo "       character cXML_support*32   ! XML compile-time options"    >> ${SRCdir}/include/build_info.h
echo "       character cSQLite_support*32! SQLite compile-time options" >> ${SRCdir}/include/build_info.h
echo "       character cXlibrary*32      ! X11 library location"        >> ${SRCdir}/include/build_info.h
echo "       "                                                          >> ${SRCdir}/include/build_info.h
echo "       cBuilder          = \"${USER}\" "                          >> ${SRCdir}/include/build_info.h
echo "       cHost             = \"${host}\""                           >> ${SRCdir}/include/build_info.h
echo "       cArchitecture     = \"${architecture}\""                   >> ${SRCdir}/include/build_info.h
echo "       cOperSystem       = \"${system}\""                         >> ${SRCdir}/include/build_info.h
echo "       cOSversion        = \"${os_flavour}\""                     >> ${SRCdir}/include/build_info.h

# Set flag indicating if this is a 'release' build, which must be
# built from a versioned copy of TRUNK in a Vanilla state.
if [ "$versioned_repository" = "yes" ] &&
   [ "$source" = "Trunk"             ] &&
   [ "$state"  = "Vanilla"           ];  then
  echo "       bRelease          = .TRUE."                              >> ${SRCdir}/include/build_info.h
else
  echo "       bRelease          = .FALSE."                             >> ${SRCdir}/include/build_info.h
fi
echo "       cRelease_num      = \"${release}\""                        >> ${SRCdir}/include/build_info.h
if [ "${versioned_repository}" = "yes" ]; then
  echo "       bVersioned        = .TRUE. "                             >> ${SRCdir}/include/build_info.h
else
  echo "       bVersioned        = .FALSE. "                            >> ${SRCdir}/include/build_info.h
fi
if [ "$state" = "Vanilla" ]; then
  echo "       bModified         = .FALSE."                             >> ${SRCdir}/include/build_info.h
else
  echo "       bModified         = .TRUE."                              >> ${SRCdir}/include/build_info.h
fi
echo "C      URL commented out, as it likely exceeds g77's  "           >> ${SRCdir}/include/build_info.h
echo "C      72 character-per-line limit."                              >> ${SRCdir}/include/build_info.h

echo "C      cURL              = \"${URL}\""                            >> ${SRCdir}/include/build_info.h
echo "       cSource           = \"$source\""                           >> ${SRCdir}/include/build_info.h
echo "       cBranch           = \"$branch_name\" "                     >> ${SRCdir}/include/build_info.h
echo "       cRevision         = \"$revision_number\""                  >> ${SRCdir}/include/build_info.h
echo "       cState            = \"${state}\""                          >> ${SRCdir}/include/build_info.h
# Add compilers,  X11 libraries & xml/xsl status.
echo "       cCC               = \"$CC\""                               >> ${SRCdir}/include/build_info.h
echo "       cFC               = \"$FC\""                               >> ${SRCdir}/include/build_info.h
echo "       cCPL              = \"$CPL\""                              >> ${SRCdir}/include/build_info.h
if [ "$xml_support" = "yes" ]; then
  echo "       cXML_support      = \"supported\""                       >> ${SRCdir}/include/build_info.h
else
  echo "       cXML_support      = \"unsupported\""                     >> ${SRCdir}/include/build_info.h
fi
if [ "$SQLite_support" = "yes" ]; then
  echo "       cSQlite_support   = \"supported\""                       >> ${SRCdir}/include/build_info.h
else
  echo "       cSQLite_support   = \"unsupported\""                     >> ${SRCdir}/include/build_info.h
fi
echo "       cXlibrary         = \"$xLibs\" "                           >> ${SRCdir}/include/build_info.h
 
# Write a gnome desktop file to give a prj start icon.
#echo "  "                                                                > ${HOME}/esp-r.desktop
#echo "[Desktop Entry]"                                                  >> ${HOME}/esp-r.desktop
#echo "Version=1.0"                                                      >> ${HOME}/esp-r.desktop
#echo "Type=Application"                                                 >> ${HOME}/esp-r.desktop
#echo "Terminal=false"                                                   >> ${HOME}/esp-r.desktop
#echo "Icon=${ESPdir}/esplogosmall.png"                                  >> ${HOME}/esp-r.desktop
#echo "Name=ESP-r"                                                       >> ${HOME}/esp-r.desktop
#echo "Exec=prj"                                                         >> ${HOME}/esp-r.desktop
#echo "Comment=For use with Ubuntu"                                      >> ${HOME}/esp-r.desktop
#echo "GenericName=Starts the ESP-r Project Manager"                     >> ${HOME}/esp-r.desktop
#cp ${SRCdir}/bitmaps/esplogosmall.png ${ESPdir}
#case $platform in
#  linux)  chmod a+x ${HOME}/esp-r.desktop
#          mv ${HOME}/esp-r.desktop ${HOME}/Desktop/esp-r.desktop
#  ;;
#esac

# Begin build.
targets_shift="${targets} end_of_exes"
while [ "${targets_shift}" != "end_of_exes" ]
do
   # Strip any leading spaces.
   targets_shift=`echo $targets_shift | sed 's/^ *//g'`
   # Extract leading executable name from targets_shift.
   target=`echo $targets_shift | sed 's/ .*$//g'`
   # Remove executable name from targets_shift.
   targets_shift=`echo $targets_shift | sed 's/^[^ ]* //g'`
   echo -n "    - installing ${target} ..."
   # Empty 'make_msg_file' if defined.
  if [ "$make_msg_file" != "" ]; then
    echo "Compilation of $target on `date`"> $make_msg_file
  fi
   # Delete existing executable.
   case $target in
     libX11) result="${SRCdir}/lib/libxesru.a"    ;;
     libGTK) result="${SRCdir}/lib/libgtkesru.a"  ;;
     libnoX) result="${SRCdir}/lib/libnoxesru.a"  ;;
     enableXML | disableXML ) result="${SRCdir}/lib/libXML.a"  ;;
     enableSQLite | disableSQLite ) result="${SRCdir}/lib/libSQLite.a"  ;;
     ecnv)   result="${SRCdir}/cnv/ecnv${EXE}"      ;;
     enet)    result="${SRCdir}/net/enet${EXE}"      ;;
     vew)    result="${SRCdir}/evew/viewer${EXE}"      ;;
     bpsdll) result="${SRCdir}/bps/bps.dll"   ;;
     harmonizer) result="${SRCdir}/harmonizer/harmonizer.exe"   ;;
     harmonizerdll) result="${SRCdir}/harmonizer/harmonizer.dll"   ;;
     *)      result="${SRCdir}/e${target}/$target${EXE}"   ;;
   esac

   if [ -r $result ]; then
     if [ "${make_msg_file}" != "" ]; then
       echo " Deleting $result " >> $make_msg_file
       #rm $result >> $make_msg_file 2>&1
     else
       echo -n " Deleting $result "
       #rm $result
     fi
   fi
   # harmonizer.exe does not fit the pattern for the normal make proceedure..
   if [ "$result" == "${SRCdir}/harmonizer/harmonizer.exe" ]; then
		gfortran ${SRCdir}/harmonizer/win32_interface.f95 ${SRCdir}/harmonizer/launch_dll.f95 -fcray-pointer -o ${SRCdir}/harmonizer/harmonizer.exe
	else
   # Execute make with redirection if make_msg_file specified. Otherwise display messages in buffer.
   if [ "${make_msg_file}" != "" ]; then
      echo " Make command:"             >>$make_msg_file
      echo " -------------"             >>$make_msg_file
      echo "   make MCTYPE=${MCTYPE} MCC=${CC} MCPL=${CPL} MFC=${FC} DESTdir="${DESTdir}" ESPdir="${ESPdir}" WWLINK="${WWLINK}" EXE="${EXE}" XINSTALLDIR="${XINSTALLDIR}" CFLAGS="${CFLAGS}" FFLAGS="${FFLAGS}" LD_FLAGS="${LD_FLAGS}" ULIBS="${ULIBS}" xml_status="${xml_status}" SQLite_status="${SQLite_status}" FMIarg="${FMIarg}" -f Makefile  ${target} >>$make_msg_file 2>&1 " >> $make_msg_file
      echo " "                          >>$make_msg_file
      echo " Make output:"              >>$make_msg_file
      echo " ------------"                    >>$make_msg_file
      make MCTYPE=${MCTYPE} MCC=${CC} MCPL=${CPL} MFC=${FC} DESTdir="${DESTdir}" ESPdir="${ESPdir}" WWLINK="${WWLINK}" EXE="${EXE}" XINSTALLDIR="${XINSTALLDIR}" CFLAGS="${CFLAGS}" FFLAGS="${FFLAGS}" LD_FLAGS="${LD_FLAGS}" ULIBS="${ULIBS}" xml_status="${xml_status}" SQLite_status="${SQLite_status}" FMIarg="${FMIarg}" -f Makefile  ${target} >>$make_msg_file 2>&1
   else
      echo ""
      make MCTYPE=${MCTYPE} MCC=${CC} MCPL=${CPL} MFC=${FC} DESTdir="${DESTdir}" ESPdir="${ESPdir}" WWLINK="${WWLINK}" EXE="${EXE}" XINSTALLDIR="${XINSTALLDIR}" CFLAGS="${CFLAGS}" FFLAGS="${FFLAGS}" LD_FLAGS="${LD_FLAGS}" ULIBS="${ULIBS}" xml_status="${xml_status}" SQLite_status="${SQLite_status}" FMIarg="${FMIarg}" -f Makefile  ${target}
   fi
   fi
   # Was target built successfully?
   if [  ! -r $result ]; then
      # Ignore if a clean command was invoked.
      if [ "$target" != "clean" ]; then
        echo " "
        echo " Error: could not build executable ${target}!"
        echo " Error: result ${result}."

        # If redirection in use, dump messages.
        if [ "${make_msg_file}" != "" ]; then
           echo " Compilation messages follow: "
           echo " ----------------------------------------- "
           cat ${make_msg_file}
           echo " ----------------------------------------- "
           rm -f ${make_msg_file}
        fi

        echo " "
        echo " Executable ${target} could not be built!"
        echo " Installation aborted."
        exit
      fi
   else
     echo " done."
   fi
   # delete message file, if necessary
   if [ "${make_msg_file}" != "" ]; then
      rm -f ${make_msg_file}
   fi
done

# Set executables to be the just compiled versions
# (default to user's default if any not found).
BPS=bps
CLM=clm
ISH=ish
PRJ=prj
PDB=pdb
if [ -f ebps/bps ] ; then
  BPS=${SRCdir}/ebps/bps
fi
if [ -f eclm/clm ] ; then
  CLM=${SRCdir}/eclm/clm
fi
if [ -f eish/ish ] ; then
  ISH=${SRCdir}/eish/ish
fi
if [ -f eprj/prj ] ; then
  PRJ=${SRCdir}/eprj/prj
fi
if [ -f epdb/pdb ] ; then
  PDB=${SRCdir}/epdb/pdb
fi

echo -n "    - installing help files ..."
cp -r ${SRCdir}/tutorial/*.help ${ESPdir}/lib

# ESP-r default file.
echo "*ESP-r Defaults" > ${ESPdir}/default
echo "*ipth ${ESPdir}" >> ${ESPdir}/default
# Default training model.
echo "*cfg ${ESPdir}/training/basic/cfg/bld_basic.cfg"        >> ${ESPdir}/default
echo "*ctl ${ESPdir}/training/basic/ctl/bld_basic.ctl"        >> ${ESPdir}/default
echo "*mfn ${ESPdir}/training/basic/nets/bld_basic_af1.afn"   >> ${ESPdir}/default
echo "*dfd ${ESPdir}/training/cfd/template.dfd"               >> ${ESPdir}/default
echo "*pnf ${ESPdir}/training/plant/vent_simple/cfg/vent.cfg" >> ${ESPdir}/default
# Install databases?
case "${install_dbs}" in
  yes)
       DBInstDir="${ESPdir}"
       LinkDB="yes"
      ;;
  no)
      if [ -r ${ESPdir}/databases/pressc.db1 ]; then
        DBInstDir="${ESPdir}"; LinkDB="yes"
      else
        if [ -r ${ESPdir}/databases/pressc.db1 ]; then
          DBInstDir="${ESPdir}"; LinkDB="yes"
        else
          LinkDB="no"
        fi
      fi
      ;;
esac

if [ "${LinkDB}" = "yes" ]; then
  # Default results.
  echo "*res ${ESPdir}/databases/test.res"              >> ${ESPdir}/default
  echo "*mfr ${ESPdir}/databases/test.mfr"              >> ${ESPdir}/default
  # Default databases.
  echo "*clm ${DBInstDir}/climate/clm67"                >> ${ESPdir}/default
  echo "*prs ${DBInstDir}/databases/pressc.db1"         >> ${ESPdir}/default
  echo "*prm ${DBInstDir}/databases/material.db"        >> ${ESPdir}/default
  echo "*mlc ${DBInstDir}/databases/multicon.db"        >> ${ESPdir}/default
  echo "*opt ${DBInstDir}/databases/optics.db"          >> ${ESPdir}/default
  echo "*evn ${DBInstDir}/databases/profiles.db2.a"     >> ${ESPdir}/default
  echo "*pdb ${DBInstDir}/databases/plantc.db1"         >> ${ESPdir}/default
  echo "*ecdb ${DBInstDir}/databases/elcomp.db1"        >> ${ESPdir}/default
  echo "*mcdb ${DBInstDir}/databases/mscomp.db1"        >> ${ESPdir}/default
  echo "*icdb ${DBInstDir}/databases/icons.db1"         >> ${ESPdir}/default
  echo "*mldb ${DBInstDir}/databases/mould.db1"         >> ${ESPdir}/default
  echo "*sbem ${DBInstDir}/databases/SBEM.db1"          >> ${ESPdir}/default
  echo "*cfcdb ${DBInstDir}/databases/CFClayers.db2.a"  >> ${ESPdir}/default
  echo "*pre ${DBInstDir}/databases/predefined.db1"     >> ${ESPdir}/default
fi
echo "*end"                                             >> ${ESPdir}/default

# Create esprc file.
echo "*ESPRC"                                            > ${ESPdir}/esprc
echo "*gprn,rectangular dump,import"                    >> ${ESPdir}/esprc
echo "*tprn,Text dump,/tmp/tx_dump"                     >> ${ESPdir}/esprc
echo "*gxwd,screen dump,import -window root"            >> ${ESPdir}/esprc
echo "*cad,CAD package,gtool,UNKN"                      >> ${ESPdir}/esprc
echo "*session,OFF"                                     >> ${ESPdir}/esprc
case "${MCTYPE}" in
  mingw)
         echo "*image_display,TIF,iexplore.exe"         >> ${ESPdir}/esprc
         echo "*image_display,XBMP,iexplore.exe"        >> ${ESPdir}/esprc
         echo "*image_display,GIF,iexplore.exe"         >> ${ESPdir}/esprc
         echo "*image_display,XWD,iexplore.exe"         >> ${ESPdir}/esprc
         echo "*image_display,PNG,iexplore.exe"         >> ${ESPdir}/esprc
    ;;
  osx)
         echo "*image_display,TIF,open"                 >> ${ESPdir}/esprc
         echo "*image_display,XBMP,open"                >> ${ESPdir}/esprc
         echo "*image_display,GIF,open"                 >> ${ESPdir}/esprc
         echo "*image_display,XWD,open"                 >> ${ESPdir}/esprc
         echo "*image_display,PNG,open"                 >> ${ESPdir}/esprc
    ;;
  *)
         echo "*image_display,TIF,display"              >> ${ESPdir}/esprc
         echo "*image_display,XBMP,display"             >> ${ESPdir}/esprc
         echo "*image_display,GIF,display"              >> ${ESPdir}/esprc
         echo "*image_display,XWD,display"              >> ${ESPdir}/esprc
         echo "*image_display,PNG,display"              >> ${ESPdir}/esprc
    ;;
esac
echo "*journal,OFF"                                     >> ${ESPdir}/esprc
case "${MCTYPE}" in
  mingw)
         echo "*editor,editor,wordpad.exe"              >> ${ESPdir}/esprc
    ;;
  *)
         echo "*editor,editor,nedit"                    >> ${ESPdir}/esprc
    ;;
esac
echo "*report_gen,Reporting tool,xfs"                   >> ${ESPdir}/esprc

case "${install_training}" in
  yes)
       TVInstDir="${ESPdir}"
       LinkTV="yes"
      ;;
  no)
      if [ -r ${ESPdir}/training/exemplars  ] &&
         [ -r ${ESPdir}/validation/stds_list ]; then
        TVInstDir="${ESPdir}"; LinkTV="yes"
      else
        if [ -r ${ESPdir}/training/exemplars  ] &&
           [ -r ${ESPdir}/validation/stds_list ]; then
          TVInstDir="${ESPdir}"; LinkTV="yes"
        else
          LinkTV="no"
        fi
      fi
      ;;
esac
if [ "${LinkTV}" = "yes" ]; then
  echo "*exemplars,Exemplars,${TVInstDir}/training/exemplars"                    >> ${ESPdir}/esprc
  echo "*validation_stds,Validation standards,${TVInstDir}/validation/stds_list" >> ${ESPdir}/esprc
fi

echo "*db_defaults,Defaults,${ESPdir}/default"                                   >> ${ESPdir}/esprc
if [ "${LinkDB}" = "yes" ]; then
  echo "*db_climates,climatelist,${DBInstDir}/climate/climatelist"               >> ${ESPdir}/esprc
fi
echo "*end"                                                                      >> ${ESPdir}/esprc

echo " done."

# Install databases.
if [ "$install_dbs" = "yes" ]; then
  rm -f ${DESTdir}/databases/*
  rm -f ${DESTdir}/climate/*
  rm -f ${DESTdir}/databases/*

# Constructions.
  echo -n "    - installing materials databases ..."
  cd ${DATdir}/databases
  cp multicon.db ${DESTdir}/databases
  cp multicon.db3 ${DESTdir}/databases
  cp multicon.db4 ${DESTdir}/databases
  cp multicon.db5 ${DESTdir}/databases
  cp ccht_constr.db1 ${DESTdir}/databases/ccht_constr.db1
  cp ccht_na_constr.db1 ${DESTdir}/databases
  cp ccht_material.ascii ${DESTdir}/databases
  cp cellular.materialdb ${DESTdir}/databases
  cp north_american.materialdb.a ${DESTdir}/databases
  cp north_american.constrdb ${DESTdir}/databases
  cp material.db ${DESTdir}/databases
  cp material.db3.a ${DESTdir}/databases
  cp material.db4.a ${DESTdir}/databases
  cp CFClayers.db1.a ${DESTdir}/databases
  cp CFClayers.db2.a ${DESTdir}/databases
  cp SBEM.db1 ${DESTdir}/databases
  cp UK_notional.constrdb ${DESTdir}/databases
  echo " done."
  
# Plant components.
# Define a function to convert the plant database file format from ascii to binary.
pdb_convert()
{
SourceName=$1
TargetName=$2
TargetFolder=$3
printf "\r    - installing plant databases [${TargetName}] ..."
$PDB -mode text -file $TargetName -act asci2bin ${SourceName}
mv $TargetName $TargetFolder
}
  echo -n "    - installing plant components databases ..."
  pdb_convert plantc.db1.a plantc.db1 ${DESTdir}/databases >/dev/null
  pdb_convert plantc.db2.a plantc.db2 ${DESTdir}/databases >/dev/null
  pdb_convert plantc.tt.a  plantc.tt  ${DESTdir}/databases >/dev/null
  cp components.db1 mscomp.db1 mscomp.db2 *.desc ${DESTdir}/databases
  echo " done."

# Weather.
# Define a function to convert the climate database format from ascii to binary.
clim_convert()
{
TargetName=`echo $2 |  sed 's/\.a$//g'`
printf "\r    - installing weather files [${TargetName}] ..."
rm -f $1
$CLM -mode text -file $1 -act asci2bin silent $2  >/dev/null 2>/dev/null
}
  echo -n "    - installing weather files ..."
  cd ${DATdir}/climate
  cp climatelist ${DESTdir}/climate
  sed -e 's|/opt/esp-r|'"${ESPdir}"'|' ${DATdir}/climate/climatelist > ${ESPdir}/climate/climatelist
  cp README ${DESTdir}/climate/Readme
  cp README_IWEC ${DESTdir}/climate/Readme_iwec
  for file in *.a
    do
      CLIM_a=${file}
      CLIM_b=`echo $file |  sed 's/\.a$//g'`
      clim_convert ${DATdir}/climate/${CLIM_b} ${CLIM_a} >/dev/null
      mv ${DATdir}/climate/${CLIM_b} ${DESTdir}/climate/
    done
  echo " done."

# Miscellaneous.
  echo -n "    - installing miscellaneous databases ..."
  cd ${DATdir}/databases
  cp optics.db ${DESTdir}/databases
  cp optics.db2 ${DESTdir}/databases
  cp optics.db3 ${DESTdir}/databases
  cp ccht-optics.db1 ${DESTdir}/databases
  cp mould.db1 ${DESTdir}/databases
  cp pressc.db1 ${DESTdir}/databases
  cp predefined.db1 ${DESTdir}/databases
  cp flow_icons.db6 ${DESTdir}/databases
  cp profiles.db2.a ${DESTdir}/databases
  cp icons.db1 ${DESTdir}/databases
  cp components.db1 ${DESTdir}/databases
  cp ${SRCdir}/bitmaps/*.xbm ${DESTdir}/lib
  cp multi_seg_occup_DB.txt ${DESTdir}/databases
  echo " done."
fi

# Training and validation models.
if [ "$install_training" = "yes" ]; then
  echo "    - installing training and validation models:"
# Special case.
  rm -rf ${ESPdir}/training ${ESPdir}/validation
  cd ${MODdir}/training/Temporal_Clm
  $CLM -mode text -file 15265.climate -act asci2bin 15265.climate.a >/dev/null
# Update weather files in validation models.
  cd ${MODdir}/validation/CEN/13791/databases
  $CLM -mode text -file Cond.clm -act asci2bin silent Cond.clm.a >/dev/null
  $CLM -mode text -file WM_A.clm -act asci2bin silent WM_A.clm.a >/dev/null
  $CLM -mode text -file WM_B.clm -act asci2bin silent WM_B.clm.a >/dev/null
# Process all models.
  cp -r ${MODdir}/training ${ESPdir}/training
  sed -e 's|/opt/esp-r|'"${ESPdir}"'|' ${MODdir}/training/exemplars > ${ESPdir}/training/exemplars
  cp -r ${MODdir}/validation ${ESPdir}/validation
  sed -e 's|/opt/esp-r|'"${ESPdir}"'|' ${MODdir}/validation/stds_list > ${ESPdir}/validation/stds_list
#  Removing versioning information.
#  find  ${ESPdir}/training -name "\.svn" | xargs rm -fr
#  find  ${ESPdir}/training -name "\.git" | xargs rm -fr
#  find  ${ESPdir}/validation -name "\.svn" | xargs rm -fr
#  find  ${ESPdir}/validation -name "\.git" | xargs rm -fr

# Removing weather databases from models.
  cd ${MODdir}/
  rm -f validation/CEN/13791/databases/WM_A.clm
  rm -f validation/CEN/13791/databases/WM_B.clm
  rm -f validation/CEN/13791/databases/Cond.clm

# Updating model shading databases.
  cfgnames=(`find ./training ./validation -name "*.cfg" -print`)
  cfgcount=`find ./training ./validation -name "*.cfg" -print | wc -l`
  cfgnum=0
  for file in "${cfgnames[@]}"; do
    cfgnum=$((${cfgnum} + 1))
    printf "       -> ${cfgnum}/${cfgcount} (${file})"
    if [ "${skip_ish_calcs}" = "no" ]; then
      isi=(`egrep '(\*isi\ |\*zon\ )' $file | cut -d# -f1`)
      ish_tag_count=(`egrep '(\*isi\ )' $file | cut -d# -f1 | wc -l `)
      hits=${#isi[@]}
      i=0
      ish_processed_count=0
      while [ $((i)) -lt $((hits-2)) ]; do
      if [ ${isi[$((i))]} == "*zon" ]; then
        if [ ${isi[$((i+2))]} == "*isi" ]; then
          ish_processed_count=$((${ish_processed_count}+1))
          if [ "${reuse_ish_calcs}" = "no" ]; then
            printf "\r       -> ${cfgnum}/${cfgcount} (${file}); zone ${ish_processed_count}/${ish_tag_count}"
            $ISH -mode text -file ${file:2} -zone ${isi[$((i+1))]} -act update_silent > /dev/null
            shdfile=${file%/*}/${isi[$((i+3))]}
            mv -f ${shdfile} ${ESPdir}/${shdfile}
          elif [ "${reuse_ish_calcs}" = "yes" ]; then
            printf "\r       -> ${cfgnum}/${cfgcount} (${file}); zone ${ish_processed_count}/${ish_tag_count}"
            $ISH -mode text -file ${file:2} -zone ${isi[$((i+1))]} -act useupdate_silent > /dev/null
            shdfile=${file%/*}/${isi[$((i+3))]}
            mv -f ${shdfile} ${ESPdir}/${shdfile}
          fi
        fi
      fi
      i=2+$(($i))
      done
    fi
    printf "\n"

  # Update model paths to reflect install directory.
  sed -e 's|/usr/esru|'"${DESTdir}"'|' ${file} > ${ESPdir}/${file:2}
  done

# Update model paths to reflect install directory for plant networks
plnnames=(`find ./training ./validation -name "*.pln" -print`)
plncount=`find ./training ./validation -name "*.pln" -print | wc -l`

for file in "${plnnames[@]}"; do
  plnnum=$((${plnnum} + 1))
  # printf "       -> ${plnnum}/${plncount} (${file})"
  sed -e 's|/usr/esru|'"${DESTdir}"'|' ${file} > ${ESPdir}/${file:2}
  # printf "\n"
done

# Create a sample result set.
echo -n "    - installing example results database ..."
rm -f ${ESPdir}/databases/test.res
$BPS -mode text >/dev/null 2>&1 <<zzz
a
d
y
c
${ESPdir}/databases/test.res
11 7
17 7
1
1
s

example_results
y
y
-
-
zzz
  echo " done."
  cd ${SRCdir}
  echo -n "    - installing manual files ..."
  rm -rf ${ESPdir}/manual
  cp -r ${DOCdir}/manual ${ESPdir}
  echo " done."
  echo -n "    - installing common scripts ..."
  rm -rf ${ESPdir}/scripts
  mkdir ${ESPdir}/scripts
  cp ${SCRIPTdir}/link_to_bash ${ESPdir}/scripts/
  cp ${SCRIPTdir}/link_to ${ESPdir}/scripts/
  cp ${SCRIPTdir}/Linux_model_2dos ${ESPdir}/scripts/
  cp ${SCRIPTdir}/Linux_model_to_dos ${ESPdir}/scripts/
  cp ${SCRIPTdir}/dos_model_to_linux ${ESPdir}/scripts/
  cp ${SCRIPTdir}/convert_idf_2_espr.sh ${ESPdir}/scripts/
  cp ${SCRIPTdir}/associate_geometryAndDatabases_fromEplusModel.py ${ESPdir}/scripts/
  cp ${SCRIPTdir}/import_geometryAndAttribution_fromEplusModel.py ${ESPdir}/scripts/
  cp ${SCRIPTdir}/import_materialsAndConstructions_fromEplusModel.py ${ESPdir}/scripts/
  cp ${SCRIPTdir}/pandoc_ref.docx ${ESPdir}/scripts/
  echo " done."
fi

# If xml support requested install the XSLT files.
if [ "$xml_support" = "yes" ]; then
echo -n "    - installing xslt files ..."
cp ${SRCdir}/cetc/h3kreports/xsl/*.xsl ${DESTdir}/xsl
echo " done."
fi

# Executables.
if [ "$install_exes" = "yes" ]; then
  echo -n "    - installing executables in ${ESPBinDir} ..." 
  cd ${SRCdir}
  if [ "$debugging" = "no" ]; then
    make ESPdir=${ESPdir} EXE=${EXE} COSIMDir=${COSIMdir} strip  >/dev/null 2>&1
  fi
  make ESPBinDir=${ESPBinDir} EXE=${EXE} COSIMDir=${COSIMdir} InstBins ${targets}  >/dev/null 2>&1
  if [ "$clean" = "yes" ]; then
    make EXE=${EXE} clean  >/dev/null 2>&1
  fi
  echo " done."

# Makeup an appropriate esp-r script.
  if [ ${MCTYPE} = sun ]; then
    echo "#!/bin/sh" > ${ESPdir}/bin/esp-r
    echo "if [ X$EFONT_0 = X ]; then" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_0=6x12" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_1=6x13" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_2=8x13" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_3=9x15" >> ${ESPdir}/bin/esp-r
    echo "fi" >> ${ESPdir}/bin/esp-r
    echo "prj \$@ &" >> ${ESPdir}/bin/esp-r
    chmod a+x ${ESPdir}/bin/esp-r
  elif [ ${MCTYPE} = lin ]; then
    echo "#!/bin/sh" > ${ESPdir}/bin/esp-r
    echo "if [ X$EFONT_0 = X ]; then" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_0=6x12" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_1=6x13" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_2=8x13" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_3=9x15" >> ${ESPdir}/bin/esp-r
    echo "fi" >> ${ESPdir}/bin/esp-r
    echo "prj \$@ &" >> ${ESPdir}/bin/esp-r
    chmod a+x ${ESPdir}/bin/esp-r
  elif [ ${MCTYPE} = cygw ]; then
    echo "#!/bin/sh" > ${ESPdir}/bin/esp-r
    echo "if [ X$EFONT_0 = X ]; then" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_0=6x12" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_1=6x13" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_2=8x13" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_3=9x15" >> ${ESPdir}/bin/esp-r
    echo "fi" >> ${ESPdir}/bin/esp-r
    echo "prj \$@ &" >> ${ESPdir}/bin/esp-r
    chmod a+x ${ESPdir}/bin/esp-r
  elif [ ${MCTYPE} = osx ]; then
    echo "#!/bin/sh" > ${ESPdir}/bin/esp-r
    echo "if [ X$EFONT_0 = X ]; then" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_0=6x12" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_1=6x13" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_2=8x13" >> ${ESPdir}/bin/esp-r
    echo "      EFONT_3=9x15" >> ${ESPdir}/bin/esp-r
    echo "fi" >> ${ESPdir}/bin/esp-r
    echo "prj \$@ &" >> ${ESPdir}/bin/esp-r
    chmod a+x ${ESPdir}/bin/esp-r
  elif [ ${MCTYPE} = mingw ]; then
    echo "@rem batch file to start project manager - associate with cfg files" > ${ESPdir}/bin/esp-r.cmd
    echo "start prj -file %1" >> ${ESPdir}/bin/esp-r.cmd
  fi

# Temporary.
  ln -sf ${ESPdir}/bin/mrt ${ESPdir}/bin/vwf
  cp -r ${HOMEdir}/modish ${DESTdir}/bin
fi

if [ "$third_party" = "yes" ]; then
  echo " "
  echo " Installation complete."
  echo " "
  echo " You may wish to install the following 3rd Party programs that are"
  echo " used by ESP-r modules."
  echo "  - Radiance, for lighting simulation (https://www.radiance-online.org/);"
  echo "  - gtool, a CAD front-end (see /opt/esp-r/manual/gtool_install_ubuntu.pdf);"
  echo "  - obFMU, for occupant behaviour (https://behavior.lbl.gov/?q=obFMUdownload);"
  echo "  - wings3d, for .obj file viewing (www.wings3d.com); and"
  echo "  - paraview, for CFD air movement visualisation (www.paraview.org)."
  echo " "
  echo " New installations can be tested using the scripts in the 'tester' folder."
  echo " "
  echo " Please ensure that you update your PATH environment variable to include"
  echo " the location of the ESP-r executables and any support tools."
else
  echo " "
  echo " Installation complete."
fi

exit

