File: configure

package info (click to toggle)
mrtrix3 3.0.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 15,300 kB
  • sloc: cpp: 130,470; python: 9,603; sh: 597; makefile: 62; xml: 47
file content (1498 lines) | stat: -rwxr-xr-x 42,901 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
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
#!/usr/bin/python3

# Copyright (c) 2008-2025 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)

    -fsl         prevent stripping FSL from the PATH (only use if you intend
                 building with the FSL 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/python3' ]).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
fsl = 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
  elif '-fsl'.startswith (arg):
    fsl = 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.lower():
      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

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

log ('\nPATH 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 += [ '-isystem', 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'): #pylint: disable=too-many-positional-arguments
  """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'): #pylint: disable=too-many-positional-arguments
  """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'
else:
  assert False, 'Unknown OS'




# 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 ('NOTE: if you intend to build with anaconda/miniconda (not recommended), pass the -conda flag to ./configure\n')
if issue_fsl_warning:
  report ('NOTE: if you intend to build with the FSL toolchain (not recommended), pass the -fsl flag to ./configure\n')
report ('\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'
        filetext += 'QMAKE_LIBS_OPENGL = -framework OpenGL\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 += [ '-isystem', 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/python3
  #
  # 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')