File: Utility.tcl

package info (click to toggle)
dart 0.20061109-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k, lenny
  • size: 5,668 kB
  • ctags: 247
  • sloc: tcl: 5,652; perl: 256; python: 141; cpp: 79; makefile: 68; sh: 36
file content (1116 lines) | stat: -rw-r--r-- 28,972 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
# =========================================================================
#
#   Program:   Insight Segmentation & Registration Toolkit
#   Module:    $RCSfile: Utility.tcl,v $
#   Language:  Tcl
#   Date:      $Date: 2005/10/03 19:58:16 $
#   Version:   $Revision: 1.48 $
#

# Copyright (c) 2001 Insight Consortium
# All rights reserved.

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:

#  * Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.

#  * Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.

#  * The name of the Insight Consortium, nor the names of any consortium members,
#    nor of any contributors, may be used to endorse or promote products derived
#    from this software without specific prior written permission.

#   * Modified source versions must be plainly marked as such, and must not be
#     misrepresented as being the original software.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


proc ManglePathName { path } {
  if { [regexp cygtclsh [info nameofexecutable]] == 1 && $path != "" } {
    set path [exec cygpath -w $path]
    set path [eval file join [file split $path]]
  }
  return $path
}


#
# combines a command and a stdout/stderr redirect to a file in a safe manner
#
proc MakeCommand {cmd outDir } {
   set cmd2 "exec $cmd >& \"$outDir\""
   return $cmd2
}

proc LoadConfigurationFile { arrayname filename } {
  # Open the file, read each of the options in this form
  # option: value
  upvar $arrayname Options
  if { ![file exists $filename] } { return }
  set f [open $filename r]
  set d [read $f]
  close $f
  # Replace backslash line continuation
  regsub -all "\\\\\n" $d "" replaced
  set d [split $replaced "\n"]
  foreach line $d {
    set line [string trim $line]
    # Ignore comments, empty lines, and mis-formed lines
    if { [string index $line 0] == "\#"
     || $line == ""
     || [string first ":" $line] == -1 } {
      continue
    }
    set index [string first ":" $line]
    set option [string range $line 0 [expr $index - 1]]
    set value [string range $line [expr $index + 1] end]
    # Don't override an existing value with a blank
    if { ( [info exists Options($option)] && $value != "" )
         || ![info exists Options($option)] } {
      set Options($option) [string trim $value]
    }
  }
  if { [info exists Options(MangledPathNames) ] } {
    foreach var $Options(MangledPathNames) {
      set Options($var) [ManglePathName $Options($var)]
    }
  }
}

proc SaxonOptions { args } \
{
  set targs {}
  foreach a $args {
      set ta [split $a =]  
      if { [llength $ta] > 1 && [lindex $ta 1] != {} } {
          lappend targs $a
      }
  }
          
  return $targs
}

proc MakeDateTimeStamp {} \
{
  return [clock format [clock seconds] -format %Y%m%d-%H%M -gmt 1]
}

proc NeedToRemake { File } \
{
  set XML [file join XML $File.xml]
  if { ![file exists $File.html] && ![file exists $File.htmlz]} \
  {
    # puts "Remake 1"
    return 1
  }

  # If both uncompressed and compressed versions of the HTML file exist, use
  # the date of the newest
  set htmlFileMTime 0
  set compressedHTMLFileMTime 0
  set latestMTime 0

  if { [file exists $File.html] } {
     set htmlFileMTime [file mtime $File.html]
  }

  if { [file exists $File.htmlz] } {
     set compressedHTMLFileMTime [file mtime $File.htmlz]
  }

  if { [expr $htmlFileMTime > $compressedHTMLFileMTime] } {
      set latestMTime $htmlFileMTime
  } else {
      set latestMTime $compressedHTMLFileMTime
  }

  # Is the XML file in XML directory?  i.e. something submitted by a client
  if { [file exists $XML] } \
  {
    return [expr $latestMTime <= [file mtime $XML]]
  }

  # Is the file in the current directory? i.e. something produced on server
  # while processing other XML files.
  if { [file exists $File.xml] } \
  {
    return [expr $latestMTime <= [file mtime $File.xml]]
  }
  return 1
}

proc IsBuildStampInDay { NightlyDateTimeStamp BuildStamp } \
{
  global Dart
  # Convert the BuildStamp into something recognizable
  if { [catch { set NTS [ConvertStampToSeconds $NightlyDateTimeStamp] } r ] } \
  {
    puts $r
    return 0;
  }

  # NTS is in seconds, so we want the range to be from NTS to NTS + 24 hours
  set Start $NTS
  set End [expr $Start + 24 * 60 * 60]

  if { [catch { set BSTS [ConvertStampToSeconds $BuildStamp] } r ] } \
  {
    puts $r
    return 0;
  }

  if { $BSTS >= $Start && $BSTS < $End } \
  {
    return 1
  } \
  else \
  {
    return 0
  }
}

proc GetNightlySeconds {} \
{
    global Dart

    # Convert the nightly start time to seconds. Since we are
    # providing only a time and a timezone, the current date of the
    # local machine is assumed. Consequently, nightlySeconds is the
    # time at which the nightly dashboard was opened or will be opened
    # on the date of the current client machine.  As such, this time
    # may be in the past or in the future.
    set nightlySeconds [clock scan $Dart(NightlyStartTime)]

    # If nightlySeconds is in the past, this is the current open
    # dashboard, then return nightlySeconds.  If nightlySeconds is in
    # the future, this is the next dashboard to be opened, so subtract 24
    # hours to get the time of the current open dashboard
    if { $nightlySeconds <= [clock seconds] } {
        return $nightlySeconds
    } else {
        return [expr $nightlySeconds - 24 * 60 * 60]
    }

}

proc MakeNightlyDateTimeStamp {} \
{
  set t [GetNightlySeconds]
  return [clock format $t -format %Y%m%d-%H%M -gmt 1]
}

proc ConvertStampToSeconds { Stamp } \
{
  if { [string range $Stamp 8 8] != "-" } \
  {
    # Stamp is from a submission using old-style encoding for Experimental.
    set Year [string range $Stamp 0 3]
    set Month [string range $Stamp 4 5]
    set Day [string range $Stamp 6 7]
    set Hour [string range $Stamp 8 9]
    set Minute [string range $Stamp 10 11]
    set Seconds [clock scan "$Month/$Day/$Year $Hour:$Minute" -gmt 1]
    return $Seconds
  }

  if { [string range $Stamp 8 12] == "-Nigh" } \
  {
    # Stamp is from a submission using old-style encoding for Nightly.
    set Year [string range $Stamp 0 3]
    set Month [string range $Stamp 4 5]
    set Day [string range $Stamp 6 7]
    # Use nightly start time as build's time since encoding doesn't provide it.
    set NDTS [MakeNightlyDateTimeStamp]
    set Hour [string range $NDTS 9 10]
    set Minute [string range $NDTS 11 12]
    set Seconds [clock scan "$Month/$Day/$Year $Hour:$Minute" -gmt 1]
    return $Seconds
  }

  set Year [string range $Stamp 0 3]
  set Month [string range $Stamp 4 5]
  set Day [string range $Stamp 6 7]
  set Hour [string range $Stamp 9 10]
  set Minute [string range $Stamp 11 12]
  set Seconds [clock scan "$Month/$Day/$Year $Hour:$Minute" -gmt 1]
  return $Seconds
}

# Test should be an optional function that takes the name of a directory
# of file and returns false if it should be ignored.

proc FileMap { Queue PatternList Map {Test {}}} \
{

  while { [llength $Queue] != 0 } \
  {
    set Filename [lindex $Queue 0]
    set Queue [lrange $Queue 1 end]

    if { [file isdirectory $Filename] } \
    {
      if { [file tail $Filename] == "CVS" } \
      {
        continue
      }
      if {$Test != {}} {
         if {[$Test $Filename]} {
            set Status [catch { set Queue [concat $Queue [glob -nocomplain -- [file join $Filename *]]] } Result]
         }
      } else {
         set Status [catch { set Queue [concat $Queue [glob -nocomplain -- [file join $Filename *]]] } Result]
      }
      if { $Status } \
      {
        puts "Caught $Result"
      }
      continue;
    }
    foreach Pattern $PatternList \
    {
      if { [string match $Pattern [file tail $Filename]] } \
      {
        if {$Test == {} || [$Test $Filename]} {
          catch { eval $Map $Filename }
        }
      }
    }
  }
}

proc GetYesterdayDateTimeStamp { NightlyDateTimeStamp } \
{
  if { $NightlyDateTimeStamp == "" } {
    set ts [clock seconds]
  } else {
    set ts [ConvertStampToSeconds $NightlyDateTimeStamp]
  }
  return [clock format [expr $ts - 24 * 60 * 60] -format %Y%m%d-%H%M -gmt 1]
}

proc GetTomorrowDateTimeStamp { NightlyDateTimeStamp } \
{
  if { $NightlyDateTimeStamp == "" } {
    set ts [clock seconds]
  } else {
    set ts [ConvertStampToSeconds $NightlyDateTimeStamp]
  }
  return [clock format [expr $ts + 24 * 60 * 60] -format %Y%m%d-%H%M -gmt 1]
}

proc GetLastBuildDirectory { {Model Experimental} } \
{
  global Dart
  set HTMLDir [file join Testing HTML]
  set SiteDir [file join $HTMLDir TestingResults Sites $Dart(Site)]
  set BuildNameDir [file join $SiteDir $Dart(BuildName)]

  set GlobString 2*-Experimental
  if { $Model == "Nightly" } \
  {
    set GlobString 2*-Nightly
  }
  if { $Model == "Continuous" } \
  {
    set GlobString 2*-Continuous
  }
  set BuildStampDirs ""
  set BuildStampDirs [glob -nocomplain -- [file join $BuildNameDir $GlobString]]
  return [lindex [lsort $BuildStampDirs] end]
}

proc GetLastDashboardDirectory { {Model Experimental} } \
{
  global Dart

  set GlobString 2*-Experimental
  if { $Model == "Nightly" } \
  {
    set GlobString 2*-Nightly
  }
  if { $Model == "Continuous" } \
  {
    set GlobString 2*-Continuous
  }
  set DashboardDirs ""
  set DashboardDirs [glob -nocomplain -- [file join Testing HTML TestingResults Dashboard $GlobString]]
  return [lindex [lsort $DashboardDirs] end]
}


proc EchoFileName { file } \
{
  puts $file
}


proc RemoveFile { file } \
{
  file delete -force -- $file
}


proc CompressOldFile { file } \
{
  global AgeMTime
  global Dart

  if { $Dart(CompressionType) == "gzip" } {
      if { [expr [file mtime $file] < $AgeMTime] } {
          puts "\tCompressing $file"
          CompressFile $file ${file}z
          # if the compression worked, then remove the original
          set compressedSize 0
          catch {set compressedSize [file size ${file}z]}
          if { [expr $compressedSize > 0] } {
              RemoveFile $file
          }
      } else {
          # puts "$file compression skipped"
      }
  }
}

proc CompressFile { In Out } \
{
  global Dart

  if { $In == $Out } \
  {
    error "CompressFile, can not compress a file to itself $In"
  }
  switch -glob $Dart(CompressionCommand) \
  {
    *gzip* \
    {
      set Dart(CompressionType) gzip
      return [exec $Dart(CompressionCommand) -c $In > $Out]
    }
    *compress* \
    {
      set Dart(CompressionType) compress
      return [exec $Dart(CompressionCommand) -c $In > $Out]
    }
    *zip* \
    {
      set Dart(CompressionType) zip
      return [exec $Dart(CompressionCommand) - $In > $Out]
    }
    default \
    {
      set Dart(CompressionType) none
      return [file copy -force $In $Out]
    }
  }
}

proc XMLConcat { FP filename } \
{
  catch {
    set f [open $filename r]
      while { ![eof $f] } {
    set line [gets $f]
    if { ![string match {<?xml*} $line] } \
     {
         puts $FP $line
     }
      }
    # puts -nonewline $FP [read $f]
    close $f
  }
}


proc XMLSafeString { str } \
{
  # Here is where all substitutions should be done
  # regsub -all "\"" $str {%quot;} str
  regsub -all "&" $str {\&amp;} str
  regsub -all "<" $str {\&lt;} str
  regsub -all ">" $str {\&gt;} str
  # regsub -all "'" $str {%apos;} str

  return [PrintableString $str]
  return $str
}

# Set inside PrintableString
set XMLCharMap ""
proc PrintableString { str } \
{
  global XMLCharMap
  # need to remove nulls, and > 0x80
  if { [info tclversion] > 8.0 } { regsub -all "\0" $str "^BadChar^" str }
  if { [info tclversion] > 8.2 } {
    # remove all problem characters
    while { ![string is ascii -failindex idx $str] } {
      # Remove the bad character
      set str [string replace $str $idx $idx "^BadChar^"]
    }
    if { $XMLCharMap == "" } {
      # Remove < 0x20, aside from \t, \n, \r
      # > 20 hex are OK, == 32 decimal
      for { set t 0 } { $t < 32 } { incr t } {
        if { $t == 9 || $t == 10 || $t == 13 } { continue }
        lappend XMLCharMap [binary format c $t]
        lappend XMLCharMap "^BadChar^"
      }
    }
    set str [string map $XMLCharMap $str]
  }
  return $str
}

proc XMLStyleSheet { basename } {
    global Dart
    return "<?xml-stylesheet type=\"text/xsl\" href=\"file:///[file join $Dart(DartRoot) Source Server XSL $basename.xsl]\"?>"
}



proc GetDirectories { dir } \
{
  set result ""
  foreach f [glob -nocomplain -- $dir]
  {
    if { [file isdirectory $f] } \
    {
      lappend result $f
    }
  }
  return $result
}


proc InitBase64 {} \
{
  global Base64

  if { [info exists Base64(0)] } { return }
  set String "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

  set count [string length $String]
  for { set i 0 } { $i < $count } { incr i } \
  {
    set Base64($i) [string index $String $i]
  }
  set Base64(Pad) "="
}

proc _toU8 { num } \
{
  return [expr ( $num + 0x100 ) % 0x100]
}

proc Base64Encode { String } \
{
  global Base64
  InitBase64

  set length [string length $String]
  set result ""
  set index 0
  set count 0
  while { $length > 2 } \
  {
    binary scan [string index $String $index] c current0
    set current0 [_toU8 $current0]
    incr index
    binary scan [string index $String $index] c current1
    set current1 [_toU8 $current1]
    incr index
    binary scan [string index $String $index] c current2
    set current2 [_toU8 $current2]
    incr index

    # puts "$current0 $current1 $current2"

    append result $Base64([expr $current0 >> 2])
    append result $Base64([expr (($current0 & 0x03) << 4) + ($current1 >> 4 )])
    append result $Base64([expr (($current1 & 0x0f ) << 2) + ($current2 >> 6) ])
    append result $Base64([expr $current2 & 0x3f])
    incr length -3
  }


  if { $length != 0 } \
  {
    # puts "length = $length"
    binary scan [string index $String $index] c current0
    set current0 [_toU8 $current0]
    incr index
    append result $Base64([expr $current0 >> 2])
    if { $length > 1 } \
    {
      binary scan [string index $String $index] c current1
      set current1 [_toU8 $current1]
      incr index
      append result $Base64([expr (($current0 & 0x03) << 4) + ($current1 >> 4)])
      append result $Base64([expr ($current1 & 0x0f) << 2])
      append result $Base64(Pad)
    } \
    else \
    {
      append result $Base64([expr ($current0 & 0x03) << 4])
      append result $Base64(Pad)
      append result $Base64(Pad)
    }
  }
  # Break result into 78 character counts
  set length [string length $result]
  set ret ""
  set index 0
  while { $length > 60 } \
  {
    append ret "[string range $result 0 59]\n"
    set result [string range $result 60 end]
    incr length -60
  }
  if { $length != 0 } \
  {
    append ret $result
  }
  return $ret
}

proc Base64EncodeFileToFile { In Out } \
{
  global Base64
  InitBase64
  set length 0
  set result ""
  set index 0
  set count 0

  while { ![eof $In] } \
  {
    append String [read $In 2049]
    incr length [string length $String]
    while { $length > 2 } \
    {
      binary scan [string index $String $index] c current0
      set current0 [_toU8 $current0]
      incr index
      binary scan [string index $String $index] c current1
      set current1 [_toU8 $current1]
      incr index
      binary scan [string index $String $index] c current2
      set current2 [_toU8 $current2]
      incr index

      set result ""
      append result $Base64([expr $current0 >> 2])
      append result $Base64([expr (($current0 & 0x03) << 4) + ($current1 >> 4 )])
      append result $Base64([expr (($current1 & 0x0f ) << 2) + ($current2 >> 6) ])
      append result $Base64([expr $current2 & 0x3f])
      incr length -3
      incr count 4
      puts -nonewline $Out $result
      if { $count >= 78 } \
      {
    puts $Out ""
    set count 0
      }
    }
  }

  set result ""
  if { $length != 0 } \
  {
    # puts "length = $length"
    binary scan [string index $String $index] c current0
    set current0 [_toU8 $current0]
    incr index
    append result $Base64([expr $current0 >> 2])
    if { $length > 1 } \
    {
      binary scan [string index $String $index] c current1
      set current1 [_toU8 $current1]
      incr index
      append result $Base64([expr (($current0 & 0x03) << 4) + ($current1 >> 4)])
      append result $Base64([expr ($current1 & 0x0f) << 2])
      append result $Base64(Pad)
    } \
    else \
    {
      append result $Base64([expr ($current0 & 0x03) << 4])
      append result $Base64(Pad)
      append result $Base64(Pad)
    }
    incr count 3
  }
  puts $Out $result
}

proc lremove { l item } \
{
  # Return a list with all instances of the item removed
  set ret ""
  foreach element $l \
  {
    if { [string compare $element $item] != 0 } \
    {
      lappend ret $element
    }
  }
  return $ret
}


proc Grep { matchlist file { Exceptions {} } } \
{
  set result ""
  foreach line [split $file "\n"] \
  {
    set E 0
    foreach match $matchlist \
    {
      if { [regexp $match $line] } \
      {
    set E 1
    foreach Exception $Exceptions \
    {
      if { [regexp $Exception $line] } \
      {
        set E 0
      }
    }
    if { $E } \
    {
      lappend result $line
      break
    }
      }
    }
  }
  return $result
}

proc Match { match file { Exceptions {} } } \
{
  return [expr [llength [Grep $match $file $Exceptions]] > 0 ]
}

proc FindTests { Path {clear 1}} \
{
  global TestList
  if { ![info exists TestList] } { set TestList "" }
  if { $clear } { set TestList "" }

  set testCommands [GetTestfileTests]
  if { $testCommands != ""} {
    # insert $Path to the list for this test and change how tests are run to a
    # (cwd $Path; exec; cwd $Back)
    foreach test $testCommands {
       set testCommand [list [lindex $test 0] $Path ]
       set testCommand [concat $testCommand [lrange $test 1 end]]
       lappend TestList $testCommand
    }
  }

  foreach SubDir [GetTestfileSubdirs] \
  {
    # Need to return to the previous directory.
    # Using cd .. does not always work.
    set curDir [pwd]
    cd $SubDir
    FindTests [file join $Path $SubDir] 0
    cd $curDir
  }
  return $TestList
}


proc GetCMakeVariable { Variable } \
{
  if { ![file exists CMakeLists.txt] } \
  {
    error "No CMakeLists.txt file"
  }
  set Contents ""
  set f [open CMakeLists.txt r]
  set Contents [read $f]
  close $f
  regsub -all "\n" $Contents " " C1
  regsub -all {\)} $C1 ")\n " C
  set Contents $C

  set variableValue ""
  foreach Line [split $Contents "\n"] \
  {
    if { [string first $Variable $Line] != -1 } \
    {
      set i [expr [string first "(" $Line] + 1]
      set l [string trim [string range $Line $i end]]
      set l [string trim $l "()"]
      eval lappend variableValue $l
    }
  }
  return $variableValue
}

# Pull out all ADD_TEST commands from a Testfile. Each ADD_TEST command
# adds a sublist which is {TestName ExeName [args]}
proc GetTestfileTests {} \
{
  if { ![file exists DartTestfile.txt] } \
  {
    error "No DartTestfile.txt found"
  }
  set Contents ""
  set f [open DartTestfile.txt r]
  set Contents [read $f]
  close $f
  regsub -all "\n" $Contents " " C1
  regsub -all {\)} $C1 ")\n " C
  set Contents $C

  set variableValue ""
  foreach Line [split $Contents "\n"] \
  {
    if { [string first ADD_TEST $Line] != -1 } \
    {
      if { [string first "#" $Line] != -1 && [string first "#" $Line] < [string first ADD_TEST $Line] } {
        continue;
      }
      set i [expr [string first "(" $Line] + 1]
      set l [string trim [string range $Line $i end]]
      set l [string trim $l "()"]
      if {$l != ""} {
        lappend variableValue $l
      }
    }
  }
  return $variableValue
}


# Pull out all SUBDIRS commands from a Testfile and append them into a
# single list.
proc GetTestfileSubdirs {} \
{
  if { ![file exists DartTestfile.txt] } \
  {
    error "No DartTestfile.txt found"
  }
  set Contents ""
  set f [open DartTestfile.txt r]
  set Contents [read $f]
  close $f
  regsub -all "\n" $Contents " " C1
  regsub -all {\)} $C1 ")\n " C
  set Contents $C

  set variableValue ""
  foreach Line [split $Contents "\n"] \
  {
    if { [string first SUBDIRS $Line] != -1 } \
    {
      set i [expr [string first "(" $Line] + 1]
      set l [string trim [string range $Line $i end]]
      set l [string trim $l "()"]
      eval lappend variableValue $l
    }
  }
  return $variableValue
}


# If the specified Microsoft Workspace has an ALL_BUILD project, return all
# projects it (ALL_BUILD) depends on.
#
proc FindAllBuildDSPDepends { Workspace } {
  set dsps ""

  if { [file exists $Workspace] } {
    set f [open $Workspace r]

    while { ![eof $f] } {
      set pname ""

      set Line [gets $f]

      # Extract the project name from
      # 'Project: "PROJECT_NAME"=PROJECT_NAME.dsp - Package Owner <4>'
      regexp "^Project: \"(\[^\"\]*)\"=" $Line dummy pname

      # If project name is ALL_BUILD
      if { $pname == "ALL_BUILD" } {
        # Search for project dependencies listed in DSW
        while { ![eof $f] } {
          set Line [gets $f]

          # if Line is, Project: "PROJECT_NAME"=.... then we are done
          if {[regexp "^Project: \"(\[^\"\]*)\"=" $Line d1 d2] } {
            close $f
            return $dsps
          }

          # if Line is, Project_Dep_Name PROJECT_NAME
          # then add it to dsp list
          if {[regexp "^Project_Dep_Name (.*)" $Line dummy pname]} {
            lappend dsps $pname
          }
        }
      }
    }

    # if we get here, make sure we close the file
    close $f
  }
}

proc AbbreviateTimeZone { dt } {

  if { [regsub "Eastern Standard Time" $dt "EST" newdt] } {
    return $newdt
  } elseif { [regsub "Eastern Daylight Time" $dt "EDT" newdt] } {
    return $newdt
  } else {
    return $dt
  }
}

proc lunique { l } {
  # Return a new list containing only unique members of l
  foreach i $l {
    set a($i) 1
  }
  return [array names a]
}

proc GetAuthorsFromUpdateSummary { filename } {
  set Authors ""
  set expression {<Author>([^<]*)</Author>}
  if { ![file exists $filename] } { return $Authors }
  set f [open $filename r]
  while { ![eof $f] } {
    set line [gets $f]
    if { [regexp $expression $line foo a] } {
      lappend Authors $a
    }
  }
  close $f
  set Email [FormatEmailAddress [lunique $Authors]]
  return $Email
}


proc GetErrorsWarningsFromBuildSummary { filename } {
  set Errors 0
  set Warnings 0
  set eexpression {<ErrorCount>([^<]*)</ErrorCount>}
  set wexpression {<WarningCount>([^<]*)</WarningCount>}
  if { ![file exists $filename] } { return [list $Errors $Warnings] }
  set f [open $filename r]
  while { ![eof $f] } {
    set line [gets $f]
    if { [regexp $eexpression $line foo a] } {
      set Errors $a
    }
    if { [regexp $wexpression $line foo a] } {
      set Warnings $a
    }
  }
  close $f
  return [list $Errors $Warnings]
}

proc GetStatusFromConfigureSummary { filename } {
  set Status 0
  set sexpression {<ConfigureStatus>([^<]*)</ConfigureStatus>}
  if { ![file exists $filename] } { return $Status }
  set f [open $filename r]
  while { ![eof $f] } {
    set line [gets $f]
    if { [regexp $sexpression $line foo a] } {
      set Status $a
    }
  }
  close $f
  return $Status
}


proc GetCountsFromTestSummary { filename } {
  set Passed 0
  set NotRun 0
  set Failed 0
  set pexpression {<PassedCount>([^<]*)</PassedCount>}
  set fexpression {<FailedCount>([^<]*)</FailedCount>}
  set nexpression {<NotRunCount>([^<]*)</NotRunCount>}
  if { ![file exists $filename] } { return [list $NotRun $Failed $Passed] }
  set f [open $filename r]
  while { ![eof $f] } {
    set line [gets $f]
    if { [regexp $pexpression $line foo a] } {
      set Passed $a
    }
    if { [regexp $nexpression $line foo a] } {
      set NotRun $a
    }
    if { [regexp $fexpression $line foo a] } {
      set Failed $a
    }
  }
  close $f
  return [list $NotRun $Failed $Passed]
}


proc FormatEmailAddress { Addresses } {
  global Dart Users

  set r ""
  foreach Address $Addresses {
    set Address [string trim $Address]
    if { [info exists Users($Address)] } {
      # We have a lookup!
      set Address $Users($Address)
    }
    if { [string first "@" $Address] != -1 } {
      # Looks like a valid email address
      lappend r $Address
    } else {
      # Try to slap on the DefaultContinuousDomain variable
      if { [info exists Dart(DefaultContinuousDomain)] && $Dart(DefaultContinuousDomain) != "" } {
        lappend r "$Address@$Dart(DefaultContinuousDomain)"
      } elseif { [info exists Dart(CVSIdentToEmail)] && $Dart(CVSIdentToEmail) != "" } {
        set AuthorEmail ""
        foreach Rule $Dart(CVSIdentToEmail) {
          if { [regsub [lindex $Rule 0] $Address [lindex $Rule 1] AuthorEmail] } {
            break
          } else {
            set AuthorEmail {}
          }
        }
        if {$AuthorEmail == ""} {
          puts "\t\tERROR: Can't match $Address in CVSIdentToEmail"
        } elseif {$AuthorEmail != "DO_NOT_EMAIL"} {
          set r [concat $r $AuthorEmail]
        }
      }
    }
  }
  return $r
}

proc GetUsersList {} {
  global Users
  global Dart
  # Read in the user list
  set CheckFiles [list [file join $Dart(SourceDirectory) Documentation UserList.txt] \
                  [file join $Dart(SourceDirectory) CVSROOT users]]

  foreach File $CheckFiles {
    if {[file exists $File]} {
      set f [open $File]
      while { ![eof $f] } \
      {
        set l [split [string trim [gets $f]] ":"]
        switch [llength $l] \
        {
          3 {
            # No clue what this Insight style is, so I will just ignore it (ANDY)
            ## Insight style
            #set Users([lindex $l 0]) [lindex $l 2]
            #puts "Insight style: Users([lindex $l 0]) [lindex $l 2]"
            # Insight style
            set Users([lindex $l 0]) [lindex $l 1]
          }
          2 {
            # CVSROOT style
            set Users([lindex $l 0]) [lindex $l 1]
          }
        }
      }
      close $f
    }
  }
}

# A fileevent proc to immediately dump output, and set done when
# finished
proc DumpOutput { p out } {
  global done
  if { [eof $p] } {
    set done "Completed"
  } else {
    puts -nonewline $out [read $p 1]
  }
}

# This code handles fileevents and idle callbacks
proc UtilityReadFile { p } {
  global done Output
  if { [eof $p] } {
    set done "Completed"
  } else {
    if { [gets $p line] != -1 } {
      puts $Output "$line\n"
    }
  }
}

proc UtilityIdleTimeout {} {
  global done
  set done "Timeout"
}

proc RunTimedCommand { command Timeout LogFile } {
  global done
  global Dart
  global Output
  global tcl_platform
  # Setup a timer for the test.
  set Output [open $LogFile w]

  set p [open "| $command |&  [list $Dart(TclshCommand)] [file join $Dart(DartRoot) Source Client Cat.tcl]"]
  # If the gets operation blocks, then the tcl event loop
  # will never get a chance to see the timeout.
  fconfigure $p -blocking 0

  fileevent $p readable [list UtilityReadFile $p]
  set Callback [after [expr int($Timeout * 1000)] UtilityIdleTimeout]
  # Wait for a timeout, or the command to complete
  vwait done
  # Cancel the after callback, and the fileevent.
  after cancel $Callback
  fileevent $p readable ""

  # Assume we passed, until proven otherwise.
  set Status 0
  # If we timed out, kill the process, if we can.
  if { $done == "Timeout" } {
    set Status 1
    foreach PID [pid $p] {
      if { $tcl_platform(platform) == "windows" } {
        # this is a windows system, use the kill command distributed w/Dart
        catch { exec [file join $Dart(DartRoot) Source Utilities win32 bin kill.exe] $PID }
      } else {
        # this is a unix system, use standard kill command
        catch { exec kill $PID }
      }
    }
  }

  close $Output
  # Configure the command pipeline to be blocking before closing,
  # to ensure that close with a useful exit status.
  fconfigure $p -blocking 1
  return [close $p]
}