#!/usr/bin/env python

# Copyright (c) 2008-2022 the MRtrix3 contributors.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Covered Software is provided under this License on an "as is"
# basis, without warranty of any kind, either expressed, implied, or
# statutory, including, without limitation, warranties that the
# Covered Software is free of defects, merchantable, fit for a
# particular purpose or non-infringing.
# See the Mozilla Public License v. 2.0 for more details.
#
# For more details, see http://www.mrtrix.org/.

# pylint: disable=invalid-name

# note: deal with these warnings properly when we drop support for Python 2:
# pylint: disable=unspecified-encoding,consider-using-dict-items,unused-variable,consider-iterating-dictionary

usage_string = '''
USAGE

    [ENV] ./configure [-debug] [-assert] [-profile] [-nogui] [-noshared]


DESCRIPTION

    In most cases, a simple invocation should work:

       $ ./configure

    This creates a 'config' file containing the parameters of the buid (PATH,
    compiler flags, etc.). A number of options are provided to modify the build
    for debugging and other purposes (see OPTIONS below). For example:

      $ ./configure -debug -assert

    will generate a config file with debugging symbols and assertions enabled.
    Other parameters are controlled by setting environment variables (see
    ENVIRONMENT VARIABLES below). For example:

      $ ARCH=x86-64 ./configure

    will produce a config file to run on a generic AMD64 CPU.

OPTIONS

    -debug       enable debugging symbols.

    -assert      enable all assert() and related checks.

    -nooptim     disable optimisation (implied by -debug and -profile).

    -profile     enable profiling.

    -nogui       disable GUI components.

    -noshared    disable shared library generation.

    -static      produce statically-linked executables.

    -verbose     enable more informative output.

    -dev         enable the extended development build process.

    -R           used to generate an R module (implies -noshared).

    -openmp      enable OpenMP compiler flags.

    -conda       prevent stripping anaconda/miniconda from the PATH (only use if
                 you intend building with the conda toolchain - not recommended)


ENVIRONMENT VARIABLES

    For non-standard setups, you may need to supply additional information
    using environment variables. For example, to set the compiler, use:

      $ CXX=/usr/local/bin/g++-5.5 ./configure

    Alternatively:

      $ export CXX=/usr/local/bin/g++-5.5
      $ ./configure

    Multiple environment variables can be set this way as needed.
    The following environment variables are available:

    CXX
        The compiler command to use. The default is "clang++", falling back to
        "g++" if not found.

    CXX_ARGS
        The arguments expected by the compiler. The default is:
            "-c CFLAGS SRC -o OBJECT"

    LINK
        The linker command to use. The default is the same as CXX.

    LINK_ARGS
        The arguments expected by the linker. The default is:
            "LINKFLAGS OBJECTS -o EXECUTABLE"

    LINKLIB_ARGS
        The arguments expected by the linker for generating a shared library.
        The default is:
             "-shared LINKLIB_FLAGS OBJECTS -o LIB"

    ARCH
        the specific CPU architecture to compile for. This variable will be
        passed to the compiler using -march=$ARCH. You can use 'ARCH=native' to
        get the best performance for your system. Note that this will result in
        executables that may not run on other systems if the same CPU
        extensions are not available.

    CFLAGS
        Any additional flags to the compiler.

    LINKFLAGS
        Any additional flags to the linker.

    LINKLIB_FLAGS
        Any additional flags to the linker to generate a shared library.

    EIGEN_CFLAGS
        Any flags required to compile with Eigen3. This may include in
        particular the path to the include files, if not in a standard location
        For example:
            $ EIGEN_CFLAGS="-isystem /usr/local/include/eigen3" ./configure

    ZLIB_CFLAGS
        Any flags required to compile with the zlib compression library.

    ZLIB_LINKFLAGS
        Any flags required to link with the zlib compression library.

    TIFF_CFLAGS
        Any flags required to compile with the TIFF library.

    TIFF_LINKFLAGS
        Any flags required to link with the TIFF library.

    PNG_CFLAGS
        Any flags required to compile with the libpng library.

    PNG_LINKFLAGS
        Any flags required to link with the libpng library.

    FFTW_CFLAGS
        Any flags required to compile with the FFTW library.

    FFTW_LINKFLAGS
        Any flags required to link with the FFTW library.

    QMAKE
        The command to invoke Qt's qmake (default: qmake).

    MOC
        The command to invoke Qt's meta-object compile (default: moc)

    RCC
        The command to invoke Qt's resource compiler (default: rcc)

    PATH
        Set the path to use during the configure process. This may be useful
        to set the path to Qt's qmake. For example:
            $ PATH=/usr/local/bin:$PATH ./configure

        Note that this path will be stored in the config file and used during
        subsequent invocations of the build process. It only needs to be
        specified correctly at configure time.
'''

import subprocess, sys, os, platform, tempfile, shlex, re, copy
system = platform.system().lower()

# on Windows, need to use MSYS2 version of python - not MinGW version:
if sys.executable[0].isalpha() and sys.executable[1] == ':':
  python_cmd = subprocess.check_output ([ 'cygpath.exe', '-w', '/usr/bin/python' ]).decode(errors='ignore').splitlines()[0].strip()
  sys.exit (subprocess.call ([ python_cmd ] + sys.argv))


debug = False
asserts = False
profile = False
nogui = False
noshared = False
static = False
verbose = False
R_module = False
openmp = False
dev = False
conda = False

optimlevel = 3

for arg in sys.argv[1:]:
  if '-debug'.startswith (arg):
    debug = True
    optimlevel = 0
  elif '-dev'.startswith (arg):
    dev = True
  elif '-assert'.startswith (arg):
    asserts = True
  elif '-nooptim'.startswith (arg):
    optimlevel = 0
  elif '-profile'.startswith (arg):
    profile = True
    optimlevel = 0
  elif '-nogui'.startswith (arg):
    nogui = True
  elif '-noshared'.startswith (arg):
    noshared = True
  elif '-static'.startswith (arg):
    static = True
    noshared = True
  elif '-verbose'.startswith (arg):
    verbose = True
  elif '-R'.startswith (arg):
    R_module = True
    #noshared = True
    nogui = True
  elif '-openmp'.startswith (arg):
    openmp = True
  elif '-conda'.startswith (arg):
    conda = True
  else:
    sys.stdout.write (usage_string)
    sys.exit (1)



logfile = open (os.path.join (os.path.dirname(sys.argv[0]), 'configure.log'), 'wb') #pylint: disable=consider-using-with
config_report = ''


def log (message):
  logfile.write (message.encode (errors='ignore'))
  if verbose:
    sys.stdout.write (message)
    sys.stdout.flush()

def report (message):
  global config_report
  config_report += message
  sys.stdout.write (message)
  sys.stdout.flush()
  logfile.write (('\nREPORT: ' + message.rstrip() + '\n').encode (errors='ignore'))

def error (message):
  logfile.write (('\nERROR: ' + message.rstrip() + '\n\n').encode (errors='ignore'))
  sys.stdout.write ('\nERROR: ' + message.rstrip() + '\n\n')
  sys.stdout.flush()
  sys.exit (1)


if profile:
  build_type = 'profiling version'
elif debug:
  build_type = 'debug version'
else:
  build_type = 'release version'

build_options = []
if asserts:
  build_options.append ('asserts')
if optimlevel <= 1:
  build_options.append ('nooptim')
if nogui:
  build_options.append ('nogui')
if noshared:
  build_options.append ('noshared')
if static:
  build_options.append ('static')
if openmp:
  build_options.append ('openmp')

if build_options:
  build_type += ' with ' + ', '.join (build_options)

report ("""
MRtrix build type requested: """ + build_type + '\n\n')


# if not using conda, remove any mention of conda from PATH:
issue_conda_warning = False
if conda:
  path = os.environ['PATH']
else:
  path = []
  for entry in os.environ['PATH'].split(os.pathsep):
    if 'conda' in entry:
      report ('WARNING: anaconda/miniconda detected in PATH ("' + entry + '") - removed to avoid conflicts\n')
      issue_conda_warning = True
    else:
      path += [ entry ]
  path = os.pathsep.join(path)
  os.environ['PATH'] = path

log ('PATH set to: ' + path)





cpp = ld = None

cxx = [ 'clang++', 'g++' ]
cxx_args = '-c CFLAGS SRC -o OBJECT'.split()
cpp_flags = [ '-std=c++11', '-DMRTRIX_BUILD_TYPE="'+build_type+'"' ]

ld_args = 'OBJECTS LINKFLAGS -o EXECUTABLE'.split()
ld_flags = []
if system != 'darwin':
  ld_flags += [ '-Wl,--sort-common,--as-needed' ]

if static:
  ld_flags += [ '-static', '-Wl,--whole-archive', '-lpthread', '-Wl,--no-whole-archive']

ld_lib_args = 'OBJECTS LINKLIB_FLAGS -o LIB'.split()


class TempFile(object):
  def __init__ (self, suffix):
    self.fid = None
    self.name = None
    [ fid, self.name ] = tempfile.mkstemp (suffix)
    self.fid = os.fdopen (fid, 'w')

  def __enter__ (self):
    return self

  def __exit__(self, exception_type, value, traceback):
    try:
      os.unlink (self.name)
    except OSError as excp_local:
      log ('error deleting temporary file "' + self.name + '": ' + excp_local.strerror)



class DeleteAfter(object):
  def __init__ (self, name):
    self.name = name

  def __enter__ (self):
    return self

  def __exit__(self, exception_type, value, traceback):
    try:
      os.unlink (self.name)
    except OSError as excp_local:
      log ('error deleting temporary file "' + self.name + '": ' + excp_local.strerror)


class TempDir(object):
  def __init__ (self):
    self.name = tempfile.mkdtemp()

  def __enter__ (self):
    return self

  def __exit__(self, exception_type, value, traceback):
    try:
      for basename in os.listdir (self.name):
        fullpath = os.path.join (self.name, basename)
        if os.path.isdir (fullpath):
          os.rmdir (fullpath)
        else:
          os.unlink (fullpath)
      os.rmdir (self.name)

    except OSError as excp_local:
      log ('error deleting temporary folder "' + self.name + '": ' + excp_local.strerror)



# error handling helpers:
class VersionError (Exception):
  pass
class QMakeError (Exception):
  pass
class QMOCError (Exception):
  pass
class CompileError (Exception):
  pass
class LinkError (Exception):
  pass
class RunError (Exception):
  pass

def compiler_hint (cmd, flags_var, flags, args_var=None, args=None):
  ret='''

  Set the '''+ flags_var + ''' environment variable to inform 'configure' of the path to the
  ''' + cmd + ''' on your system, as follows:
    $ export ''' + flags_var + '=' + flags + '''
    $./configure
  (amend with the actual path to the ''' + cmd + ''' on your system)
'''
  if args_var is not None:
    ret += '''
  If you are using a ''' + cmd + ' other than gcc or clang, you can also set the ' + args_var + '''
  environment variable to specify how your ''' + cmd + ''' expects different arguments
  to be presented on the command line, for instance as follows:
    $ export ''' + args_var + '=' + args + '''
    $ ./configure
'''
  return ret

def compiler_flags_hint (name, var, flags):
  return '''

  Set the ''' + var + ''' environment variable to inform 'configure' of
  the flags it must provide to the compiler in order to compile
  programs that use ''' + name + ''' functionality; this may include the path to
  the ''' + name + ''' include files, as well as any required flags.
  For example:
    $ export ''' + var + '=' + flags + '''
    $./configure
  (amend with the actual path to the ''' + name + ''' include files on your system)
'''

def linker_flags_hint (name, var, flags):
  return '''

  Set the ''' + var + ''' environment variable to inform 'configure' of
  the flags it must provide to the linker in order to link
  programs that use ''' + name + ''' functionality; this may include the path to
  the ''' + name + ''' libraries, as well as any required flags.
  For example:
    $ export ''' + var + '=' + flags + '''
    $./configure
  (amend with the actual path to the ''' + name + ''' library file on your system)
'''

configure_log_hint='''

  See the file 'configure.log' for details. If this doesn't help and you need
  further assistance, please post on the MRtrix3 community forum
  (http://community.mrtrix.org/), and make sure to include the full contents of
  the 'configure.log' file.
'''

qt_path_hint='''

  Make sure your PATH environment variable includes the location of the correct
  version of this command, for example:
    $ export PATH=/opt/qt5/bin:$PATH
    $./configure
  (amend with the actual path to the Qt executables on your system)
'''

def qt_exec_hint (name):
  return '''

  If your PATH already includes the correct location, but there are several
  versions of the command available, use the ''' + name.upper() + ''' environment variable to inform
  'configure' of the correct version, for example:
    $ export '''+ name.upper() + '=' + name + '''-qt5
    $./configure
  (amend with the actual name of (or full path to) Qt's ''' + name + ''' on your system)
'''




# other helper functions:

def commit (outfile, name, variable):
  outfile.write (name + ' = ')
  if isinstance (variable, list):
    outfile.write ('[')
    if variable:
      outfile.write(' \'' + '\', \''.join (variable) + '\' ')
    outfile.write (']\n')
  else:
    outfile.write ('\'' + variable + '\'\n')



def fillin (template, keyvalues):
  command_string = []
  for item in template:
    if item in keyvalues:
      if isinstance(keyvalues[item], list):
        command_string += keyvalues[item]
      else:
        command_string += [ keyvalues[item] ]
    else:
      command_string += [ item ]
  return command_string



def execute (cmd, exception, raise_on_non_zero_exit_code = True, cwd = None):
  log ('EXEC <<\nCMD: ' + ' '.join(cmd) + '\n')
  try:
    process = subprocess.Popen (cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd) #pylint: disable=consider-using-with
    ( stdout, stderr ) = process.communicate()

    log ('EXIT: ' + str(process.returncode) + '\n')
    stdout = stdout.decode(errors='ignore').rstrip()
    if stdout:
      log ('STDOUT:\n' + stdout + '\n')
    stderr = stderr.decode(errors='ignore').rstrip()
    if stderr:
      log ('STDERR:\n' + stderr + '\n')
    log ('>>\n\n')

  except OSError as excp_local:
    log ('error invoking command "' + cmd[0] + '": ' + excp_local.strerror + '\n>>\n\n')
    raise exception
  except Exception as excp_local:
    error ('unexpected exception of type ' + type(excp_local).__name__ + ': ' + str(excp_local) +  configure_log_hint)
  else:
    if raise_on_non_zero_exit_code and process.returncode != 0:
      raise exception (stderr)


  return (process.returncode, stdout, stderr)



def compile (source, compiler_flags, linker_flags): # pylint: disable=redefined-builtin
  with TempFile ('.cpp') as srcfile:
    log ('\nCOMPILE ' + srcfile.name + ':\n---\n' + source + '\n---\n')
    srcfile.fid.write (source)
    srcfile.fid.flush()
    srcfile.fid.close()
    with DeleteAfter (srcfile.name[:-4] + '.o') as objfile:
      execute (fillin (cpp, {
          'CFLAGS': compiler_flags,
          'SRC': srcfile.name,
          'OBJECT': objfile.name }), CompileError)

      with DeleteAfter ('a.out') as out:
        execute (fillin (ld, {
            'LINKFLAGS': linker_flags,
            'OBJECTS': objfile.name,
            'EXECUTABLE': out.name }), LinkError)

        return execute ([ './'+out.name ], RunError)[1]


#def compare_version (needed, observed):
#  needed = [ float(n) for n in needed.split()[0].split('.') ]
#  observed = [ float(n) for n in observed.split()[0].split('.') ]
#  for n in zip (needed, observed):
#    if n[0] > n[1]:
#      return False
#  return True




def get_flags (default=None, env=None, pkg_config_flags=None):
  """Return a list of the flags required for a given packagei

  If 'env' is defined, it will check whether the corresponding environment
  variable is set, and if so return its contents. If 'pkg_config_flags' is set,
  it will invoke 'pkg-config' with the given arguments, and return its output.
  Otherwise it returns the contents of 'default'.
  """
  if env:
    if env in os.environ.keys():
      return shlex.split (os.environ[env])
  if pkg_config_flags:
    try:
      flags = []
      for flag in shlex.split (execute ([ 'pkg-config' ] + pkg_config_flags.split(), RunError)[1]):
        if flag.startswith ('-I'):
          flags += [ '-idirafter', flag[2:] ]
        else:
          flags += [ flag ]
      return flags
    except Exception:
      log('error running "pkg-config ' + pkg_config_flags + '"\n\n')
  return default






def compile_test (name, cflags, ldflags, code, on_success='ok', on_failure='not found'):
  """Tests whether the code given compiles, links, and runs.

  This returns True if successful, and False for any type of failure.  It will
  also report that is it checking for 'name', and print the contents of stdout
  if non-empty, or the contents of 'on_success' / 'on_failure' otherwise.
  """
  report ('Checking for ' + name + ': ')
  try:
    stdout = compile (code, cflags, ldflags)
    if stdout:
      report (stdout.splitlines()[0] + '\n')
    else:
      report (on_success+'\n')
    return True
  except Exception:
    report (on_failure+'\n')
    return False











def compile_check (full_name, name, cflags, ldflags, code, cflags_env=None, cflags_hint=None, ldflags_env=None, ldflags_hint=None, on_success='ok'):
  """Checks whether the code given compiles, links, and runs.

  This is intended to check for required dependencies, and will cause
  'configure' to abort on failure. It will report that is it checking for
  'full_name', and on success print the contents of stdout if non-empty, or the
  contents of 'on_success' otherwise. On failure, it will print hints about
  what might be going wrong, depending on the specific mode of failure. For
  compile and linking errors, the compiler_flags_hint() or linker_flags_hint()
  functions will be used to provide helpul hints if the corresponding *_env and
  *_hint variables are set. Otherwise, the 'configure_log_hint' message will be
  shown. The 'name' variable is a shorthand of the 'full_name' that will be
  used during error reporting.
  """
  report ('Checking for ' + full_name + ': ')
  try:
    stdout = compile (code, cflags, ldflags)
    if stdout:
      report (stdout.splitlines()[0] + '\n')
    else:
      report (on_success+'\n')
  except CompileError:
    if cflags_env and cflags_hint:
      hint = compiler_flags_hint (name, cflags_env, cflags_hint)
    else:
      hint = configure_log_hint
    error ('error compiling ' + name + ''' application!

    MRtrix3 was unable to compile a test program involving ''' + name + '.' + hint)
  except LinkError:
    if cflags_env and cflags_hint:
      hint = linker_flags_hint (name, ldflags_env, ldflags_hint)
    else:
      hint = configure_log_hint
    error ('error linking ' + name + ''' application!

    MRtrix3 was unable to link a test program involving ''' + name + '.' + hint)
  except RunError:
    error ('''runtime error!

   Unable to configure ''' + name + configure_log_hint)
  except Exception as excp_local:
    error ('unexpected exception of type ' + type(excp_local).__name__ + ': ' + str(excp_local) +  configure_log_hint)









# OS-dependent variables:

obj_suffix = '.o'
exe_suffix = ''
lib_prefix = 'lib'
ld_lib_flags = []

if system.startswith('mingw') or system.startswith('msys'):
  system = 'windows'
if system == 'linux':
  cpp_flags += [ '-pthread', '-fPIC' ]
  lib_suffix = '.so'
  ld_flags += [ '-pthread' ]
  ld_lib_flags += [ '-shared' ]
  runpath = '-Wl,-rpath,$ORIGIN/'
elif system == 'windows':
  cxx = [ 'g++', 'clang++' ]
  cpp_flags += [ '-pthread', '-DMRTRIX_WINDOWS', '-mms-bitfields', '-Wa,-mbig-obj', '-D_FILE_OFFSET_BITS=64' ]
  exe_suffix = '.exe'
  lib_prefix = ''
  lib_suffix = '.dll'
  ld_flags += [ '-pthread', '-Wl,--allow-multiple-definition' ]
  ld_lib_flags += [ '-shared' ]
  runpath = ''
  if debug and not optimlevel: # Compilation will fail otherwise
    optimlevel = 1
elif system == 'darwin':
  if 'MACOSX_DEPLOYMENT_TARGET' in os.environ and 'QMAKE_MACOSX_DEPLOYMENT_TARGET' in os.environ:
    if not os.environ['QMAKE_MACOSX_DEPLOYMENT_TARGET'] == os.environ['MACOSX_DEPLOYMENT_TARGET']:
      error ('environment variables QMAKE_MACOSX_DEPLOYMENT_TARGET and MACOSX_DEPLOYMENT_TARGET differ')
    macosx_version = os.environ['MACOSX_DEPLOYMENT_TARGET']
  elif 'QMAKE_MACOSX_DEPLOYMENT_TARGET' in os.environ:
    macosx_version = os.environ['QMAKE_MACOSX_DEPLOYMENT_TARGET']
  elif 'MACOSX_DEPLOYMENT_TARGET' in os.environ:
    macosx_version = os.environ['MACOSX_DEPLOYMENT_TARGET']
  else:
    macosx_version =  ('.'.join(execute([ 'sw_vers', '-productVersion' ], RunError)[1].split('.')[:2]))
  report ('OS X deployment target: ' +  macosx_version + '\n')
  cpp_flags += [ '-DMRTRIX_MACOSX', '-fPIC', '-mmacosx-version-min='+macosx_version ]
  ld_flags += [ '-mmacosx-version-min='+macosx_version ]
  ld_lib_flags += [ '-dynamiclib', '-install_name', '@rpath/LIBNAME' ]
  runpath = '-Wl,-rpath,@loader_path/'
  lib_suffix = '.dylib'





# set CPP compiler:
ld_cmdline = None
if 'CXX' in os.environ.keys():
  cxx_env = os.environ['CXX']
  if not conda and 'conda' in cxx_env:
    report ('WARNING: anaconda/miniconda compiler set by CXX environment variable - ignored to avoid conflicts\n')
    issue_conda_warning = True
  else:
    cxx = shlex.split (cxx_env)
if 'CXX_ARGS' in os.environ.keys():
  cxx_args = shlex.split (os.environ['CXX_ARGS'])
if 'LINK' in os.environ.keys():
  ld_env = os.environ['LINK']
  if not conda and 'conda' in ld_env:
    report ('WARNING: anaconda/miniconda linker set by LINK environment variable - ignored to avoid conflicts\n')
    issue_conda_warning = True
  else:
    ld_cmdline = shlex.split (ld_env)
if 'LINK_ARGS' in os.environ.keys():
  ld_args = shlex.split (os.environ['LINK_ARGS'])
if 'LINKLIB_ARGS' in os.environ.keys():
  ld_lib_args = shlex.split (os.environ['LINKLIB_ARGS'])




if issue_conda_warning:
  report ('\nNOTE: if you intend to build with anaconda/miniconda (not recommended), pass the -conda flag to ./configure\n\n')






report ('Detecting OS: ' + system + '\n')

if 'ARCH' in os.environ.keys():
  march = os.environ['ARCH']
  if march:
    report ('Machine architecture set by ARCH environment variable to: ' + march + '\n')
    cpp_flags += [ '-march='+march ]



# CPP flags:

if 'CFLAGS' in os.environ.keys():
  cpp_flags += shlex.split (os.environ['CFLAGS'])
if 'LINKFLAGS' in os.environ.keys():
  ld_flags += shlex.split (os.environ['LINKFLAGS'])
ld_lib_flags += ld_flags
if 'LINKLIB_FLAGS' in os.environ.keys():
  ld_lib_flags += shlex.split (os.environ['LINKLIB_FLAGS'])

for candidate in cxx:
  report ('Looking for compiler [' + candidate + ']: ')
  cpp = [ candidate ] + cxx_args
  if ld_cmdline:
    ld = ld_cmdline
  else:
    ld = copy.copy([ candidate ])
  ld_lib = ld + ld_lib_args
  ld += ld_args

  try:
    compiler_version = execute ([ cpp[0], '--version' ], CompileError)[1]
    if not compiler_version:
      report ('(no version information)\n')
    else:
      report (compiler_version.splitlines()[0] + '\n')
  except Exception:
    report ('not found\n')
    continue

  if compile_test ('C++11 compliance', cpp_flags, ld_flags, '''
#include <cstddef>
struct Base {
    Base (int);
};
struct Derived : Base {
    using Base::Base;
};

int main() {
  Derived D (int); // check for contructor inheritance
  return 0;
}
''', on_failure='test failed (see configure.log for details)\n'):
    break
else:
  error ('''no suitable compiler found!

''' + compiler_hint ('compiler', 'CXX', '/usr/bin/g++-5.5', 'CXX_ARGS', '"-c CFLAGS SRC -o OBJECT"') + configure_log_hint)




# shared library generation:
if not noshared:
  report ('Checking shared library generation: ')

  with TempFile ('.cpp') as bogus_cpp:
    bogus_cpp.fid.write ('int bogus() { return (1); }')
    bogus_cpp.fid.flush()
    bogus_cpp.fid.close()
    with DeleteAfter (bogus_cpp.name[:-4] + '.o') as bogus_obj:
      try:
        execute (fillin (cpp, {
            'CFLAGS': cpp_flags,
            'SRC': bogus_cpp.name,
            'OBJECT': bogus_obj.name }), CompileError)
      except CompileError:
        error ('compiler not found!' + configure_log_hint)
      except Exception as excp:
        error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) +  configure_log_hint)
      with DeleteAfter (lib_prefix + 'test' + lib_suffix) as lib:
        try:
          execute (fillin (ld_lib, {
              'LINKLIB_FLAGS': ld_lib_flags,
              'OBJECTS': bogus_obj.name,
              'LIB': lib.name }), LinkError)
        except LinkError:
          error ('''linker not found!

  MRtrix3 was unable to employ the linker program for shared library generation.''' + compiler_hint ('shared library linker', 'LINKLIB_FLAGS', '"-L/usr/local/lib"', 'LINKLIB_ARGS', '"-shared LINKLIB_FLAGS OBJECTS -o LIB"'))
        except Exception as excp:
          error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) +  configure_log_hint)

        report ('ok\n')










report ('Detecting pointer size: ')
try:
  pointer_size = int (compile ('''
#include <iostream>
int main() {
  std::cout << sizeof(void*);
  return (0);
}
''', cpp_flags, ld_flags))
  report (str(8*pointer_size) + ' bit\n')
  if pointer_size == 8:
    cpp_flags += [ '-DMRTRIX_WORD64' ]
  elif pointer_size != 4:
    error ('unexpected pointer size!')
except Exception as excp:
  error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) +  configure_log_hint)




report ('Detecting byte order: ')
if sys.byteorder == 'big':
  report ('big-endian\n')
  cpp_flags += [ '-DMRTRIX_BYTE_ORDER_IS_BIG_ENDIAN' ]
else:
  report ('little-endian\n')







if not compile_test ('variable-length array support', cpp_flags, ld_flags, '''
int main(int argc, char* argv[]) {
  int x[argc];
  return 0;
}
'''):
  cpp_flags += [ '-DMRTRIX_NO_VLA' ]





if not compile_test ('non-POD variable-length array support', cpp_flags, ld_flags, '''
#include <string>

class X {
  int x;
  double y;
  std::string s;
};

int main(int argc, char* argv[]) {
  X x[argc];
  return 0;
}
'''):
  cpp_flags += [ '-DMRTRIX_NO_NON_POD_VLA' ]





if not compile_test ('::max_align_t', cpp_flags, ld_flags, '''
#include <iostream>
#include <cstddef>
using ::max_align_t;
int main() {
  std::cout << alignof (max_align_t) << " bytes\\n";
  return 0;
}
'''):
  cpp_flags += [ '-DMRTRIX_MAX_ALIGN_T_NOT_DEFINED' ]




if not compile_test ('std::max_align_t', cpp_flags, ld_flags, '''
#include <iostream>
#include <cstddef>
using std::max_align_t;
int main() {
  std::cout << alignof (max_align_t) << " bytes\\n";
  return 0;
}
'''):
  cpp_flags += [ '-DMRTRIX_STD_MAX_ALIGN_T_NOT_DEFINED' ]







# Eigen3 flags:

eigen_cflags = get_flags ([ '-isystem', '/usr/include/eigen3' ], 'EIGEN_CFLAGS', '--cflags eigen3')

compile_check ('Eigen3 library', 'Eigen3', cpp_flags + eigen_cflags, ld_flags, '''
#include <cstddef>
#include <Eigen/Core>
#include <iostream>

int main (int argc, char* argv[]) {
  std::cout << EIGEN_WORLD_VERSION << "." << EIGEN_MAJOR_VERSION << "." << EIGEN_MINOR_VERSION << "\\n";
  return 0;
}
''', 'EIGEN_CFLAGS', '"-isystem /usr/include/eigen3"')


if not openmp:
  eigen_cflags += [ '-DEIGEN_DONT_PARALLELIZE' ]


if compile_test ('Eigen3 Unsupported', cpp_flags + eigen_cflags, ld_flags, '''
#include <iostream>
#include <Eigen/Core>
#include <unsupported/Eigen/SpecialFunctions>

using array_type = Eigen::Array<double, 1, 1>;

int main (int argc, char* argv[]) {
  auto test = Eigen::betainc (array_type::Constant (10.0), array_type::Constant (0.5), array_type::Constant (1.0));
  std::cout << "Present";
  return (0);
}
''', on_failure='not found; custom functions to be used'):
  cpp_flags += [ '-DMRTRIX_HAVE_EIGEN_UNSUPPORTED_SPECIAL_FUNCTIONS' ]












# zlib:

zlib_cflags = get_flags ([], 'ZLIB_CFLAGS', '--cflags zlib')
zlib_ldflags = get_flags ([ '-lz' ], 'ZLIB_LINKFLAGS', '--libs zlib')

compile_check ('zlib compression library', 'zlib', cpp_flags + zlib_cflags, ld_flags + zlib_ldflags, '''
#include <iostream>
#include <zlib.h>

int main() {
  std::cout << zlibVersion();
  return (0);
}
''', 'ZLIB_CFLAGS', '"-isystem /usr/local/include"', 'ZLIB_LINKFLAGS', '"-L/usr/local/lib -lz"')

cpp_flags += zlib_cflags
ld_flags += zlib_ldflags
ld_lib_flags += zlib_ldflags






# Test that JSON for Modern C++ will compile, since it enforces its own requirements

compile_check ('"JSON for Modern C++" requirements', 'JSON for modern C++', \
    cpp_flags + [ '-I'+os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), 'core')) ], ld_flags, '''
#include "''' + os.path.join('file', 'json.h') + '''"
int main (int argc, char* argv[])
{
  nlohmann::json json;
  json["key"] = "value";
}
''')








# TIFF:

tiff_cflags = get_flags ([], 'TIFF_CFLAGS', '--cflags libtiff-4')
tiff_ldflags = get_flags ([ '-ltiff' ], 'TIFF_LINKFLAGS', '--libs libtiff-4')

if compile_test ('TIFF library', cpp_flags + tiff_cflags, ld_flags + tiff_ldflags, '''
#include <iostream>
#include <tiffio.h>

int main() {
  std::cout << TIFFGetVersion();
  return (0);
}
''', on_failure='not found - TIFF support disabled'):
  cpp_flags += [ '-DMRTRIX_TIFF_SUPPORT' ] + tiff_cflags
  ld_flags += tiff_ldflags
  ld_lib_flags += tiff_ldflags





# PNG:

png_cflags = get_flags ([], 'PNG_CFLAGS', '--cflags libpng')
png_ldflags = get_flags ([ '-lpng' ], 'PNG_LINKFLAGS', '--libs libpng')

if compile_test ('PNG library', cpp_flags + png_cflags, ld_flags + png_ldflags, '''
#include <iostream>
#include <png.h>

int main() {
  std::cout << "Header: " << PNG_LIBPNG_VER_STRING << "; library: " << png_libpng_ver;
  return (0);
}
''', on_failure='not found - PNG support disabled'):
  cpp_flags += [ '-DMRTRIX_PNG_SUPPORT' ] + png_cflags
  ld_flags += png_ldflags
  ld_lib_flags += png_ldflags






# FFTW:


fftw_cflags = get_flags ([], 'FFTW_CFLAGS', '--cflags fftw3')
fftw_ldflags = get_flags ([ '-lfftw3' ], 'FFTW_LINKFLAGS', '--libs fftw3')

if compile_test ('FFTW library', cpp_flags + fftw_cflags, ld_flags + fftw_ldflags, '''
#include <iostream>
#include <fftw3.h>

int main() {
  std::cout << fftw_version << "\\n";
  return (0);
}
''', on_failure='not found - FFTW support disabled'):
  cpp_flags += [ '-DEIGEN_FFTW_DEFAULT' ] + fftw_cflags
  ld_flags += fftw_ldflags
  ld_lib_flags += fftw_ldflags




# add openmp flags if required and available

if openmp:
  cpp_flags += [ '-fopenmp' ]
  ld_flags  += [ '-fopenmp' ]
  compile_check ('OpenMP support', 'OpenMP', cpp_flags + eigen_cflags, ld_flags, '''
    #include <Eigen/Core>
    int main()
    {
      Eigen::initParallel();
      Eigen::setNbThreads(4);
      return (Eigen::nbThreads() == 4) ? 0 : 1;
    }
    ''')






#the following regex will be reused so keep it outside of the get_qt_version func
version_regex = re.compile(r'\d+\.\d+(\.\d+)+') #: :type version_regex: re.compile
def get_qt_version(cmd_list, raise_on_non_zero_exit_code):
  out = execute (cmd_list, raise_on_non_zero_exit_code, False)
  stdouterr = ' '.join(out[1:]).replace(r'\n',' ').replace(r'\r','')
  version_found = version_regex.search(stdouterr)
  if version_found:
    return version_found.group()
  raise raise_on_non_zero_exit_code('Version not Found')


moc = ''
rcc = ''
qt_cflags = []
qt_ldflags = []




if not nogui:

  report ('Checking for Qt moc: ')
  moc = 'moc'
  if 'MOC' in os.environ.keys():
    moc = os.environ['MOC']
  try:
    moc_version = get_qt_version([ moc, '-v' ], OSError)
    report (moc + ' (version ' + moc_version + ')\n')
    if int (moc_version.split('.')[0]) < 4:
      raise VersionError
  except VersionError:
    error (''' Qt moc version is too old!

  The version number reported by the Qt moc command is too old.''' + qt_path_hint + qt_exec_hint ('moc'))
  except OSError:
    error (''' Qt moc not found!

  MRtrix3 was unable to locate the Qt meta-object compiler 'moc'.''' + qt_path_hint)
  except Exception as excp:
    error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) +  configure_log_hint)

  report ('Checking for Qt qmake: ')
  qmake = 'qmake'
  if 'QMAKE' in os.environ.keys():
    qmake = os.environ['QMAKE']
  try:
    qmake_version = get_qt_version([ qmake, '-v' ], OSError)
    report (qmake + ' (version ' + qmake_version + ')\n')
    if int (qmake_version.split('.')[0]) < 4:
      raise VersionError
  except VersionError:
    error (''' Qt qmake version is too old!

  The version number reported by the Qt qmake command is too old.''' + qt_path_hint + qt_exec_hint ('qmake'))
  except OSError:
    error (''' Qt qmake not found!

  MRtrix3 was unable to locate the Qt command 'qmake'.''' + qt_path_hint)
  except Exception as excp:
    error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) +  configure_log_hint)



  report ('Checking for Qt rcc: ')
  rcc = 'rcc'

  if 'RCC' in os.environ.keys():
    rcc = os.environ['RCC']
  try:
    rcc_version = get_qt_version([ rcc, '-v' ], OSError)
    report (rcc + ' (version ' + rcc_version + ')\n')
    if int (rcc_version.split('.')[0]) < 4:
      raise VersionError
  except VersionError:
    error (''' Qt rcc version is too old!

  The version number reported by the Qt rcc command is too old.''' + qt_path_hint + qt_exec_hint ('rcc'))
  except OSError:
    error (''' Qt rcc not found!

  MRtrix3 was unable to locate the Qt command 'rcc'.''' + qt_path_hint)
  except Exception as excp:
    error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) +  configure_log_hint)




  report ('Checking for Qt: ')

  try:
    with TempDir() as qt_dir:
      filetext = '''#include <QObject>

class Foo: public QObject {
  Q_OBJECT;
  public:
    Foo();
    ~Foo();
  public slots:
    void setValue(int value);
  signals:
    void valueChanged (int newValue);
  private:
    int value_;
};
'''
      log ('\nsource file "qt.h":\n---\n' + filetext + '---\n')

      with open (os.path.join (qt_dir.name, 'qt.h'), 'w') as f:
        f.write (filetext)

      filetext = '''#include <iostream>
#include "qt.h"

Foo::Foo() : value_ (42) { connect (this, SIGNAL(valueChanged(int)), this, SLOT(setValue(int))); }

Foo::~Foo() { std::cout << qVersion() << "\\n"; }

void Foo::setValue (int value) { value_ = value; }

int main() { Foo f; }
'''

      log ('\nsource file "qt.cpp":\n---\n' + filetext + '---\n')
      with open (os.path.join (qt_dir.name, 'qt.cpp'), 'w') as f:
        f.write (filetext)

      filetext = 'CONFIG += c++11'
      if debug:
        filetext += ' debug'
      filetext += '\nQT += core gui opengl svg network\n'
      filetext += 'HEADERS += qt.h\nSOURCES += qt.cpp\n'
      if system == "darwin":
        filetext += 'QMAKE_MACOSX_DEPLOYMENT_TARGET = ' + macosx_version + '\n'

      log ('\nproject file "qt.pro":\n---\n' + filetext + '---\n')
      with open (os.path.join (qt_dir.name, 'qt.pro'), 'w') as f:
        f.write (filetext)

      qmake_cmd = [ qmake ]

      try:
        (qmake_retcode, qmake_stderr) = execute (qmake_cmd, QMakeError, raise_on_non_zero_exit_code = False, cwd=qt_dir.name)[0:3:2]
        if qmake_retcode != 0:
          error ('''qmake returned with error:

''' + qmake_stderr)
      except QMakeError:
        error ('''error issuing qmake command!

  Use the QMAKE environment variable to set the correct qmake command for use with Qt''')


      qt_defines = []
      qt_includes = []
      qt_cflags = []
      qt_libs = []
      qt_ldflags = []
      for qt_makefile in [ 'Makefile', 'Makefile.Release' ]:
        try:
          log ("reading Qt parameters from file '" + qt_makefile + "'... ")
          with open (os.path.join (qt_dir.name, qt_makefile)) as f:
            for line in f:
              line = line.strip()
              if line.startswith ('DEFINES'):
                qt_defines = shlex.split (line[line.find('=')+1:].strip())
              elif line.startswith ('INCPATH'):
                qt_includes = shlex.split (line[line.find('=')+1:].strip())
              elif line.startswith ('LIBS'):
                qt_libs = shlex.split (line[line.find('=')+1:].strip())
          if qt_defines or qt_includes or qt_libs:
            log ('ok\n')
            log ('  qt_defines: ' + str(qt_defines) + '\n')
            log ('  qt_includes: ' + str(qt_includes) + '\n')
            log ('  qt_libs: ' + str(qt_libs) + '\n')
            break
        except OSError:
          log ('not found\n')
          continue
      else:
        raise QMakeError


      for index, entry in enumerate(qt_includes):
        if entry[2:].startswith('..'):
          qt_includes[index] = '-I' + os.path.abspath(qt_dir.name + '/' + entry[2:])

      qt = qt_defines + qt_includes
      qt_cflags = []
      for entry in qt:
        if entry[0] != '$' and not entry == '-I.':
          entry = entry.replace('\"','').replace("'",'')
          if entry.startswith('-I'):
            qt_cflags += [ '-idirafter', entry[2:] ]
          else:
            qt_cflags += [ entry ]

      qt_ldflags = []
      for entry in qt_libs:
        if entry[0] != '$':
          qt_ldflags += [ entry.replace('\"','').replace("'",'') ]

      execute ([ moc, 'qt.h', '-o', 'qt_moc.cpp' ], \
          QMOCError, cwd=qt_dir.name)

      execute ([ cpp[0], '-c' ] + cpp_flags + qt_cflags + [ 'qt.cpp', '-o', 'qt.o' ], \
          CompileError, cwd=qt_dir.name)

      execute ([ cpp[0], '-c' ] + cpp_flags + qt_cflags + [ 'qt_moc.cpp', '-o', 'qt_moc.o' ], \
          CompileError, cwd=qt_dir.name)

      execute ([ cpp[0] ] + ld_flags + [ 'qt_moc.o', 'qt.o', '-o', 'qt' ] + qt_ldflags, \
          LinkError, cwd=qt_dir.name)

      report (execute ([ os.path.join(qt_dir.name, 'qt') ], RunError)[1] + '\n')


  except QMakeError:
    error ('error invoking Qt qmake!' + configure_log_hint)
  except QMOCError:
    error ('error invoking Qt moc!' + configure_log_hint)
  except LinkError:
    error ('error linking Qt application!' + configure_log_hint)
  except CompileError:
    error ('error compiling Qt application!' + configure_log_hint)
  except RunError:
    error ('error running Qt application!' + configure_log_hint)
  except OSError as e:
    error ('unexpected error: ' + str(e) + configure_log_hint)
  except Exception as excp:
    error ('unexpected exception of type ' + type(excp).__name__ + ': ' + str(excp) +  configure_log_hint)





  if system == "darwin":
    qt_cflags = [ x for x in qt_cflags if x not in [ '-Wall', '-W' ] ]


# output R module:
if R_module:

  R_cflags = get_flags (default=[ '-isystem /usr/include/R' ], env='R_CFLAGS', pkg_config_flags='--cflags libR')
  R_ldflags = get_flags (default=[ '-L/usr/lib/R/lib', '-lR' ], env='R_LINKFLAGS', pkg_config_flags='--libs libR')

  compile_check ('R library', 'R', cpp_flags + R_cflags, ld_flags + R_ldflags, '''
  #include <R.h>
  #include <Rversion.h>
  #include <iostream>

  int main() {
    std::cout << R_MAJOR << "." << R_MINOR << " (r" << R_SVN_REVISION << ")\\n";
    return 0;
  }
  ''', 'R_CFLAGS', '"-isystem /usr/local/include/R"', 'R_LINKFLAGS', '"-L/usr/local/R/lib -lR"')

  cpp_flags += R_cflags + [ '-DMRTRIX_AS_R_LIBRARY' ]
  ld_lib_flags += R_ldflags

  ld_flags = ld_lib_flags
  exe_suffix = lib_suffix





# add debugging or profiling flags if requested:

cpp_flags += [ '-Wall' ]

if profile:
  cpp_flags += [ '-g', '-pg' ]
  ld_flags += [ '-g', '-pg' ]
  ld_lib_flags += [ '-g', '-pg' ]
elif debug:
  cpp_flags += [ '-g' ]
  ld_flags += [ '-g' ]
  ld_lib_flags += [ '-g' ]

cpp_flags += [ '-O' + str(optimlevel) ]

if asserts:
  cpp_flags += [ '-D_GLIBCXX_DEBUG=1', '-D_GLIBCXX_DEBUG_PEDANTIC=1' ]
elif not debug:
  cpp_flags += [ '-DNDEBUG' ]








# write out configuration:
config_filename = os.path.join (os.path.dirname(sys.argv[0]), 'config')

sys.stdout.write ('\nwriting configuration to file \'' + config_filename + '\': ')

with open (config_filename, 'w') as config_file:

  config_file.write ("""#!/usr/bin/python
  #
  # autogenerated by MRtrix configure script
  #
  # configure output:
  """)
  for line in config_report.splitlines():
    config_file.write ('# ' + line + '\n')
  config_file.write ('\n\n')

  config_file.write ("PATH = r'" + path + "'\n")

  commit (config_file, 'obj_suffix', obj_suffix)
  commit (config_file, 'exe_suffix', exe_suffix)
  commit (config_file, 'lib_prefix', lib_prefix)
  commit (config_file, 'lib_suffix', lib_suffix)
  commit (config_file, 'cpp', cpp)
  commit (config_file, 'cpp_flags', cpp_flags)
  commit (config_file, 'ld', ld)
  commit (config_file, 'ld_flags', ld_flags)
  commit (config_file, 'runpath', runpath)
  config_file.write ('ld_enabled = ')
  if noshared:
    config_file.write ('False\n')
  else:
    config_file.write ('True\n')
    commit (config_file, 'ld_lib', ld_lib)
    commit (config_file, 'ld_lib_flags', ld_lib_flags)
  commit (config_file, 'eigen_cflags', eigen_cflags)

  commit (config_file, 'moc', moc)
  commit (config_file, 'rcc', rcc)
  commit (config_file, 'qt_cflags', qt_cflags)
  commit (config_file, 'qt_ldflags', qt_ldflags)
  config_file.write ('nogui = ')
  if nogui:
    config_file.write ('True\n')
  else:
    config_file.write ('False\n')

  if dev:
    config_file.write('bash_completion = True\ncommand_doc = True\n')

sys.stdout.write ('ok\n\n')
