File: configure

package info (click to toggle)
mrtrix3 3.0~rc3+git135-g2b8e7d0c2-3
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 34,248 kB
  • sloc: cpp: 117,101; python: 6,472; sh: 638; makefile: 226; xml: 39; ansic: 20
file content (1349 lines) | stat: -rwxr-xr-x 37,683 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
#!/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')