File: build

package info (click to toggle)
mrtrix 0.2.12-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 5,980 kB
  • ctags: 4,172
  • sloc: cpp: 26,485; python: 913; xml: 39; makefile: 22; sh: 10
file content (1060 lines) | stat: -rwxr-xr-x 32,061 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
#!/usr/bin/python

import platform, sys, os, time, threading, subprocess, shutil, stat, codecs

system = None
debug = False
profile = False
dependencies = False
verbose = False
release = False
targets = []


global todo, headers, object_deps, file_flags, cflags_glib, cflags_gtk, cflags_gtkgl, libs_glib, libs_gtk, libs_gtkgl, lock, stop
global include_paths
todo, headers, object_deps, file_flags = {}, {}, {}, {}
include_paths = []
lock = threading.Lock()
stop = False

installto = None
linkto = ''
print_help = False


if sys.version_info[0] == 2:
  def as_str (msg):
    if not isinstance (msg, unicode): msg = unicode(msg, 'utf-8')
    return msg
  def report (msg):
    sys.stderr.write (as_str (msg).encode ('utf-8', 'ignore'))
else: 
  def as_str (msg):
    if not isinstance (msg, str): msg = msg.decode (errors='ignore')
    return msg
  def report (msg):
    sys.stderr.write (as_str (msg))



def fopen (filename, mode):
  return codecs.open (filename, mode, encoding='utf-8')




# parse command-line:

for arg in sys.argv[1:]:
  if arg == '-help':
    print_help = True
    break
  elif arg == '-verbose': verbose = True
  elif arg == '-debug': debug = True
  elif arg == '-deps': dependencies = True
  elif arg == '-profile': profile = True
  elif arg == '-release': release = True
  elif arg == 'clean': targets = [ 'clean' ]
  elif arg == 'uninstall': targets = [ 'uninstall' ]
  else:
    args = arg.split ('=', 1)
    if args[0] == 'install': 
      if len (args) > 1: installto = args[1]
      else: installto = ''
    elif args[0] == 'linkto': 
      if len (args) > 1: 
        if len (args[1]) == 0: linkto = None
        else: linkto = args[1]
    elif args[0] == '-system': 
      if len (args) != 2: 
        report ('missing argument to option "-system"')
        exit (1)
      system = args[1]
    elif arg[0] == '-':
      report ('unknown command-line option "' + arg + '"')
      sys.exit (1)
    else: 
      targets.append(arg)

if system == None: system = platform.system()
exec ('from sysconf.' + system.lower() + ' import *')


if print_help:
  report ("""usage: ./build [ options ] [ target ]... 

A target can be any file generated by the compilation process. For example:

$ ./build bin/mrconvert

will compile only the dependencies required to build the mrconvert executable.
Multiple targets can be specified on the command-line if required.

These special targets are also allowed:

  clean              remove all intermediate files generated by a previous
                     invocation of ./build

  doc                generate documentation for each command

  install[=prefix]   install executables and shared library in prefix/bin and
                     prefix/lib respectively. Note that this may require
                     super-user privileges. If no prefix is specified, the
                     default of """ + default_installto + """ will be used. By
                     default, symbolic links will also be created to these
                     executables in a standard location (see "linkto" special
                     target below).

  linkto[=prefix]    When installing using the "install" special target,
                     symbolic links pointing to the executables will be created
                     in the specified folder (default is """ + default_linkto + """). 
                     This can be disabled by specifying an empty path
                     (i.e. "linkto="). A different location can also be
                     specified by specifying a suitable path prefix (e.g.
                     "linkto=/usr/local").

  uninstall          remove all MRtrix-related files. Note that this will not
                     work if the MRtrix executables are not already in the path.

Acceptable options are:
  -verbose          print additional debugging information
  -debug            generate code with debugging symbols
  -deps             print out a list of dependencies for each target
  -profile          generate code with profiling enabled (for use with gprof)
  -system=X         specify the architecture to build
(default is native)
""")
  exit (0)


# check if we are compiling a separate project:

mrtrix_dir = os.path.dirname (os.path.realpath(sys.argv[0]))
if os.path.abspath(mrtrix_dir) == os.path.abspath(os.getcwd()): 
  mrtrix_dir = None
else:
  if verbose: 
    report ('compiling separate project against "' + mrtrix_dir + '''"

''')
  lib_dir = os.path.join (mrtrix_dir, lib_dir)
  include_paths = [ misc_dir ]
  misc_dir = os.path.join (mrtrix_dir, misc_dir)
  svn_revision_file = os.path.join (mrtrix_dir, svn_revision_file)
  


# get version info:

with fopen (os.path.join (lib_dir, 'mrtrix.h'), 'r') as f:
  for line in f:
    line = line.split()
    if len(line) != 3: continue
    if line[0] == '#define':
      if line[1] == 'MRTRIX_MAJOR_VERSION': major = line[2]
      elif line[1] == 'MRTRIX_MINOR_VERSION': minor = line[2]
      elif line[1] == 'MRTRIX_MICRO_VERSION': micro = line[2]

libname += '-' + major + '_' + minor + '_' + micro



# other settings:

ld_flags_lib = [ ld_flags_lib_prefix + libname ]
libname = lib_prefix + libname + lib_suffix
ld_path = [ '-L' + lib_dir ]
include_paths += [ lib_dir, misc_dir ]

if release:
  cpp_flags += cpp_flags_release

if debug:
  cpp_flags = cpp_flags_debug
  ld_flags = ld_flags_debug
  ld_lib_flags = ld_lib_flags_debug

if profile:
  cpp_flags = cpp_flags_profile
  ld_flags = ld_flags_profile
  ld_lib_flags = ld_lib_flags_profile

# honor the environment
try:
  # the splitting is needed because the command is submitted as a list
  # and we need individual options -- it may not be that simple though...
  env_flags = os.environ['LDFLAGS'].split()
  ld_flags.extend(env_flags)
  ld_lib_flags.extend(env_flags)
except:
  pass

# used to set install_name on MacOSX:
ld_lib_flags = [ entry.replace ('LIBNAME', libname) for entry in ld_lib_flags ]


# SVN revision number:
svn_revision = '#define SVN_REVISION 0\n'
if not os.path.exists (svn_revision_file):
  with fopen(svn_revision_file, 'w') as fd:
    fd.write (svn_revision)

try:
  svn_cmd = [ 'svn', 'info', '--xml' ]
  if mrtrix_dir: 
    svn_cmd += [ mrtrix_dir ]
  process = subprocess.Popen (svn_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  if process.wait() != 0: 
    raise Exception
  svn_info = as_str (process.stdout.read()).replace(' ','').replace('\t','').replace('\n','')
  svn_revision_index = svn_info.find ('revision=')
  svn_revision = 0
  if not svn_revision_index > 0:
    if verbose:
      report ('WARNING: error parsing output of "svn info" - SVN revision number may be incorrect')
    raise Exception
  svn_revision = svn_info[svn_revision_index:-1].split('"')[1]
  if verbose:
    report ('SVN revision: ' + svn_revision + os.linesep + os.linesep)
  svn_revision = '#define SVN_REVISION ' + svn_revision + '\n'

  if svn_revision != fopen (svn_revision_file, 'r').read():
    with fopen (svn_revision_file, 'w') as fd:
      fd.write (svn_revision)

except:
  if verbose:
    report ('failed to retrieve current SVN revision number - leaving as-is' + os.linesep + os.linesep)




def SVN_last_changed (filename):
  try:
    process = subprocess.Popen ([ 'svn', 'info', filename ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    if process.wait() != 0: raise 0
    for line in process.stdout:
      if line.startswith ('Text Last Updated:'):
        return line.split(':')[1].split()[0].strip() 
  except:
    return None



def pkg (package, target, extras = None):
  cmd = pkgconfig + [ '--' + target, package ]
  if extras: cmd += extras
  process = subprocess.Popen (cmd, stdout=subprocess.PIPE, env=pkgconfig_env)
  if process.wait() != 0:
    report ('WARNING: unable to find', package, 'configuration' + os.linesep)
    return None
  return as_str(process.stdout.read()).split()

cflags_glib = pkg (pkgconfig_glib, 'cflags')
cflags_gtk = pkg (pkgconfig_gtk, 'cflags')
cflags_gtkgl = pkg (pkgconfig_gtk, 'cflags', [ pkgconfig_gl ])
libs_glib = pkg (pkgconfig_glib, 'libs')
libs_gtk = pkg (pkgconfig_gtk, 'libs')
libs_gtkgl = pkg (pkgconfig_gtk, 'libs', [ pkgconfig_gl ]) + ld_flags_gl

if verbose:
  report ('''Settings:
  GLib cflags:   ''' + ' '.join (cflags_glib) + '''
  GTK cflags:    ''' + ' '.join (cflags_gtk) + '''
  GTK/GL cflags: ''' + ' '.join (cflags_gtkgl) + '''
  GLib libs:     ''' + ' '.join (libs_glib) + '''
  GTK libs:      ''' + ' '.join (libs_gtk) + '''
  GTK/GL libs:   ''' + ' '.join (libs_gtkgl) + '''
''')



###########################################################################
#                           TODO list Entry
###########################################################################

class Entry:
  def __init__ (self, name):
    global todo
    if name in todo.keys(): return
    todo[name] = self

    self.name = name
    self.cmd = []
    self.deps = set()
    self.action = 'NA'
    self.timestamp = mtime (self.name)
    self.dep_timestamp = self.timestamp
    self.currently_being_processed = False

    if is_executable (self.name): self.set_executable()
    elif is_icon (self.name): self.set_icon()
    elif is_object (self.name): self.set_object()
    elif is_library (self.name): self.set_library()

    [ Entry(item) for item in self.deps ]
    dep_timestamp = [ todo[item].dep_timestamp for item in todo.keys() if item in self.deps and not is_library(item) ]
    if len(dep_timestamp): self.dep_timestamp = max(dep_timestamp)
    

  def set_executable (self):
    self.action = 'LB'
    if len(exe_suffix) > 0: cc_file = self.name[:-len(exe_suffix)]
    else: cc_file = self.name
    cc_file = os.path.join (cmd_dir, os.sep.join (cc_file.split(os.sep)[1:])) + cpp_suffix
    self.deps = list_cmd_deps(cc_file)

    try: windres
    except NameError: pass
    else: self.deps.add (icon)

    if file_flags[cc_file] == 1: gtk = libs_glib
    elif file_flags[cc_file] == 2: gtk = libs_gtk
    else: gtk = libs_gtkgl

    self.cmd = fillin (ld, { '$flags$': ld_flags,
      '$path$': ld_path,
      '$obj$': self.deps,
      '$mrtrix$': ld_flags_lib,
      '$gsl$': ld_flags_gsl,
      '$gtk$': gtk,
      '$lz$': ld_flags_zlib,
      '$bin$': [ self.name ] })

    try:
      if ld_use_shell: self.cmd = [ 'sh', '-c', ' '.join(self.cmd) ]
    except NameError: pass

    if not os.path.isdir (bin_dir): os.mkdir (bin_dir)
    self.deps.add (os.path.join (lib_dir, libname))



  def set_object (self):
    self.action = 'CC'
    cc_file = self.name[:-len(obj_suffix)] + cpp_suffix
    self.deps = set([ cc_file ])
    self.deps = self.deps.union (list_headers (cc_file))

    if file_flags[cc_file] == 1: gtk = cflags_glib
    elif file_flags[cc_file] == 2: gtk = cflags_gtk
    else: gtk = cflags_gtkgl

    self.cmd = fillin (cpp, { '$flags$': cpp_flags + cpp_flags_gsl,
      '$path$': [ '-I' + entry for entry in include_paths ],
      '$obj$': [ self.name ],
      '$gtk$': gtk,
      '$src$': [ cc_file ] })


    
  def set_library (self):
    self.action = 'LD'
    for root, dirs, files in os.walk (os.path.split(self.name)[0], followlinks=True):
      for file in files:
        if file[0] == '.': continue
        if file.endswith (cpp_suffix):
          self.deps.add (os.path.join (root, file[:-len(cpp_suffix)] + obj_suffix))

    self.cmd = fillin (ld_lib, { '$flags$': ld_lib_flags,
      '$obj$': [ item for item in self.deps ] + pkg (pkgconfig_glib, 'libs') + ld_flags_gsl + ld_flags_zlib,
      '$lib$': [ self.name ] })

    try:
      if ld_use_shell: self.cmd = [ 'sh', '-c', ' '.join(self.cmd) ]
    except NameError: pass


  def set_icon (self):
    self.action = 'WR'
    self.deps = [ icon_dep ]
    self.cmd = windres + [ icon_dep, icon ]


  def display (self):
    report ('[' + self.action + '] ' + self.name + ' (' + str(self.timestamp) + ' - ' + str(self.dep_timestamp) + ')')
    if not self.timestamp or self.timestamp < self.dep_timestamp: 
      report (' [REBUILD]')
    report (''':
    deps: ''' + ' '.join(self.deps) + '''
    command: ''' + ' '.join(self.cmd) + '''
''')






###########################################################################
#                         FUNCTION DEFINITIONS
###########################################################################


def default_targets():
  if not os.path.isdir (cmd_dir): 
    report ('ERROR: no "cmd" folder - unable to determine default targets' + os.linesep)
    exit (1)
  target_list = []
  for entry in os.listdir (cmd_dir):
    if entry.endswith(cpp_suffix):
      target_list.append (os.path.join (bin_dir, entry[:-len(cpp_suffix)] + exe_suffix))
  return target_list

def is_executable (target):
  return target.split (os.sep)[0] == bin_dir

def is_library (target):
  return target.endswith (lib_suffix) and target.split(os.sep)[-1].startswith (lib_prefix)

def is_object (target):
  return target.endswith (obj_suffix)

def is_icon (target):
  return target == icon

def mtime (target):
  if not os.path.exists (target): return None
  return os.path.getmtime(target)

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



def execute (message, cmd):
  report (message + os.linesep)
  if verbose: 
    report (' '.join(cmd) + os.linesep)

  try: 
    process = subprocess.Popen (cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    ( stdoutdata, stderrdata ) = process.communicate()
    if process.returncode != 0:
      report ('''
ERROR: ''' + message + '''

''' + ' '.join(cmd) + '''

failed with output:

''' + as_str (stderrdata) + os.linesep)
      return 1
    if len(stdoutdata):
      report ('STDOUT: ' + message + os.linesep + as_str (stdoutdata) + os.linesep)
    if len(stderrdata):
      report ('STDERR: ' + message + os.linesep + as_str (stderrdata) + os.linesep)

  except OSError:
    report (cmd[0] + ': command not found' + os.linesep)
    return 1
  except Exception as inst:
    report ('unexpected exception: ' + inst.args[0] + os.linesep)
    return 1





def list_headers (file):
  global headers, file_flags

  if file not in headers.keys(): 
    headers[file] = set()
    if file == gl: file_flags[file] = 3
    else: file_flags[file] = 1
    if not os.path.exists (file):
      report ('ERROR: cannot find file "' + file + '"' + os.linesep)
      exit(1)
    with fopen (file, 'r') as fd:
      for line in fd:
        line = line.strip()
        if line.startswith('#include'):
          line = line[8:].strip()
          if line.startswith('<gtk') or line.startswith('<gdk'): file_flags[file] = max (file_flags[file], 2)
          elif line[0] == '"':
            line = line[1:].rstrip('"')
            for path in include_paths:
              if os.path.exists (os.path.join (path, line)):
                line = os.path.join (path, line)
                headers[file].add (line)
                [ headers[file].add(entry) for entry in list_headers(line) ]
                break
            else:
              report ('ERROR: cannot find header file \"' + line + '\" (from file \"' + file + '\")' + os.linesep)
              exit(1)
    flags =  [ file_flags[file] ] + [ file_flags[entry] for entry in headers[file] ]
    if len(flags): file_flags[file] = max (flags)

  return headers[file]






def list_cmd_deps (file_cc):
  global object_deps, file_flags

  if file_cc not in object_deps.keys():
    object_deps[file_cc] = set([ file_cc[:-len(cpp_suffix)] + obj_suffix ])
    for entry in list_headers (file_cc):
      if os.path.abspath(entry).startswith(os.path.abspath(lib_dir)): continue
      entry_cc = entry[:-len(h_suffix)] + cpp_suffix
      if os.path.exists (entry_cc):
        object_deps[file_cc] = object_deps[file_cc].union (list_cmd_deps(entry_cc))
    file_flags[file_cc] = 1
    flags = [ file_flags[entry] for entry in headers[file_cc] ]
    if len(flags): file_flags[file_cc] = max (flags)

  return object_deps[file_cc]





def build_next (id):
  global todo, lock, stop

  try:
    while not stop:
      current = None
      lock.acquire()
      if len(todo):
        for item in todo.keys():
          if todo[item].currently_being_processed: continue
          unsatisfied_deps = set(todo[item].deps).intersection (todo.keys())
          if not len(unsatisfied_deps):
            todo[item].currently_being_processed = True
            current = item
            break
      else: stop = max (stop, 1)
      lock.release()
  
      if stop: return
      if current == None: 
        time.sleep (0.01)
        continue
  
      target = todo[current]
      if execute ('[' + target.action + '] ' + target.name, target.cmd):
        report ('STOP' + os.linesep)
        stop = 2
        return

      lock.acquire()
      del todo[current]
      lock.release()

  except:
    stop = 2
    return
    
  stop = max(stop, 1)



def start_html (fid, title, left, up, home, right):
  fid.write ('''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
  <title>MRtrix #VERSION# documentation</title>
  <link rel="stylesheet" href="../stylesheet.css" type="text/css" media=screen>
</head>

<body>

<table class=nav>
  <tr>
    <td><a href="''' + left + '''.html"><img src="../left.png"></a></td>
    <td><a href="''' + up + '''.html"><img src="../up.png"></a></td>
    <td><a href="''' + home + '''.html"><img src="../home.png"></a></td>
    <th>''' + title + '''</th>
    <td><a href="''' + right + '''.html"><img src="../right.png"></a></td>
  </tr>
</table>

''')




def gen_command_html_help ():
  binaries = os.listdir (bin_dir)
  binaries.sort()
  description = []
  most_recent_cmd = None
  most_recent_timestamp = 0

  # generate each program's individual page:
  for n in range (0, len(binaries)):
    report ('[DOC] ' + binaries[n] + os.linesep)
     
    env = dict(os.environ)
    if platform.system().lower() == 'windows':
      env['PATH'] = lib_dir + ';' + env['PATH']
    else:
      env['PATH'] = lib_dir + ':' + env['PATH']
    process = subprocess.Popen ([os.path.join(bin_dir,binaries[n]), '__print_full_usage__' ], stdout=subprocess.PIPE, env=env) 
    a = process.communicate()
    if process.returncode != 0:
      report ('ERROR: unable to execute', binaries[n], ' - aborting' + os.linesep)
      return 1
    H = as_str (a[0]).splitlines()

    with fopen (os.path.join (doc_dir, 'commands', binaries[n] + '.html'), 'w') as fid:

      if n == 0: prev = 'index'
      else: prev = binaries[n-1]

      if n == len(binaries)-1: next = 'index'
      else: next = binaries[n+1]

      start_html (fid, binaries[n], prev, 'index', '../index', next)
      fid.write ('<h2>Description</h2>\n')

      line = 0
      while not H[line].startswith ('ARGUMENT') and not H[line].startswith('OPTION'):
        if len(description) <= n: description.append (H[line])
        fid.write ('<p>\n' + H[line] + '\n</p>\n')
        line += 1

      arg = []
      opt = []
      while line < len(H)-2:
        if not H[line].startswith ('ARGUMENT') and not H[line].startswith ('OPTION'):
          report ('ERROR: malformed usage for executable "' + binaries[n] + '" - aborting' + os.linesep)
          return 1

        if H[line].startswith ('ARGUMENT'):
          S = H[line].split (None, 5)
          A = [ S[1], int(S[2]), int(S[3]), S[4], H[line+1], H[line+2] ]
          if len(opt) > 0: opt[-1].append (A)
          else: arg.append(A)

        elif H[line].startswith ('OPTION'):
          S = H[line].split (None, 4)
          A = [ S[1], int(S[2]), int(S[3]), H[line+1], H[line+2] ]
          opt.append (A)

        line += 3

      fid.write ('<p class=indented><strong>syntax:</strong> &nbsp; &nbsp; ' + binaries[n] + ' [ options ] ')
      for A in arg:
        if A[1] == 0: fid.write ('[ ')
        fid.write (A[0] + ' ')
        if A[2] == 1: fid.write ('[ ' + A[0] + ' ... ')
        if A[1] == 0 or A[2] == 1: fid.write ('] ')
      fid.write ('</p>\n<h2>Arguments</h2>\n<table class=args>\n')


      for A in arg:
        fid.write ('<tr><td><b>' + A[0] + '</b>')
        if A[1] == 0 or A[2] == 1:
          fid.write (' [ ')
          if A[1] == 0: 
            fid.write ('optional')
            if A[2] == 1: fid.write (', ')
          if A[2] == 1: fid.write ('multiples allowed')
          fid.write (' ]')
        fid.write ('</td>\n<td>' + A[5] + '</td></tr>\n')
      fid.write ('</table>\n')
  
      fid.write ('<h2>Options</h2>\n<table class=args>\n')
      for O in opt:
        fid.write ('<tr><td nowrap><b>-' + O[0] + '</b>')
        for A in O[5:]: fid.write ('&nbsp;<i>' + A[0] + '</i>')
        fid.write ('</td>\n<td>' + O[4])
        if len(O) > 5:
          fid.write ('\n<table class=opts>\n')
          for A in O[5:]:
            fid.write ('<tr><td><i>' + A[0] + '</i></td>\n<td>' + A[5] + '</td></tr>\n')
          fid.write ('</table>')
        fid.write ('</td></tr>\n')
      fid.write ('</table>\n')
  
      cmd_file = os.path.join (cmd_dir, binaries[n] + cpp_suffix)
      timestamp = mtime (cmd_file)
      if timestamp > most_recent_timestamp: 
        most_recent_timestamp = timestamp
        most_recent_cmd = cmd_file
      fid.write ('''
<p class=footer>
Donald Tournier<br>
MRtrix version #VERSION#<br>
Last updated #MTIME#
</p>

</body>
</html>
''')




  with fopen (os.path.join (doc_dir, 'commands', 'index.html'), 'w') as fid:
    start_html (fid, 'list of MRtrix commands', '../faq', '../index', '../index', '../appendix/index')
    fid.write ('<table class=cmdindex width=100%>\n')

    for n in range (0,len(binaries)):
      fid.write ('<tr><td><a href="' + binaries[n] + '.html">' + binaries[n] + '</a></td><td>' + description[n] + '</td></tr>\n')
    fid.write ('''</table>

<p class=footer>
Donald Tournier<br>
MRtrix version #VERSION#<br>
</p>

</body>
</html>
''')




def gen_doc ():
  shutil.rmtree (doc_dir, True)
  shutil.copytree (os.path.join (misc_dir, doc_dir), doc_dir)
  gen_command_html_help()
  for root, dirs, files in os.walk (doc_dir):
    for entry in files:
      if entry[0] == '.': continue
      if not entry.endswith ('.html'): continue
      fname = os.path.join (root, entry)
      timestamp = SVN_last_changed (os.path.join (misc_dir, fname))
      if not timestamp:
        timestamp = SVN_last_changed (os.path.join (cmd_dir, entry.replace (".html", cpp_suffix)))
      if not timestamp:
        timestamp = '-'
      with fopen(fname, 'r') as fd:
        contents = fd.read()
      with fopen(fname, 'w') as fd:
        fd.write (contents
           .replace ('#MTIME#', timestamp)
           .replace ('#VERSION#', major + '.' + minor + '.' + micro))





def clean_cmd ():
  files_to_remove = []
  for root, dirs, files in os.walk ('.', followlinks=True):
    for file in files:
      if file[0] == '.': continue
      if file.endswith (obj_suffix) or ( file.startswith (lib_prefix) and file.endswith (lib_suffix) ):
        files_to_remove.append (os.path.join (root, file))
        
  dirs_to_remove = []
  if os.path.isdir (bin_dir):
    for root, dirs, files in os.walk (bin_dir, topdown=False, followlinks=True):
      for file in files: files_to_remove.append (os.path.join (root, file))
      for entry in dirs: dirs_to_remove.append (os.path.join (root, entry))
    dirs_to_remove.append (bin_dir)

  if len(files_to_remove):
    report ('[RM] ' + ' '.join(files_to_remove) + os.linesep)
    for entry in files_to_remove: os.remove (entry)

  if len(dirs_to_remove):
    report ('[RM] ' + ' '.join (dirs_to_remove) + os.linesep)
    for entry in dirs_to_remove: os.rmdir (entry)


def apply_recursive (action, source, destination):
  if not os.path.isdir (source):
    if not os.path.isdir (os.path.dirname (destination)):
      os.makedirs (os.path.dirname (destination))
    action (source, destination)
    return

  if not os.path.isdir (destination):
    os.makedirs (destination)

  for entry in os.listdir (source):
    if entry[0] == '.': continue
    src = os.path.join (source, entry)
    dst = os.path.join (destination, entry)
    if os.path.isdir (src): apply_recursive (action, src, dst)
    else: action (src, dst)


def install (source, destination):
  if os.path.exists (destination):
    os.unlink (destination)
  shutil.copy (source, destination)


def create_link (source, destination):
  if os.path.isabs (source): src = source
  else: src = os.path.relpath (source, os.path.dirname(destination))
  try:
    os.symlink (src, destination)
  except OSError as e:
    if e.errno == 17:
      if verbose: report ('error creating symbolic link "' + destination + '": ' + e.strerror + os.linesep)
    else:
      report ('WARNING: error creating symbolic link: ' + e.strerror + os.linesep)
      raise
  

def which (executables):
  for path in os.environ["PATH"].split(os.pathsep):
    for entry in executables:
      exe_file = os.path.join(path, entry)
      if os.path.exists (exe_file) and os.access (exe_file, os.X_OK):
        return path
  return None



def add_to_uninstall_list (path, executable):
  full_entry = os.path.join (path, executable)
  if not os.path.exists (full_entry): 
    return None
  if os.path.islink (full_entry):
    actual = os.readlink (full_entry)
    if not os.path.isabs (actual):
      actual = os.path.normpath (os.path.join (os.path.dirname (full_entry), actual))
    return [ actual, full_entry ]
  else:
    return [ full_entry, None ]


def sort_uninstall_list (uninstall_list):
  sorted_file_list = {}
  sorted_link_list = {}
  for entry in uninstall_list:
    [ folder, file ] = os.path.split (entry[0])
    if folder not in sorted_file_list.keys():
      sorted_file_list[folder] = []
    sorted_file_list[folder].append (file)
 
    if entry[1]:
      [ folder, link ] = os.path.split (entry[1])
      if folder not in sorted_link_list.keys():
        sorted_link_list[folder] = []
      sorted_link_list[folder].append (link)
 
  return [ sorted_file_list, sorted_link_list ]
    
    
    


def delete (folder, files):
  if verbose: 
    report ('deleting from folder "' + folder + '": ' + ' '.join(files) + os.linesep)
  for entry in files:
    try:
      os.remove (os.path.join (folder, entry))
    except OSError as e:
      report ('error deleting file "' + os.path.join (folder, entry) + '": ' + e.strerror + os.linesep)
  
  if verbose:
    report ('attempting to delete folder "' + folder + '"... ')
  try: 
    os.removedirs (folder)
  except OSError: 
    if verbose:
      report ('not empty' + os.linesep)
  else:
    if verbose: 
      report ('ok' + os.linesep)


###########################################################################
#                            START OF PROGRAM
###########################################################################

try: num_processors = os.sysconf('SC_NPROCESSORS_ONLN')
except:
  try: num_processors = int(os.environ['NUMBER_OF_PROCESSORS'])
  except: num_processors = 1
  
if platform.system().lower() == 'windows':
  configfile = 'C:\\mrtrix.conf'
else:
  configfile = '/etc/mrtrix.conf'

# uninstall:

if 'uninstall' in targets:
  executables = [ os.path.basename (entry) for entry in default_targets() ]
  path = which (executables)
  if not path:
    report ('ERROR: could not find executables in path' + os.linesep)
    exit (1)
  path = path.rstrip (os.path.sep)

  uninstall_list = [] 
  for entry in executables:
    item = add_to_uninstall_list (path, entry)
    if item: uninstall_list.append (item)

  [ symlink_prefix, last ] = os.path.split (path)
  [ actual_prefix, last ] = os.path.split (os.path.dirname (uninstall_list[0][0]))

  if not last == 'bin':
    report ('ERROR: executables are expected to reside in a folder named "bin"' + os.linesep)
    exit (1)

  lib_path = None
  if libname in os.listdir (os.path.join (symlink_prefix, 'lib')):
    lib_path = os.path.join (symlink_prefix, 'lib')
  elif libname in os.listdir (os.path.join (actual_prefix, 'lib')):
    lib_path = os.path.join (os.path.join (actual_prefix, 'lib'))
  if lib_path:
    item = add_to_uninstall_list (lib_path, libname)
    if item: uninstall_list.append (item)

  [ sorted_file_list, sorted_link_list ] = sort_uninstall_list (uninstall_list)

  report ('WARNING: about to delete files:' + os.linesep)
  for key in sorted_file_list.keys():
    report ('  from folder "' + key + '": ' + ' '.join(sorted_file_list[key]) + os.linesep)

  report ('WARNING: about to delete symbolic links:' + os.linesep)
  for key in sorted_link_list.keys():
    report ('  from folder "' + key + '": ' + ' '.join(sorted_link_list[key]) + os.linesep)

  if os.path.exists (configfile):
    report ('WARNING: about to delete configuration file: ' + configfile + os.linesep)


  ans = raw_input ('proceed? y|[N]: ')
  if len(ans) and 'yes'.startswith (ans.lower()):
    for folder in sorted_file_list.keys():
      delete (folder, sorted_file_list[folder])
    for folder in sorted_link_list.keys():
      delete (folder, sorted_link_list[folder])
    if os.path.exists (configfile):
      try:
        os.remove (configfile)
      except OSError as e:
        report ('error deleting file "' + configfile + '": ' + e.strerror + os.linesep)
    exit (0)

  report ('aborted' + os.linesep)
  exit(1) 




# install:

if installto is not None:
  if len(installto) == 0:
    installto = default_installto
  dest_bin = os.path.join (installto, 'bin')
  dest_lib = os.path.join (installto, 'lib')
  report ('installing executables to "' + dest_bin + '" and dynamic library to "' + dest_lib + '"... ')
  apply_recursive (install, bin_dir, dest_bin)
  apply_recursive (install, os.path.join (lib_dir, libname), os.path.join (dest_lib, libname))
  report ('ok' + os.linesep)

  if linkto is not None:
    if len (linkto) == 0:
      linkto = default_linkto
    link_bin = os.path.join (linkto, 'bin')
    report ('creating symbolic links to executables in "' + link_bin + '"... ')
    apply_recursive (create_link, dest_bin, link_bin)
    report ('ok' + os.linesep)

  if not os.path.exists (configfile):
    report ('creating default system-wide configuration file (setting up multi-threading with ' + str(num_processors) + ' threads)... ')
    with fopen(configfile, 'wb') as fd:
      fd.write ('NumberOfThreads: ' + str(num_processors) + '\n');
    report ('ok' + os.linesep)
  else:
    report ('configuration file already exists - leaving as-is' + os.linesep)

  exit(0)



# clean:

if 'clean' in targets:
  clean_cmd()
  exit (0)



# doc:

if doc_dir in targets: 
  exit (gen_doc());



# standard targets:

if len(targets) == 0: targets = default_targets()

if verbose:
  report ('''
building targets: ''')
  for entry in targets:
    report (entry + ' ')
  report (os.linesep + os.linesep)

if verbose:
  report (''' 
compiling TODO list... ''')
[ Entry(item) for item in targets ]
todo_tmp = todo
todo = {}
for item in todo_tmp.keys():
  if not ( todo_tmp[item].action == 'NA' or (todo_tmp[item].timestamp and todo_tmp[item].timestamp >= todo_tmp[item].dep_timestamp) ):
    todo[item] = todo_tmp[item]
if verbose: 
  report ('TODO list contains ' + str(len(todo)) + ''' items

''')

#for entry in todo.values(): entry.display()

if dependencies:
  report ('''=======================================
  Objects
=======================================''')
  for entry in object_deps.keys():
    report (entry + ' [' + str(file_flags[entry]) + ']:')
    for item in object_deps[entry]: 
      report ('  ' + item + os.linesep)

  report ('''=======================================
  Headers
=======================================''')
  for entry in headers.keys():
    report (entry + ' [' + str(file_flags[entry]) + ']:' + os.linesep)
    for item in headers[entry]: 
      report ('  ' + item + ' [' + str(file_flags[item]) + ']' + os.linesep)




if verbose:
  report (''' 
launching ''' + str(num_processors) + ''' threads
''')

threads = []
for i in range (1, num_processors):
  t = threading.Thread (target=build_next, args=(i,));
  t.start()
  threads.append (t)

build_next(0)

for t in threads: t.join()

exit (stop > 1)