#!/usr/bin/env python

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.


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"

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

    LD_ARGS
        The arguments expected by the linker. The default is:
            "LDFLAGS OBJECTS -o EXECUTABLE"

    LDLIB_ARGS
        The arguments expected by the linker for generating a shared library.
        The default is:
             "-shared LDLIB_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.

    LDFLAGS
        Any additional flags to the linker.

    LDLIB_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_LDFLAGS
        Any flags required to link with the zlib compression library.

    TIFF_CFLAGS
        Any flags required to compile with the TIFF library.

    TIFF_LDFLAGS
        Any flags required to link with the TIFF library.

    FFTW_CFLAGS
        Any flags required to compile with the FFTW library.

    FFTW_LDFLAGS
        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, shutil, 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' ]).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

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
  else:
    print (usage_string)
    sys.exit (1)



global logfile, config_report
logfile = open (os.path.join (os.path.dirname(sys.argv[0]), 'configure.log'), 'wb')
config_report = ''


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

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

def error (message):
  global logfile
  logfile.write (('\nERROR: ' + message.rstrip() + '\n\n').encode (errors='ignore'))
  sys.stderr.write ('\nERROR: ' + message.rstrip() + '\n\n')
  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 len(build_options):
  build_type += ' with ' + ', '.join (build_options)

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


# remove any mention of anaconda from PATH:
path = os.environ['PATH']
if path.endswith ('\\'):
  path = path[:-1]
cleanpath = [];
oldpath = path.split(':')
for entry in oldpath:
  if 'anaconda' not in entry.lower():
    cleanpath += [ entry ]
if not oldpath == cleanpath:
  report ('WARNING: Anaconda removed from PATH to avoid conflicts\n\n')
path = os.pathsep.join(cleanpath)

os.environ['PATH'] = path





global cpp, cpp_cmd, ld, ld_args, ld_cmd

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

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

if static:
  ld_flags += [ '-static', '-Wl,-u,pthread_cancel,-u,pthread_cond_broadcast,-u,pthread_cond_destroy,-u,pthread_cond_signal,-u,pthread_cond_wait,-u,pthread_create,-u,pthread_detach,-u,pthread_cond_signal,-u,pthread_equal,-u,pthread_join,-u,pthread_mutex_lock,-u,pthread_mutex_unlock,-u,pthread_once,-u,pthread_setcancelstate' ]

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


class TempFile:
  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, type, value, traceback):
    try:
      os.unlink (self.name)
    except OSError as error:
      log ('error deleting temporary file "' + self.name + '": ' + error.strerror)
    except:
      raise



class DeleteAfter:
  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 error:
      log ('error deleting temporary file "' + self.name + '": ' + error.strerror)
    except:
      raise


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

  def __enter__ (self):
    return self

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

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



# error handling helpers:

class VersionError (Exception): pass
class QMakeError (Exception): pass
class QMOCError (Exception): pass
class CompileError (Exception): pass
class LinkError (Exception): pass
class RuntimeError (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 (name, variable):
  cache.write (name + ' = ')
  if type (variable) == type([]):
    cache.write ('[')
    if len(variable): cache.write(' \'' + '\', \''.join (variable) + '\' ')
    cache.write (']\n')
  else: cache.write ('\'' + variable + '\'\n')



def fillin (template, keyvalue):
  cmd = []
  for item in template:
    if item in keyvalue:
      if type(keyvalue[item]) == type ([]): cmd += keyvalue[item]
      else: cmd += [ keyvalue[item] ]
    else: cmd += [ item ]
  return cmd



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)
    ( stdout, stderr ) = process.communicate()

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

  except OSError as error:
    log ('error invoking command "' + cmd[0] + '": ' + error.strerror + '\n>>\n\n')
    raise exception
  except:
    print ('Unexpected error:', str(sys.exc_info()))
    raise
  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 = []):
  global cpp, ld
  with TempFile ('.cpp') as F:
    log ('\nCOMPILE ' + F.name + ':\n---\n' + source + '\n---\n')
    F.fid.write (source)
    F.fid.flush()
    F.fid.close()
    with DeleteAfter (F.name[:-4] + '.o') as obj:
      cmd = fillin (cpp, {
        'CFLAGS': compiler_flags,
        'SRC': F.name,
        'OBJECT': obj.name })
      execute (cmd, CompileError)

      with DeleteAfter ('a.out') as out:
        cmd = fillin (ld, {
          'LDFLAGS': linker_flags,
          'OBJECTS': obj.name,
          'EXECUTABLE': out.name })
        execute (cmd, LinkError)

        ret = execute ([ './'+out.name ], RuntimeError)

  return ret[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 entry in shlex.split (execute ([ 'pkg-config' ] + pkg_config_flags.split(), RuntimeError)[1]):
        if entry.startswith ('-I'):
          flags += [ '-isystem', entry[2:] ]
        else:
          flags += [ entry ]
      return flags
    except:
      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 len(stdout):
      report (stdout.splitlines()[0] + '\n')
    else:
      report (on_success+'\n')
    return True
  except:
    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 len(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 as e:
    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 RuntimeError:
    error ('''runtime error!

   Unable to configure ''' + name + configure_log_hint)
  except:
    error ('unexpected exception!' + 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'
report ('Detecting OS: ' + system + '\n')
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' ], RuntimeError)[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'




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 ]




# set CPP compiler:
ld_cmdline = None
if 'CXX' in os.environ.keys(): cxx = shlex.split (os.environ['CXX'])
if 'CXX_ARGS' in os.environ.keys(): cxx_args = shlex.split (os.environ['CXX_ARGS'])
if 'LD' in os.environ.keys(): ld_cmdline = shlex.split (os.environ['LD'])
if 'LD_ARGS' in os.environ.keys(): ld_args = shlex.split (os.environ['LD_ARGS'])
if 'LDLIB_ARGS' in os.environ.keys(): ld_lib_args = shlex.split (os.environ['LDLIB_ARGS'])




# CPP flags:

if 'CFLAGS' in os.environ.keys(): cpp_flags += shlex.split (os.environ['CFLAGS'])
if 'LDFLAGS' in os.environ.keys(): ld_flags += shlex.split (os.environ['LDFLAGS'])
ld_lib_flags += ld_flags
if 'LDLIB_FLAGS' in os.environ.keys(): ld_lib_flags += shlex.split (os.environ['LDLIB_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 len(compiler_version) == 0: report ('(no version information)\n')
    else: report (compiler_version.splitlines()[0] + '\n')
  except:
    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 F:
    F.fid.write ('int bogus() { return (1); }')
    F.fid.flush()
    F.fid.close()
    with DeleteAfter (F.name[:-4] + '.o') as obj:
      cmd = fillin (cpp, {
        'CFLAGS': cpp_flags,
        'SRC': F.name,
        'OBJECT': obj.name })
      try: execute (cmd, CompileError)
      except CompileError:
        error ('compiler not found!' + configure_log_hint)
      except:
        error ('unexpected exception!' + configure_log_hint)
      with DeleteAfter (lib_prefix + 'test' + lib_suffix) as lib:
        cmd = fillin (ld_lib, {
          'LDLIB_FLAGS': ld_lib_flags,
          'OBJECTS': obj.name,
          'LIB': lib.name })
        try: execute (cmd, LinkError)
        except LinkError:
          error ('''linker not found!

  MRtrix3 was unable to employ the linker program for shared library generation.''' + compiler_hint ('shared library linker', 'LDLIB_FLAGS', '"-L/usr/local/lib"', 'LDLIB_ARGS', '"-shared LDLIB_FLAGS OBJECTS -o LIB"'))
        except:
          error ('unexpected exception!' + 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:
  error ('unable to determine pointer size!' + 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' ]







# zlib:

zlib_cflags = get_flags ([], 'ZLIB_CFLAGS', '--cflags zlib')
zlib_ldflags = get_flags ([ '-lz' ], 'ZLIB_LDFLAGS', '--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_LDFLAGS', '"-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_LDFLAGS', '--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




# FFTW:


fftw_cflags = get_flags ([], 'FFTW_CFLAGS', '--cflags fftw3')
fftw_ldflags = get_flags ([ '-lfftw3' ], 'FFTW_LDFLAGS', '--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()
  else: 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:
    error ('unexpected exception!' + 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:
    error ('unexpected exception!' + 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:
    error ('unexpected exception!' + configure_log_hint)




  report ('Checking for Qt: ')

  try:
    with TempDir() as qt_dir:
      file = '''#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' + file + '---\n')

      f=open (os.path.join (qt_dir.name, 'qt.h'), 'w')
      f.write (file)
      f.close();

      file = '''#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' + file + '---\n')
      f=open (os.path.join (qt_dir.name, 'qt.cpp'), 'w')
      f.write (file)
      f.close();

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

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

      qmake_cmd = [ qmake ]

      try:
         (retcode, stdout, stderr) = execute (qmake_cmd, QMakeError, raise_on_non_zero_exit_code = False, cwd=qt_dir.name)
         if retcode != 0:
           error ('''qmake returned with error:

''' + stderr)
      except QMakeError as E:
        error ('''error issuing qmake command!

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


      qt_defines = []
      qt_includes = []
      qt_cflags = []
      qt_libs = []
      qt_ldflags = []
      qt_makefile = 'Makefile'
      if system == 'windows':
        qt_makefile = 'Makefile.Release'
      for line in open (os.path.join (qt_dir.name, qt_makefile)):
        line = line.strip()
        if line.startswith ('DEFINES'):
          qt_defines = shlex.split (line[line.find('=')+1:].strip())
        elif line.startswith ('CXXFLAGS'):
          qt_cflags = 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())
        elif line.startswith ('LFLAGS'):
          qt_ldflags = shlex.split (line[line.find('=')+1:].strip())

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

      qt_cflags = [e for e in qt_cflags if e != '-O2']
      qt = qt_cflags + 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 += [ '-isystem', entry[2:] ]
          else:
            qt_cflags += [ entry ]

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

      cmd = [ moc, 'qt.h', '-o', 'qt_moc.cpp' ]
      execute (cmd, QMOCError, cwd=qt_dir.name) #process = subprocess.Popen (cmd, cwd=qt_dir.name, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

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

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

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

      cmd = [ os.path.join(qt_dir.name, 'qt') ]
      ret = execute (cmd, RuntimeError)
      report (ret[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 RuntimeError:
    error ('error running Qt application!' + configure_log_hint)
  except OSError as e:
    error ('unexpected error: ' + str(e) + configure_log_hint)
  except:
    error ('unexpected exception!' + configure_log_hint)





  if system == "darwin":
    if '-Wall' in qt_cflags: qt_cflags.remove ('-Wall')
    if '-W' in qt_cflags: qt_cflags.remove ('-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_LDFLAGS', 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_LDFLAGS', '"-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:
cache_filename = os.path.join (os.path.dirname(sys.argv[0]), 'config')

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

cache = open (cache_filename, 'w')

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

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

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

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

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

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

