File: itkParallelSparseFieldLevelSetImageFilterBugFix.txx

package info (click to toggle)
itksnap 3.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 10,196 kB
  • ctags: 9,196
  • sloc: cpp: 62,895; sh: 175; makefile: 13
file content (2697 lines) | stat: -rw-r--r-- 95,513 bytes parent folder | download | duplicates (3)
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
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
/*======================================================================
  
Program:   Insight Segmentation & Registration Toolkit
Module:    $RCSfile: itkParallelSparseFieldLevelSetImageFilterBugFix.txx,v $
Language:  C++
Date:      $Date: 2008/10/24 12:52:08 $
Version:   $Revision: 1.1 $

Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

This software is distributed WITHOUT ANY WARRANTY; without even 
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
PURPOSE.  See the above copyright notices for more information.

======================================================================*/
#ifndef __itkParallelSparseFieldLevelSetImageFilterBugFix_txx_
#define __itkParallelSparseFieldLevelSetImageFilterBugFix_txx_

#include "itkParallelSparseFieldLevelSetImageFilterBugFix.h"
#include "itkZeroCrossingImageFilter.h"
#include "itkShiftScaleImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIterator.h"
#include "itkNumericTraits.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkMacro.h"
#include <iostream>
#include <fstream>

namespace itk {

template <class TNeighborhoodType>
ParallelSparseFieldCityBlockNeighborList<TNeighborhoodType>
::ParallelSparseFieldCityBlockNeighborList()
{
  typedef typename NeighborhoodType::ImageType ImageType;
  typename ImageType::Pointer dummy_image = ImageType::New();
  
  unsigned int i, nCenter;
  int d;
  OffsetType zero_offset;
  
  for (i = 0; i < Dimension; ++i)
    {
    m_Radius[i] = 1;
    zero_offset[i] = 0;
    }
  NeighborhoodType it(m_Radius, dummy_image, dummy_image->GetRequestedRegion());
  nCenter = it.Size() / 2;
  
  m_Size = 2 * Dimension;
  m_ArrayIndex.reserve(m_Size);
  m_NeighborhoodOffset.reserve(m_Size);
  
  for (i = 0; i < m_Size; ++i)
    {
    m_NeighborhoodOffset.push_back(zero_offset);
    }
  
  for (d = Dimension - 1, i = 0; d >= 0; --d, ++i)
    {
    m_ArrayIndex.push_back( nCenter - it.GetStride(d) );
    m_NeighborhoodOffset[i][d] = -1;
    }
  for (d = 0; d < static_cast<int> (Dimension); ++d, ++i)
    {
    m_ArrayIndex.push_back( nCenter + it.GetStride(d) );
    m_NeighborhoodOffset[i][d] = 1;
    }
  
  for (i = 0; i < Dimension; ++i)
    {
    m_StrideTable[i] = it.GetStride(i);
    }
}

template <class TNeighborhoodType>
void
ParallelSparseFieldCityBlockNeighborList<TNeighborhoodType>
::Print(std::ostream &os) const
{
  os << "ParallelSparseFieldCityBlockNeighborList: " << std::endl;
  for (unsigned i = 0; i < this->GetSize(); ++i)
    {
    os << "m_ArrayIndex[" << i << "]: " << m_ArrayIndex[i] << std::endl
       << "m_NeighborhoodOffset[" << i << "]: " << m_NeighborhoodOffset[i] << std::endl;
    }
}

//template<class TInputImage, class TOutputImage>
//double ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
//::m_ConstantGradientValue = 1.0;

template<class TInputImage, class TOutputImage>
ITK_TYPENAME ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>::ValueType
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::m_ValueOne = NumericTraits<ITK_TYPENAME ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage,
                                      TOutputImage>::ValueType >::One;

template<class TInputImage, class TOutputImage>
ITK_TYPENAME ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>::ValueType
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::m_ValueZero = NumericTraits<ITK_TYPENAME ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage,
                                             TOutputImage>::ValueType >::Zero;

template<class TInputImage, class TOutputImage>
ITK_TYPENAME ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>::StatusType
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::m_StatusNull = NumericTraits<ITK_TYPENAME ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage,
                                        TOutputImage>::StatusType >::NonpositiveMin();

template<class TInputImage, class TOutputImage>
ITK_TYPENAME ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>::StatusType
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::m_StatusChanging = -1;

template<class TInputImage, class TOutputImage>
ITK_TYPENAME ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>::StatusType
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::m_StatusActiveChangingUp = -2;

template<class TInputImage, class TOutputImage>
ITK_TYPENAME ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>::StatusType
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::m_StatusActiveChangingDown = -3;

template<class TInputImage, class TOutputImage>
ITK_TYPENAME ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>::StatusType
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::m_StatusBoundaryPixel = -4;

template<class TInputImage, class TOutputImage>
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ParallelSparseFieldLevelSetImageFilterBugFix()
{
  m_IsoSurfaceValue = m_ValueZero;
  m_NumberOfLayers = ImageDimension;
  this->SetRMSChange( static_cast<double>( m_ValueOne ) );
  m_InterpolateSurfaceLocation = true;
  m_BoundsCheckingActive = false;
  m_ConstantGradientValue = 1.0;
  m_GlobalZHistogram = 0;
  m_ZCumulativeFrequency = 0;
  m_MapZToThreadNumber = 0;
  m_Boundary = 0;
  m_Data = 0;
}

template<class TInputImage, class TOutputImage>
void 
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::GenerateData()
{
  if (this->GetState() == Superclass::UNINITIALIZED)
    {
    // Clean up any memory from any aborted previous filter executions.
    this->DeallocateData();
    
    // Allocate the output image
    m_OutputImage= this->GetOutput();
    m_OutputImage->SetBufferedRegion(m_OutputImage->GetRequestedRegion());
    m_OutputImage->Allocate();
    
    // Copy the input image to the output image.  Algorithms will operate
    // directly on the output image
    this->CopyInputToOutput();
    
    // Perform any other necessary pre-iteration initialization. 
    this->Initialize();
    this->SetElapsedIterations(0);
    
    //NOTE: Cannot set state to initialized yet since more initialization is
    //done in the Iterate method.
    
    }
  
  // Evolve the surface
  this->Iterate();
  
  // Clean up
  if (this->GetManualReinitialization() == false)
    {
    this->DeallocateData();
    this->SetStateToUninitialized(); // Reset the state once execution is
                                     // completed
    }
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::CopyInputToOutput()
{
  // This method is the first step in initializing the level-set image, which
  // is also the output of the filter.  The input is passed through a
  // zero crossing filter, which produces zero's at pixels closest to the zero
  // level set and one's elsewhere.  The actual zero level set values will be
  // adjusted in the Initialize() step to more accurately represent the
  // position of the zero level set.
  
  // First need to subtract the iso-surface value from the input image.
  typedef ShiftScaleImageFilter<InputImageType, OutputImageType> ShiftScaleFilterType;
  typename ShiftScaleFilterType::Pointer shiftScaleFilter = ShiftScaleFilterType::New();
  shiftScaleFilter->SetInput( this->GetInput()  );
  shiftScaleFilter->SetShift( - m_IsoSurfaceValue );
  // keep a handle to the shifted output
  m_ShiftedImage = shiftScaleFilter->GetOutput();
  
  typename ZeroCrossingImageFilter<OutputImageType, OutputImageType>::Pointer
    zeroCrossingFilter = ZeroCrossingImageFilter<OutputImageType,OutputImageType>::New();
  zeroCrossingFilter->SetInput(m_ShiftedImage);
  zeroCrossingFilter->GraftOutput(m_OutputImage);
  zeroCrossingFilter->SetBackgroundValue(m_ValueOne);
  zeroCrossingFilter->SetForegroundValue(m_ValueZero);
  zeroCrossingFilter->SetNumberOfThreads(1);
  zeroCrossingFilter->Update();
  
  // Here the output is the result of zerocrossings
  this->GraftOutput(zeroCrossingFilter->GetOutput());
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::Initialize()
{
  unsigned int i;

  // A node pool used during initialization of the level set.
  m_LayerNodeStore = LayerNodeStorageType::New();
  m_LayerNodeStore->SetGrowthStrategyToExponential();
  
  // Allocate the status image.
  m_StatusImage = StatusImageType::New();
  m_StatusImage->SetRegions(m_OutputImage->GetRequestedRegion());
  m_StatusImage->Allocate();
  
  // Initialize the status image to contain all m_StatusNull values.
  ImageRegionIterator<StatusImageType> statusIt(m_StatusImage,
                                 m_StatusImage->GetRequestedRegion());
  for (statusIt = statusIt.Begin(); ! statusIt.IsAtEnd(); ++statusIt)
    {
    statusIt.Set( m_StatusNull );
    }
  
  // Initialize the boundary pixels in the status images to
  // m_StatusBoundaryPixel values.  Uses the face calculator to find all of the
  // region faces.
  typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<StatusImageType>
    BFCType;
  
  BFCType faceCalculator;
  typename BFCType::FaceListType faceList;
  typename BFCType::SizeType sz;
  typename BFCType::FaceListType::iterator fit;
  
  sz.Fill(1);
  faceList = faceCalculator(m_StatusImage, m_StatusImage->GetRequestedRegion(),
                            sz);
  fit = faceList.begin();
  
  for (++fit; fit != faceList.end(); ++fit) // skip the first (nonboundary) region
    {
    statusIt = ImageRegionIterator<StatusImageType>(m_StatusImage, *fit);
    for (statusIt.GoToBegin(); ! statusIt.IsAtEnd(); ++statusIt)
      {
      statusIt.Set( m_StatusBoundaryPixel );
      }
    }
  
  // Allocate the layers of the sparse field.
  m_Layers.reserve(2 * m_NumberOfLayers + 1);
  for (i = 0; i < 2 * static_cast<unsigned int>(m_NumberOfLayers) + 1; ++i)
    {
    m_Layers.push_back( LayerType::New() );
    }
  
  m_SplitAxis  = m_OutputImage->GetImageDimension() - 1; // always the "Z" dimension
  if (m_OutputImage->GetImageDimension() < 1)
    {
      // cannot split
      itkDebugMacro ("Unable to choose an axis for workload distribution among threads");
      return;
    }
  
  typename OutputImageType::SizeType requestedRegionSize
    = m_OutputImage->GetRequestedRegion().GetSize();
  m_ZSize = requestedRegionSize[m_SplitAxis];

  // Histogram of number of pixels in each Z plane for the entire 3D volume
  m_GlobalZHistogram = new int[m_ZSize];
  for (i = 0; i < m_ZSize; i++)
    {
    m_GlobalZHistogram[i] = 0;
    }
  
  // Construct the active layer and initialize the first layers inside and
  // outside of the active layer
  this->ConstructActiveLayer();
  
  // Construct the rest of the non active set layers using the first two
  // layers. Inside layers are odd numbers, outside layers are even numbers.
  for (i = 1; i < m_Layers.size() - 2; ++i)
    {
    this->ConstructLayer(i, i+2);
    }
  
  // Set the values in the output image for the active layer.
  this->InitializeActiveLayerValues();
  
  // Initialize layer values using the active layer as seeds.
  this->PropagateAllLayerValues();
  
  // Initialize pixels inside and outside the sparse field layers to positive
  // and negative values, respectively.  This is not necessary for the
  // calculations, but is useful for presenting a more intuitive output to the
  // filter.  See PostProcessOutput method for more information.
  this->InitializeBackgroundPixels();
  
  m_NumOfThreads = this->GetNumberOfThreads();
  
  // Cumulative frequency of number of pixels in each Z plane for the entire 3D
  // volume 
  m_ZCumulativeFrequency = new int[m_ZSize];
  for (i = 0; i < m_ZSize; i++)
    {
    m_ZCumulativeFrequency[i] = 0;
    }

  // The mapping from a z-value to the thread in whose region the z-value lies 
  m_MapZToThreadNumber = new unsigned int[m_ZSize];
  for (i = 0; i < m_ZSize; i++)
    {
    m_MapZToThreadNumber[i] = 0;
    }
  
  // The boundaries defining thread regions
  m_Boundary = new unsigned int[m_NumOfThreads];
  for (i = 0; i < m_NumOfThreads; i++)
    {
    m_Boundary[i] = 0;
    }

  // A boolean variable stating if the boundaries had been changed during
  // CheckLoadBalance()
  m_BoundaryChanged = false;
  
  // A global barrier for all threads.
  m_Barrier = Barrier::New();
  m_Barrier->Initialize(m_NumOfThreads);
  
  // Allocate data for each thread.
  m_Data = new ThreadData[m_NumOfThreads];
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ConstructActiveLayer()
{
  // We find the active layer by searching for 0's in the zero crossing image
  // (output image).  The first inside and outside layers are also constructed
  // by searching the neighbors of the active layer in the (shifted) input image.
  // Negative neighbors not in the active set are assigned to the inside,
  // positive neighbors are assigned to the outside.
  
  NeighborhoodIterator<OutputImageType> shiftedIt(m_NeighborList.GetRadius(),
                          m_ShiftedImage, m_OutputImage->GetRequestedRegion());
  NeighborhoodIterator<OutputImageType> outputIt (m_NeighborList.GetRadius(),
                          m_OutputImage, m_OutputImage->GetRequestedRegion());
  NeighborhoodIterator<StatusImageType> statusIt (m_NeighborList.GetRadius(),
                          m_StatusImage, m_OutputImage->GetRequestedRegion());
  
  IndexType center_index, offset_index;
  LayerNodeType *node;
  bool bounds_status = true;
  ValueType value;
  StatusType layer_number;
  
  typename OutputImageType::SizeType regionSize
    = m_OutputImage->GetRequestedRegion().GetSize();
  typename OutputImageType::IndexType startIndex
    = m_OutputImage->GetRequestedRegion().GetIndex();;
  typedef typename OutputImageType::IndexType::IndexValueType StartIndexValueType;
  
  for (outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt)
    {
    bounds_status = true;
    if ( outputIt.GetCenterPixel() == m_ValueZero )
      {
      // Grab the neighborhood in the status image.
      center_index = outputIt.GetIndex();
      statusIt.SetLocation( center_index );
      
      for(unsigned int j = 0; j < ImageDimension; j++)
        {
        if ( (center_index[j]) <= (startIndex[j]) ||
             (center_index[j]) >= startIndex[j] +
              static_cast<StartIndexValueType>(regionSize[j]-1))
          {
          bounds_status = false;
          break;
          }
        }
      if(bounds_status == true)
        {
        // Here record the hisgram information
        m_GlobalZHistogram[ center_index[m_SplitAxis] ]++;
        
        // Borrow a node from the store and set its value.
        node = m_LayerNodeStore->Borrow();
        node->m_Index = center_index;
        
        // Add the node to the active list and set the status in the status
        // image.
        m_Layers[0]->PushFront( node );
        statusIt.SetCenterPixel( 0 );
        
        // Grab the neighborhood in the image of shifted input values.
        shiftedIt.SetLocation( center_index );
        
        // Search the neighborhood pixels for first inside & outside layer
        // members.  Construct these lists and set status list values. 
        for (unsigned int i = 0; i < m_NeighborList.GetSize(); ++i)
          {
          offset_index = center_index + m_NeighborList.GetNeighborhoodOffset(i);
          
          if ( outputIt.GetPixel(m_NeighborList.GetArrayIndex(i)) != m_ValueZero &&
               statusIt.GetPixel(m_NeighborList.GetArrayIndex(i)) == m_StatusNull)
            {
            value = shiftedIt.GetPixel(m_NeighborList.GetArrayIndex(i));
            
            if ( value < m_ValueZero ) // Assign to first outside layer.
              {
              layer_number = 1;
              }
            else // Assign to first inside layer
              {
              layer_number = 2;
              }
            
            statusIt.SetPixel( m_NeighborList.GetArrayIndex(i), layer_number, bounds_status );
            if ( bounds_status == true ) // In bounds
              {
              node = m_LayerNodeStore->Borrow();
              node->m_Index = offset_index;
              m_Layers[layer_number]->PushFront( node );
              } // else do nothing.
            }
          }
        }
      }
    }
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ConstructLayer(StatusType from, StatusType to)
{
  LayerNodeType *node;
  bool boundary_status;
  typename LayerType::ConstIterator fromIt;
  NeighborhoodIterator<StatusImageType> statusIt(m_NeighborList.GetRadius(), m_StatusImage,
                                                 m_OutputImage->GetRequestedRegion() );
  
  // For all indicies in the "from" layer...
  for (fromIt = m_Layers[from]->Begin(); fromIt != m_Layers[from]->End(); ++fromIt)
    {
    // Search the neighborhood of this index in the status image for
    // unassigned indicies. Push those indicies onto the "to" layer and
    // assign them values in the status image.  Status pixels outside the
    // boundary will be ignored.
    statusIt.SetLocation( fromIt->m_Index );
    
    for (unsigned int i = 0; i < m_NeighborList.GetSize(); ++i)
      {
      if ( statusIt.GetPixel( m_NeighborList.GetArrayIndex(i) ) == m_StatusNull )
        {
        statusIt.SetPixel(m_NeighborList.GetArrayIndex(i), to, boundary_status);
        
        if (boundary_status == true) // in bounds
          {
          node = m_LayerNodeStore->Borrow();
          node->m_Index = statusIt.GetIndex() + m_NeighborList.GetNeighborhoodOffset(i);
          m_Layers[to]->PushFront( node );
          }
        }
      }
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::InitializeActiveLayerValues()
{
  const ValueType CHANGE_FACTOR = m_ConstantGradientValue / 2.0;
  ValueType MIN_NORM      = 1.0e-6;
  if (this->GetUseImageSpacing())
    {
    double minSpacing = NumericTraits<double>::max();
    for (unsigned int i=0; i<ImageDimension; i++)
      {
      minSpacing = vnl_math_min(minSpacing,this->GetInput()->GetSpacing()[i]);
      }
    MIN_NORM *= minSpacing;
    }

  typename LayerType::ConstIterator activeIt;
  ConstNeighborhoodIterator<OutputImageType>shiftedIt (m_NeighborList.GetRadius(), m_ShiftedImage,
                                                       m_OutputImage->GetRequestedRegion());
  
  unsigned int center = shiftedIt.Size() /2;
  unsigned int stride;

  const NeighborhoodScalesType neighborhoodScales = this->GetDifferenceFunction()->ComputeNeighborhoodScales();

  ValueType dx_forward, dx_backward, length, distance;
  
  // For all indicies in the active layer...
  for (activeIt = m_Layers[0]->Begin(); activeIt != m_Layers[0]->End(); ++activeIt)
    {
    // Interpolate on the (shifted) input image values at this index to
    // assign an active layer value in the output image.
    shiftedIt.SetLocation( activeIt->m_Index );
    
    length = m_ValueZero;
    for (unsigned int i = 0; i < static_cast<unsigned int>(ImageDimension); ++i)
      {
      stride = shiftedIt.GetStride(i);
 
      dx_forward  = ( shiftedIt.GetPixel(center + stride) - shiftedIt.GetCenterPixel() ) * neighborhoodScales[i];
      dx_backward = ( shiftedIt.GetCenterPixel()          - shiftedIt.GetPixel(center - stride) ) * neighborhoodScales[i];

      if ( vnl_math_abs(dx_forward) > vnl_math_abs(dx_backward) )
        {
        length += dx_forward  * dx_forward;
        }
      else
        {
        length += dx_backward * dx_backward;
        }
      }
    length = vcl_sqrt(length) + MIN_NORM;
    distance = shiftedIt.GetCenterPixel() / length;
    
    m_OutputImage->SetPixel( activeIt->m_Index ,
        vnl_math_min(vnl_math_max(-CHANGE_FACTOR, distance), CHANGE_FACTOR));
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::PropagateAllLayerValues()
{
  // Update values in the first inside and first outside layers using the
  // active layer as a seed. Inside layers are odd numbers, outside layers are
  // even numbers. 
  this->PropagateLayerValues (0, 1, 3, 1); // first inside
  this->PropagateLayerValues (0, 2, 4, 0); // first outside
  
  // Update the rest of the layers.
  for (unsigned int i = 1; i < m_Layers.size() - 2; ++i)
    {
    this->PropagateLayerValues (i, i+2, i+4, (i+2)%2);
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::PropagateLayerValues(StatusType from, StatusType to, StatusType promote, unsigned int InOrOut)
{
  unsigned int i;
  ValueType value, value_temp, delta;
  bool found_neighbor_flag;
  LayerNodeType* node;
  StatusType past_end = static_cast<StatusType>( m_Layers.size() ) - 1;
  
  // Are we propagating values inward (more negative) or outward (more positive)?
  if (InOrOut == 1)
    {
    delta = - m_ConstantGradientValue; // inward
    }
  else
    {
    delta =   m_ConstantGradientValue;
    }
  
  NeighborhoodIterator<OutputImageType> outputIt (m_NeighborList.GetRadius(), m_OutputImage,
                                                  m_OutputImage->GetRequestedRegion());
  NeighborhoodIterator<StatusImageType> statusIt (m_NeighborList.GetRadius(), m_StatusImage,
                                                  m_OutputImage->GetRequestedRegion());
  
  typename LayerType::Iterator toIt = m_Layers[to]->Begin();
  while ( toIt != m_Layers[to]->End() )
    {
    statusIt.SetLocation( toIt->m_Index );
    // Is this index marked for deletion? If the status image has
    // been marked with another layer's value, we need to delete this node
    // from the current list then skip to the next iteration.
    if (statusIt.GetCenterPixel() != to)
      {
      node = toIt.GetPointer();
      ++toIt;
      m_Layers[to]->Unlink( node );
      m_LayerNodeStore->Return( node );
      continue;
      }
    
    outputIt.SetLocation( toIt->m_Index );
    
    value = m_ValueZero;
    found_neighbor_flag = false;
    for (i = 0; i < m_NeighborList.GetSize(); ++i)
      {
      // If this neighbor is in the "from" list, compare its absolute value
      // to any previous values found in the "from" list.  Keep the value
      // that will cause the next layer to be closest to the zero level set.
      if ( statusIt.GetPixel( m_NeighborList.GetArrayIndex(i) ) == from )
        {
        value_temp = outputIt.GetPixel( m_NeighborList.GetArrayIndex(i) );
        
        if (found_neighbor_flag == false)
          {
          value = value_temp;
          }
        else
          {
            if (vnl_math_abs(value_temp+delta) < vnl_math_abs(value+delta))
              {
                // take the value closest to zero
                value= value_temp;
              }
          }
        found_neighbor_flag = true;
        }
      }
    if (found_neighbor_flag == true)
      {
      // Set the new value using the smallest magnitude
      // found in our "from" neighbors.
      outputIt.SetCenterPixel( value + delta );
      ++toIt;
      }
    else
      {
      // Did not find any neighbors on the "from" list, then promote this
      // node.  A "promote" value past the end of my sparse field size
      // means delete the node instead.  Change the status value in the
      // status image accordingly.
      node  = toIt.GetPointer();
      ++toIt;
      m_Layers[to]->Unlink( node );
      if ( promote > past_end )
        {
        m_LayerNodeStore->Return( node );
        statusIt.SetCenterPixel(m_StatusNull);
        }
      else
        {
        m_Layers[promote]->PushFront( node );
        statusIt.SetCenterPixel(promote);
        }
      }
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::InitializeBackgroundPixels()
{
  // Assign background pixels INSIDE the sparse field layers to a new level set
  // with value less than the innermost layer.  Assign background pixels
  // OUTSIDE the sparse field layers to a new level set with value greater than
  // the outermost layer.
  const ValueType max_layer = static_cast<ValueType>(m_NumberOfLayers);
  
  const ValueType outside_value  = (max_layer+1) * m_ConstantGradientValue;
  const ValueType inside_value = -(max_layer+1) * m_ConstantGradientValue;

  ImageRegionConstIterator<StatusImageType> statusIt(m_StatusImage,
                                                     this->GetOutput()->GetRequestedRegion());

  ImageRegionIterator<OutputImageType> outputIt(this->GetOutput(),
                                                this->GetOutput()->GetRequestedRegion());

  ImageRegionConstIterator<OutputImageType> shiftedIt(m_ShiftedImage,
                                                      this->GetOutput()->GetRequestedRegion());
  
  for (outputIt = outputIt.Begin(), statusIt = statusIt.Begin(),
         shiftedIt = shiftedIt.Begin();
       ! outputIt.IsAtEnd(); ++outputIt, ++statusIt, ++shiftedIt)
    {
    if (statusIt.Get() == m_StatusNull || statusIt.Get() == m_StatusBoundaryPixel)
      {
      if (shiftedIt.Get() > m_ValueZero)
        {
        outputIt.Set(outside_value);
        }
      else
        {
        outputIt.Set(inside_value);
        }
      }
    }
  
  // deallocate the shifted-image
  m_ShiftedImage = 0;
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ComputeInitialThreadBoundaries()
{
  // NOTE: Properties of the boundary computation algorithm
  //       1. Thread-0 always has something to work on.
  //       2. If a particular thread numbered i has the m_Boundary = (mZSize -
  //          1) then ALL threads numbered > i do NOT have anything to work on.
  
  // Compute the cumulative frequency distribution using the global histogram.
  unsigned int i, j;
  m_ZCumulativeFrequency[0] = m_GlobalZHistogram[0];
  for (i= 1; i < m_ZSize; i++)
    {
    m_ZCumulativeFrequency[i] = m_ZCumulativeFrequency[i-1] + m_GlobalZHistogram[i];
    }
  
  // Now define the regions that each thread will process and the corresponding
  // boundaries. 
  m_Boundary[m_NumOfThreads - 1] = m_ZSize - 1; // special case: the upper
                                                // bound for the last thread
  for (i= 0; i < m_NumOfThreads - 1; i++)
    {
    // compute m_Boundary[i]
    
    float cutOff = 1.0 * (i+1) * m_ZCumulativeFrequency[m_ZSize-1] / m_NumOfThreads;
    
    // find the position in the cumulative freq dist where this cutoff is met
    for (j = (i == 0 ? 0 : m_Boundary[i-1]); j < m_ZSize; j++)
      {
      if (cutOff > m_ZCumulativeFrequency[j])
        {
        continue;
        }
      else
        {
        // Optimize a little.
        // Go further FORWARD and find the first index (k) in the cumulative
        // freq distribution s.t. m_ZCumulativeFrequency[k] !=
        // m_ZCumulativeFrequency[j] This is to be done because if we have a
        // flat patch in the cumulative freq. dist. then we can choose
        // a bound midway in that flat patch .
        unsigned int k;
        for (k= 1; j+k < m_ZSize; k++)
          {
          if (m_ZCumulativeFrequency[j+k] != m_ZCumulativeFrequency[j])
            {
            break;
            }
          }
        
        // 
        m_Boundary[i]= static_cast<unsigned int>( (j + k / 2) );
        break;
        }
      }
    }
  
  // Initialize the local histograms using the global one and the boundaries
  // Also initialize the mapping from the Z value --> the thread number
  // i.e. m_MapZToThreadNumber[] 
  // Also divide the lists up according to the boundaries
  for (i = 0; i <= m_Boundary[0]; i++)
    {
    // this Z belongs to the region associated with thread-0
    m_MapZToThreadNumber[i]= 0;
    }
  
  for (unsigned int t= 1; t < m_NumOfThreads; t++)
    {
    for (i = m_Boundary[t-1]+1; i <= m_Boundary[t]; i++)
      {
      // this Z belongs to the region associated with thread-0
      m_MapZToThreadNumber[i]= t;
      }
    }
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedAllocateData (unsigned int ThreadId)
{
  static const float SAFETY_FACTOR = 4.0;
  unsigned int i, j;
  // create semaphores
  m_Data[ThreadId].m_Semaphore[0] = Semaphore::New ();
  m_Data[ThreadId].m_Semaphore[1] = Semaphore::New ();
  m_Data[ThreadId].m_Semaphore[0]->Initialize(0);
  m_Data[ThreadId].m_Semaphore[1]->Initialize(0);
  
  // Allocate the layers for the sparse field.
  m_Data[ThreadId].m_Layers.reserve(2 * m_NumberOfLayers + 1);
  for (i = 0; i < 2 * static_cast<unsigned int>(m_NumberOfLayers) + 1; ++i)
    {
      m_Data[ThreadId].m_Layers.push_back( LayerType::New() );
    }
  // Throw an exception if we don't have enough layers.
  if (m_Data[ThreadId].m_Layers.size() < 3)
    {
    itkExceptionMacro( << "Not enough layers have been allocated for the sparse" 
                       << "field. Requires at least one layer." ); 
    }
  
  // Layers used as buffers for transfering pixels during load balancing
  m_Data[ThreadId].m_LoadTransferBufferLayers
    = new LayerListType[2*m_NumberOfLayers+1];
  for (i = 0; i < 2 * static_cast<unsigned int>(m_NumberOfLayers) + 1; i++)
    {
    m_Data[ThreadId].m_LoadTransferBufferLayers[i].reserve( m_NumOfThreads );
    
    for (j = 0; j < m_NumOfThreads; j++)
      {
      m_Data[ThreadId].m_LoadTransferBufferLayers[i].push_back(LayerType::New());
      }
    }
  
  // Every thread allocates a local node pool (improving memory locality)
  m_Data[ThreadId].m_LayerNodeStore = LayerNodeStorageType::New();
  m_Data[ThreadId].m_LayerNodeStore->SetGrowthStrategyToExponential();

  // The SAFETY_FACTOR simple ensures that the number of nodes created
  // is larger than those required to start with for each thread.
  unsigned int nodeNum= static_cast<unsigned int>(SAFETY_FACTOR * m_Layers[0]->Size()
                                * (2*m_NumberOfLayers+1) / m_NumOfThreads);

  m_Data[ThreadId].m_LayerNodeStore->Reserve(nodeNum);
  m_Data[ThreadId].m_RMSChange = m_ValueZero;
  
  // UpLists and Downlists
  for (i = 0; i < 2; ++i)
    {
      m_Data[ThreadId].UpList[i] = LayerType::New();
      m_Data[ThreadId].DownList[i] = LayerType::New();
    }
  
  // Used during the time when status lists are being processed (in ThreadedApplyUpdate() )
  // for the Uplists
  m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[0]
    = new LayerPointerType * [m_NumberOfLayers + 1];

  // for the Downlists
  m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[1]
    = new LayerPointerType * [m_NumberOfLayers + 1];
  
  for (i= 0; i < static_cast<unsigned int>(m_NumberOfLayers) + 1; i++)
    {
    m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[0][i] =
      new LayerPointerType[m_NumOfThreads];
    m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[1][i] =
      new LayerPointerType[m_NumOfThreads];
    }
  
  for (i= 0; i < static_cast<unsigned int>(m_NumberOfLayers) + 1; i++)
    {
    for (j= 0; j < m_NumOfThreads; j++)
      {
      m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[0][i][j]
        = LayerType::New();
      m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[1][i][j]
        = LayerType::New();
      }
    }
  
  // Local histogram for every thread (used during Iterate() )
  m_Data[ThreadId].m_ZHistogram = new int[m_ZSize];
  for (i = 0; i < m_ZSize; i++)
    {
    m_Data[ThreadId].m_ZHistogram[i] = 0;
    }
  
  // Every thread must have its own copy of the the GlobalData struct.
  m_Data[ThreadId].globalData
    = this->GetDifferenceFunction()->GetGlobalDataPointer();
  
  //
  m_Data[ThreadId].m_SemaphoreArrayNumber = 0;
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedInitializeData(unsigned int ThreadId, const ThreadRegionType & ThreadRegion)
{
  // divide the lists based on the boundaries
  
  LayerNodeType * nodePtr, * nodeTempPtr;
  
  for (unsigned int i = 0; i < 2 * static_cast<unsigned int>(m_NumberOfLayers) + 1; i++)
    {
    typename LayerType::Iterator layerIt = m_Layers[i]->Begin();
    typename LayerType::Iterator layerEnd= m_Layers[i]->End();
    
    while (layerIt != layerEnd)
      {
      nodePtr = layerIt.GetPointer();
      ++layerIt;
      
      unsigned int k = this->GetThreadNumber(nodePtr->m_Index[m_SplitAxis]);
      if (k != ThreadId)
        {
        continue; // some other thread's node => ignore
        }
      
      // Borrow a node from the specific thread's layer so that MEMORY LOCALITY
      // is maintained.
      // NOTE : We already pre-allocated more than enough
      // nodes for each thread implying no new nodes are created here.
      nodeTempPtr= m_Data[ThreadId].m_LayerNodeStore->Borrow ();
      nodeTempPtr->m_Index= nodePtr->m_Index;
      // push the node on the approproate layer
      m_Data[ThreadId].m_Layers[i]->PushFront(nodeTempPtr);
      
      // for the active layer (layer-0) build the histogram for each thread
      if (i == 0)
        {
        // this Z histogram value should be given to thread-0
        m_Data[ThreadId].m_ZHistogram[ (nodePtr->m_Index)[m_SplitAxis] ]
          = m_Data[ThreadId].m_ZHistogram[ (nodePtr->m_Index)[m_SplitAxis] ] + 1;
        }
      }
    }
  
  // Make use of the SGI default "first-touch" memory placement policy
  // Copy from the current status/output images to the new ones and let each
  // thread do the copy of its own region.
  // This will make each thread be the FIRST to write to "it's" data in the new
  // images and hence the memory will get allocated 
  // in the corresponding thread's memory-node.
  ImageRegionConstIterator<StatusImageType> statusIt(m_StatusImage, ThreadRegion);
  ImageRegionIterator<StatusImageType> statusItNew (m_StatusImageTemp, ThreadRegion);
  ImageRegionConstIterator<OutputImageType> outputIt(m_OutputImage, ThreadRegion);
  ImageRegionIterator<OutputImageType> outputItNew(m_OutputImageTemp, ThreadRegion);
  
  for (outputIt = outputIt.Begin(), statusIt = statusIt.Begin(),
         outputItNew = outputItNew.Begin(), statusItNew = statusItNew.Begin();
       ! outputIt.IsAtEnd();  ++outputIt, ++statusIt, ++outputItNew, ++statusItNew)
    {
    statusItNew.Set (statusIt.Get());
    outputItNew.Set (outputIt.Get());
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::DeallocateData()
{
  unsigned int i, j;
  // Delete data structures used for load distribution and balancing.
  if ( m_GlobalZHistogram != 0 )
    {
    delete [] m_GlobalZHistogram;
    m_GlobalZHistogram = 0;
    }
  if ( m_ZCumulativeFrequency != 0 )
    {
    delete [] m_ZCumulativeFrequency;
    m_ZCumulativeFrequency = 0;
    }
  if ( m_MapZToThreadNumber != 0 )
    {
    delete [] m_MapZToThreadNumber;
    m_MapZToThreadNumber = 0;
    }
  if (m_Boundary != 0)
    {
    delete [] m_Boundary;
    m_Boundary = 0;
    }
  
  // Deallocate the status image.
  m_StatusImage= 0;
  
  // Remove the barrier from the system.
  //  m_Barrier->Remove ();
  
  // Delete initial nodes, the node pool, the layers.
  if (! m_Layers.empty())
    {
    for (i = 0; i < 2* static_cast<unsigned int>(m_NumberOfLayers)+1; i++)
      {
      // return all the nodes in layer i to the main node pool
      LayerNodeType * nodePtr= 0;
      LayerPointerType layerPtr= m_Layers[i];
      while (! layerPtr->Empty())
        {
        nodePtr= layerPtr->Front();
        layerPtr->PopFront();
        m_LayerNodeStore->Return (nodePtr);
        }
      }
    }
  if (m_LayerNodeStore)
    {
    m_LayerNodeStore->Clear();
    m_Layers.clear();
    }

  if (m_Data != 0)
    {
    // Deallocate the thread local data structures.
    for (unsigned int ThreadId= 0; ThreadId < m_NumOfThreads; ThreadId++)
      {
      // Remove semaphores from the system.
      m_Data[ThreadId].m_Semaphore[0]->Remove();
      m_Data[ThreadId].m_Semaphore[1]->Remove();
      
      delete [] m_Data[ThreadId].m_ZHistogram;
      
      if (m_Data[ThreadId].globalData != 0)
        {
        this->GetDifferenceFunction()->ReleaseGlobalDataPointer (m_Data[ThreadId].globalData);
        m_Data[ThreadId].globalData= 0;
        }
      
      // 1. delete nodes on the thread layers
      for (i = 0; i < 2 * static_cast<unsigned int>(m_NumberOfLayers) + 1; i++)
        {
        // return all the nodes in layer i to thread-i's node pool
        LayerNodeType * nodePtr;
        LayerPointerType layerPtr= m_Data[ThreadId].m_Layers[i];
        while (! layerPtr->Empty())
          {
          nodePtr= layerPtr->Front();
          layerPtr->PopFront();
          m_Data[ThreadId].m_LayerNodeStore->Return(nodePtr);
          }
        }
      m_Data[ThreadId].m_Layers.clear();
      
      // 2. cleanup the LoadTransferBufferLayers: empty all and return the nodes
      // to the pool 
      for (i = 0; i < 2 * static_cast<unsigned int>(m_NumberOfLayers) + 1; i++)
        {
        for (j= 0; j < m_NumOfThreads; j++)
          {
          if (j == ThreadId)
            {
            // a thread does NOT pass nodes to istelf
            continue;
            }
          
          LayerNodeType * nodePtr;
          LayerPointerType layerPtr= m_Data[ThreadId].m_LoadTransferBufferLayers[i][j];
          
          while (! layerPtr->Empty())
            {
            nodePtr= layerPtr->Front();
            layerPtr->PopFront();
            m_Data[ThreadId].m_LayerNodeStore->Return (nodePtr);
            }
          }
        m_Data[ThreadId].m_LoadTransferBufferLayers[i].clear();
        }
      delete [] m_Data[ThreadId].m_LoadTransferBufferLayers;
      
      // 3. clear up the nodes in the last layer of m_InterNeighborNodeTransferBufferLayers (if any)
      for (i= 0; i < m_NumOfThreads; i++)
        {
        LayerNodeType* nodePtr;
        for (unsigned int InOrOut= 0; InOrOut < 2; InOrOut++)
          {
          LayerPointerType layerPtr
            = m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[InOrOut][m_NumberOfLayers][i];
          
          while (! layerPtr->Empty())
            {
            nodePtr= layerPtr->Front();
            layerPtr->PopFront();
            m_Data[ThreadId].m_LayerNodeStore->Return(nodePtr);
            }
          }
        }
    
      // check if all last layers are empty and then delete them
      for (i = 0; i < static_cast<unsigned int>(m_NumberOfLayers) + 1; i++)
        {
        delete [] m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[0][i];
        delete [] m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[1][i];
        }
      delete [] m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[0];
      delete [] m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[1];
      
      // 4. check if all the uplists and downlists are empty
      
      // 5. delete all nodes in the node pool
      m_Data[ThreadId].m_LayerNodeStore->Clear();
      }
  
    delete [] m_Data;
    } // if m_data != 0
  m_Data= 0;
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedInitializeIteration (unsigned int itkNotUsed(ThreadId))
{
  // If child classes need an entry point to the start of every iteration step
  // they can override this method.
  return;
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::Iterate()
{
  // Set up for multithreaded processing
  ParallelSparseFieldLevelSetThreadStruct str;
  str.Filter = this;
  str.TimeStep = NumericTraits<TimeStepType>::Zero;
  
  this->GetMultiThreader()->SetNumberOfThreads (m_NumOfThreads);
  
  // Initialize the list of time step values that will be generated by the
  // various threads.  There is one distinct slot for each possible thread,
  // so this data structure is thread-safe.
  str.TimeStepList      = new TimeStepType[m_NumOfThreads];
  str.ValidTimeStepList = new bool        [m_NumOfThreads];
  
  for (unsigned int i =0; i < m_NumOfThreads; ++i)
    {
    str.ValidTimeStepList[i] = true;
    }
  
  // Multithread the execution
  this->GetMultiThreader()->SetSingleMethod(this->IterateThreaderCallback, &str);
  // It is this method that will results in the creation of the threads
  this->GetMultiThreader()->SingleMethodExecute ();
  
  delete [] str.TimeStepList;
  delete [] str.ValidTimeStepList;
}

template<class TInputImage, class TOutputImage>
ITK_THREAD_RETURN_TYPE
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::IterateThreaderCallback(void * arg)
{
  // Controls how often we check for balance of the load among the threads and perform
  // load balancing (if needed) by redistributing the load.
  const unsigned int LOAD_BALANCE_ITERATION_FREQUENCY = 30;
  
  unsigned int i;
  unsigned int ThreadId = ((MultiThreader::ThreadInfoStruct *)(arg))->ThreadID;
  
  ParallelSparseFieldLevelSetThreadStruct * str
    = (ParallelSparseFieldLevelSetThreadStruct *)
    (((MultiThreader::ThreadInfoStruct *)(arg))->UserData);


#ifdef ITK_USE_SPROC
  // Every thread should 'usadd' itself to the arena as the very first thing so
  // as to detect errors (if any) early.
  if (str->Filter->GetState() == Superclass::UNINITIALIZED)
    {
    if (MultiThreader::GetThreadArena() != 0)
      {
      int code= usadd (MultiThreader::GetThreadArena());
      if (code != 0)
        {
        OStringStream message;
        message << "Thread failed to join SGI arena: error";
        throw ::itk::ExceptionObject(__FILE__, __LINE__, message.str().c_str(),ITK_LOCATION);
        }
      }
    }
#endif
  
  // allocate thread data: every thread allocates its own data
  // We do NOT assume here that malloc is thread safe: hence make threads
  // allocate data serially
  if (str->Filter->GetState() == Superclass::UNINITIALIZED)
    {
    if (ThreadId == 0)
      {
      str->Filter->ComputeInitialThreadBoundaries ();
      
      // Create the temporary status image
      str->Filter->m_StatusImageTemp = StatusImageType::New();
      str->Filter->m_StatusImageTemp->SetRegions(str->Filter->m_OutputImage->GetRequestedRegion()); 
      str->Filter->m_StatusImageTemp->Allocate();
      
      // Create the temporary output image
      str->Filter->m_OutputImageTemp = OutputImageType::New();
      str->Filter->m_OutputImageTemp->SetRegions(str->Filter->m_OutputImage->GetRequestedRegion());
      str->Filter->m_OutputImageTemp->Allocate();
      }
    str->Filter->WaitForAll();
  
    // Data allocation performed serially.
    for (i= 0; i < str->Filter->m_NumOfThreads; i++)
      {
      if (ThreadId == i)
        {
        str->Filter->ThreadedAllocateData   (ThreadId);
        }
      str->Filter->WaitForAll();
      }
  
    // Data initialization performed in parallel.
    // Make use of the SGI default first-touch memory placement policy
    str->Filter->GetThreadRegionSplitByBoundary(ThreadId,
                                                str->Filter->m_Data[ThreadId].ThreadRegion);
    str->Filter->ThreadedInitializeData(ThreadId,
                                        str->Filter->m_Data[ThreadId].ThreadRegion);
    str->Filter->WaitForAll();
    
    if (ThreadId == 0)
      {
      str->Filter->m_StatusImage = 0;
      str->Filter->m_StatusImage = str->Filter->m_StatusImageTemp;
      str->Filter->m_StatusImageTemp = 0;
      
      str->Filter->m_OutputImage = 0;
      str->Filter->m_OutputImage = str->Filter->m_OutputImageTemp;
      str->Filter->m_OutputImageTemp = 0;
      //
      str->Filter->GraftOutput(str->Filter->m_OutputImage);
      }
    str->Filter->WaitForAll();
    str->Filter->SetStateToInitialized();
    }
  
  unsigned int iter = str->Filter->GetElapsedIterations();
  while (! (str->Filter->ThreadedHalt(arg)) )
    {
    str->Filter->ThreadedInitializeIteration(ThreadId);
    
    // Threaded Calculate Change
    str->Filter->m_Data[ThreadId].TimeStep
      = str->Filter->ThreadedCalculateChange(ThreadId);
    
    str->Filter->WaitForAll();

    // Handle AbortGenerateData()
    if (str->Filter->m_NumOfThreads == 1 || ThreadId == 0)
      {
      if( str->Filter->GetAbortGenerateData() )
        {
        str->Filter->InvokeEvent( IterationEvent() );
        str->Filter->ResetPipeline(); 
        ProcessAborted e(__FILE__,__LINE__);
        e.SetDescription("Process aborted.");
        e.SetLocation(ITK_LOCATION);
        throw e;
        }
      }
    
    // Calculate the timestep (no need to do this when there is just 1 thread)
    if (str->Filter->m_NumOfThreads == 1)
      {
      if (iter != 0)
        {
        // Update the RMS difference here
        str->Filter->SetRMSChange( static_cast<double>(str->Filter->m_Data[0].m_RMSChange));
        unsigned int count = str->Filter->m_Data[0].m_Count;
        if (count != 0)
          {
          str->Filter->SetRMSChange( static_cast<double>(vcl_sqrt(
                (static_cast<float> (str->Filter->GetRMSChange())) / count)));
          }
        }
      
      // this is done by the thread0
      str->Filter->InvokeEvent( IterationEvent() );
      str->Filter->InvokeEvent( ProgressEvent () );
      str->Filter->SetElapsedIterations(++iter);
      
      str->TimeStep = str->Filter->m_Data[0].TimeStep; // (works for the 1-thread
                                                      // case else redefined below)
      }
    else
      {
      if (ThreadId == 0)
        {
        if (iter != 0)
          {
          // Update the RMS difference here
          unsigned int count = 0;
          str->Filter->SetRMSChange(static_cast<double>( m_ValueZero ));
          for (i = 0; i < str->Filter->m_NumOfThreads; i++)
            {
            str->Filter->SetRMSChange(str->Filter->GetRMSChange() + str->Filter->m_Data[i].m_RMSChange);
            count += str->Filter->m_Data[i].m_Count;
            }
          if (count != 0)
            {
            str->Filter->SetRMSChange( static_cast<double>( vcl_sqrt((static_cast<float> (str->Filter->m_RMSChange))
                                                                     / count) ));
            }
          }
        
        // Should we stop iterating ? (in case there are too few pixels to
        // process for every thread)
        str->Filter->m_Stop= true;
        for (i= 0; i < str->Filter->m_NumOfThreads; i++) 
          {
          if (str->Filter->m_Data[i].m_Layers[0]->Size() > 10)
            {
            str->Filter->m_Stop= false;
            break;
            }
          }
        
        str->Filter->InvokeEvent ( IterationEvent() );
        str->Filter->InvokeEvent ( ProgressEvent () );
        str->Filter->SetElapsedIterations (++iter);
        }
    
      if (ThreadId == 0)
        {
        for (i= 0; i < str->Filter->m_NumOfThreads; i++)
          {
          str->TimeStepList[i]= str->Filter->m_Data[i].TimeStep;
          }
        str->TimeStep = str->Filter->ResolveTimeStep(str->TimeStepList,
                       str->ValidTimeStepList, str->Filter->m_NumOfThreads);
        }

      }
    
    str->Filter->WaitForAll();
    
    // The active layer is too small => stop iterating
    if (str->Filter->m_Stop == true)
      {
      return ITK_THREAD_RETURN_VALUE;
      }
    
    // Threaded Apply Update
    str->Filter->ThreadedApplyUpdate(str->TimeStep, ThreadId);
    
    // We only need to wait for neighbors because ThreadedCalculateChange
    // requires information only from the neighbors.
    str->Filter->SignalNeighborsAndWait(ThreadId);
    
    if (str->Filter->GetElapsedIterations()
        % LOAD_BALANCE_ITERATION_FREQUENCY == 0)
      {
      str->Filter->WaitForAll();
      // change boundaries if needed
      if (ThreadId == 0)
        {
        str->Filter->CheckLoadBalance();
        }
      str->Filter->WaitForAll();
      
      if (str->Filter->m_BoundaryChanged == true)
        {
        str->Filter->ThreadedLoadBalance (ThreadId);
        str->Filter->WaitForAll();
        }
      }
    }
  
  // post-process output
  str->Filter->GetThreadRegionSplitUniformly(ThreadId,
                                             str->Filter->m_Data[ThreadId].ThreadRegion);
  str->Filter->ThreadedPostProcessOutput(
                        str->Filter->m_Data[ThreadId].ThreadRegion);
  
  return ITK_THREAD_RETURN_VALUE;
}

template <class TInputImage, class TOutputImage>
typename
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>::TimeStepType
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedCalculateChange(unsigned int ThreadId)
{
  typename FiniteDifferenceFunctionType::Pointer df = this->GetDifferenceFunction();
  typename FiniteDifferenceFunctionType::FloatOffsetType offset;
  ValueType norm_grad_phi_squared, dx_forward, dx_backward;
  ValueType centerValue, forwardValue, backwardValue;
  ValueType MIN_NORM      = 1.0e-6;
  if (this->GetUseImageSpacing())
    {
    double minSpacing = NumericTraits<double>::max();
    for (unsigned int i=0; i<ImageDimension; i++)
      {
      minSpacing = vnl_math_min(minSpacing,this->GetInput()->GetSpacing()[i]);
      }
    MIN_NORM *= minSpacing;
    }

  ConstNeighborhoodIterator<OutputImageType> outputIt (df->GetRadius(), m_OutputImage,
                                                       m_OutputImage->GetRequestedRegion());
  if ( m_BoundsCheckingActive == false )
    {
    outputIt.NeedToUseBoundaryConditionOff();
    }
  unsigned int i, center = outputIt.Size() /2;
 
  const NeighborhoodScalesType neighborhoodScales = this->GetDifferenceFunction()->ComputeNeighborhoodScales();
 
  // Calculates the update values for the active layer indicies in this
  // iteration.  Iterates through the active layer index list, applying 
  // the level set function to the output image (level set image) at each
  // index.
  
  typename LayerType::Iterator layerIt  = m_Data[ThreadId].m_Layers[0]->Begin();
  typename LayerType::Iterator layerEnd = m_Data[ThreadId].m_Layers[0]->End();
  
  for ( ; layerIt != layerEnd; ++layerIt)
    {
    outputIt.SetLocation(layerIt->m_Index);
    // Calculate the offset to the surface from the center of this
    // neighborhood.  This is used by some level set functions in sampling a
    // speed, advection, or curvature term.
    if (this->m_InterpolateSurfaceLocation &&
        (centerValue=outputIt.GetCenterPixel()) != NumericTraits<ValueType>::Zero)
      {
      // Surface is at the zero crossing, so distance to surface is:
      // phi(x) / norm(grad(phi)), where phi(x) is the center of the
      // neighborhood.  The location is therefore
      // (i,j,k) - ( phi(x) * grad(phi(x)) ) / norm(grad(phi))^2
      norm_grad_phi_squared = 0.0;
      
      for (i = 0; i < static_cast<unsigned int>(ImageDimension); ++i)
        {
        forwardValue = outputIt.GetPixel(center + m_NeighborList.GetStride(i));
        backwardValue= outputIt.GetPixel(center - m_NeighborList.GetStride(i));
        
        if (forwardValue * backwardValue >= 0)
          {
            // 1. both neighbors have the same sign OR at least one of them is ZERO
            dx_forward  = forwardValue - centerValue;
            dx_backward = centerValue - backwardValue;
 
            // take the one-sided derivative with the larger magnitude
            if (vnl_math_abs(dx_forward) > vnl_math_abs(dx_backward))
              {
                offset[i]= dx_forward;
              }
            else 
              {
                offset[i]= dx_backward;
              }
          }
        else
          {
            // 2. neighbors have opposite sign
            // take the one-sided derivative using the neighbor that has the opposite sign w.r.t. oneself
            if (centerValue * forwardValue < 0)
              {
                offset[i]= forwardValue - centerValue;
              }
            else
              {
                offset[i]= centerValue - backwardValue;
              }
          }
        
        norm_grad_phi_squared += offset[i] * offset[i];
        }
      
      for (i = 0; i < static_cast<unsigned int>(ImageDimension); ++i)
        {
        offset[i] = ( offset[i] * outputIt.GetCenterPixel() )
          / (norm_grad_phi_squared + MIN_NORM);
        }
          
      layerIt->m_Value = df->ComputeUpdate (outputIt, (void *) m_Data[ThreadId].globalData, offset);
      }
    else // Don't do interpolation
      {
      layerIt->m_Value = df->ComputeUpdate (outputIt, (void *) m_Data[ThreadId].globalData);
      }
    }
  
  TimeStepType timeStep= df->ComputeGlobalTimeStep ((void*) m_Data[ThreadId].globalData);
  
  return timeStep;         
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedApplyUpdate (TimeStepType dt, unsigned int ThreadId)
{
  this->ThreadedUpdateActiveLayerValues(dt,
                                        m_Data[ThreadId].UpList[0],
                                        m_Data[ThreadId].DownList[0],
                                        ThreadId);
  
  // We need to update histogram information (because some pixels are LEAVING
  // layer-0 (the active layer)
  
  this->SignalNeighborsAndWait(ThreadId);
  
  // Process status lists and update value for first inside/outside layers
  
  this->ThreadedProcessStatusList( 0, 1, 2, 1, 1, 0, ThreadId);
  this->ThreadedProcessStatusList( 0, 1, 1, 2, 0, 0, ThreadId);
  
  this->SignalNeighborsAndWait(ThreadId);
  
  // Update first layer value, process first layer
  this->ThreadedProcessFirstLayerStatusLists( 1, 0, 3, 1, 1, ThreadId);
  this->ThreadedProcessFirstLayerStatusLists( 1, 0, 4, 0, 1, ThreadId);

  // We need to update histogram information (because some pixels are ENTERING
  // layer-0
  
  this->SignalNeighborsAndWait(ThreadId);
  
  StatusType   up_to= 1,   up_search= 5;
  StatusType down_to= 2, down_search= 6;
  unsigned char j= 0, k= 1;
  
  // The 3D case: this loop is executed at least once
  while ( down_search < 2 * m_NumberOfLayers + 1 )
    {
    this->ThreadedProcessStatusList(j, k, up_to, up_search, 1,
                                    (up_search - 1) / 2, ThreadId);
    this->ThreadedProcessStatusList(j, k, down_to, down_search, 0,
                                     (up_search - 1) / 2, ThreadId); 
      
    this->SignalNeighborsAndWait(ThreadId);
      
    up_to   += 2;
    down_to += 2;
    up_search   += 2;
    down_search += 2;
    
    // Swap the lists so we can re-use the empty one.
    j= k;
    k= 1 - j;
    }
  // now up_search   = 2 * m_NumberOfLayers + 1 (= 7 if m_NumberOfLayers = 3)
  // now down_search = 2 * m_NumberOfLayers + 2 (= 8 if m_NumberOfLayers = 3)
  
  // Process the outermost inside/outside layers in the sparse field
  this->ThreadedProcessStatusList(j, k, up_to, m_StatusNull, 1,
                                   (up_search - 1) / 2, ThreadId);
  this->ThreadedProcessStatusList(j, k, down_to, m_StatusNull, 0,
                                  (up_search - 1) / 2, ThreadId);
  
  this->SignalNeighborsAndWait(ThreadId);
  
  this->ThreadedProcessOutsideList(k,(2 * m_NumberOfLayers + 1) - 2, 1,
                                   (up_search + 1) / 2, ThreadId);
  this->ThreadedProcessOutsideList(k,(2 * m_NumberOfLayers + 1) - 1, 0,
                                   (up_search + 1) / 2, ThreadId);
  
  if (m_OutputImage->GetImageDimension() < 3)
    {
    this->SignalNeighborsAndWait(ThreadId);
    }

  // A synchronize is NOT required here because in 3D case we have at least 7
  // layers, thus ThreadedProcessOutsideList() works on layers 5 & 6 while
  // ThreadedPropagateLayerValues() works on 0, 1, 2, 3, 4 only. => There can
  // NOT be any dependencies amoing different threads.
  
  // Finally, we update all of the layer VALUES (excluding the active layer,
  // which has already been updated)
  this->ThreadedPropagateLayerValues(0, 1, 3, 1, ThreadId); // first inside
  this->ThreadedPropagateLayerValues(0, 2, 4, 0, ThreadId); // first outside
  
  this->SignalNeighborsAndWait (ThreadId);
  
  // Update the rest of the layer values
  unsigned int i;
  for (i = 1; i < (2 * static_cast<unsigned int>(m_NumberOfLayers) + 1) - 2; i += 2)
    {
    j = i+1;
    this->ThreadedPropagateLayerValues(i, i+2,   i+4,   1, ThreadId);
    this->ThreadedPropagateLayerValues(j, j+2,   j+4,   0, ThreadId);    
    this->SignalNeighborsAndWait (ThreadId);
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedUpdateActiveLayerValues (TimeStepType dt, LayerType * UpList,
                                   LayerType * DownList, unsigned int ThreadId)
{
  // This method scales the update buffer values by the time step and adds
  // them to the active layer pixels.  New values at an index which fall
  // outside of the active layer range trigger that index to be placed on the
  // "up" or "down" status list.  The neighbors of any such index are then
  // assigned new values if they are determined to be part of the active list
  // for the next iteration (i.e. their values will be raised or lowered into
  // the active range).
  ValueType LOWER_ACTIVE_THRESHOLD = - (m_ConstantGradientValue / 2.0);
  ValueType UPPER_ACTIVE_THRESHOLD =    m_ConstantGradientValue / 2.0 ;
  
  LayerNodeType *release_node;
  bool flag;
  
  IndexType  centerIndex;
  PixelType  centerValue;
  
  unsigned long int counter =0;
  float new_value;
  float rms_change_accumulator = m_ValueZero;
  
  unsigned int Neighbor_Size = m_NeighborList.GetSize();
  
  typename LayerType::Iterator layerIt
    = m_Data[ThreadId].m_Layers[0]->Begin();
  typename LayerType::Iterator layerEnd
    = m_Data[ThreadId].m_Layers[0]->End();
  
  while (layerIt != layerEnd )
    {
      centerIndex = layerIt->m_Index;
      centerValue = m_OutputImage->GetPixel(centerIndex);
      
      new_value = this->ThreadedCalculateUpdateValue(ThreadId, centerIndex, dt,
                                                     centerValue, layerIt->m_Value);
      
      // If this index needs to be moved to another layer, then search its
      // neighborhood for indicies that need to be pulled up/down into the
      // active layer. Set those new active layer values appropriately,
      // checking first to make sure they have not been set by a more
      // influential neighbor.
      
      //   ...But first make sure any neighbors in the active layer are not
      // moving to a layer in the opposite direction.  This step is necessary
      // to avoid the creation of holes in the active layer.  The fix is simply
      // to not change this value and leave the index in the active set.
      
      if (new_value > UPPER_ACTIVE_THRESHOLD)
        {
        // This index will move UP into a positive (outside) layer
        // First check for active layer neighbors moving in the opposite
        // direction
        flag = false;
        for (unsigned int i = 0; i < Neighbor_Size; ++i)
          {
          if (m_StatusImage->GetPixel(centerIndex + m_NeighborList.GetNeighborhoodOffset(i))
              == m_StatusActiveChangingDown)
            {
            flag = true;
            break;
            }
          }
        if (flag == true)
          {
          ++layerIt;
          continue;
          }
        
        rms_change_accumulator += vnl_math_sqr(static_cast<float>(new_value - centerValue ));
        // update the value of the pixel
        m_OutputImage->SetPixel (centerIndex, new_value);
        
        // Now remove this index from the active list.
        release_node = layerIt.GetPointer();
        ++layerIt;
        
        m_Data[ThreadId].m_Layers[0]->Unlink(release_node);
        m_Data[ThreadId].m_ZHistogram[ release_node->m_Index[m_SplitAxis] ]
          = m_Data[ThreadId].m_ZHistogram[ release_node->m_Index[m_SplitAxis] ] - 1;
        
        // add the release_node to status up list
        UpList->PushFront(release_node);
        
        //
        m_StatusImage->SetPixel(centerIndex, m_StatusActiveChangingUp);
        }
      else if (new_value < LOWER_ACTIVE_THRESHOLD)
        {
        // This index will move DOWN into a negative (inside) layer.
        // First check for active layer neighbors moving in the opposite direction
        flag = false;
        for (unsigned int i = 0; i < Neighbor_Size; ++i)
          {
          if (m_StatusImage->GetPixel(centerIndex+m_NeighborList.GetNeighborhoodOffset(i))
              == m_StatusActiveChangingUp)
            {
            flag = true;
            break;
            }
          }
        if (flag == true)
          {
          ++layerIt;
          continue;              
          }
        
        rms_change_accumulator += vnl_math_sqr(static_cast<float>(new_value - centerValue));
        // update the value of the pixel
        m_OutputImage->SetPixel(centerIndex, new_value );
        
        // Now remove this index from the active list.
        release_node = layerIt.GetPointer();
        ++layerIt;
        
        m_Data[ThreadId].m_Layers[0]->Unlink(release_node);
        m_Data[ThreadId].m_ZHistogram[ release_node->m_Index[m_SplitAxis] ]
          = m_Data[ThreadId].m_ZHistogram[ release_node->m_Index[m_SplitAxis] ] - 1;
        
        // now add release_node to status down list
        DownList->PushFront(release_node);
        
        m_StatusImage->SetPixel(centerIndex, m_StatusActiveChangingDown);
        }
      else
        {
        rms_change_accumulator += vnl_math_sqr(static_cast<float>(new_value - centerValue));
        // update the value of the pixel
        m_OutputImage->SetPixel(centerIndex, new_value );
        ++layerIt;
        }
      ++counter;
    }
  
  // Determine the average change during this iteration
  if (counter == 0)
    {
    m_Data[ThreadId].m_RMSChange = m_ValueZero;
    }
  else
    {
    m_Data[ThreadId].m_RMSChange = rms_change_accumulator;
    }
  
  m_Data[ThreadId].m_Count = counter;
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::CopyInsertList (unsigned int ThreadId, LayerPointerType FromListPtr,
                  LayerPointerType ToListPtr)
{
  typename LayerType::Iterator layerIt = FromListPtr->Begin();
  typename LayerType::Iterator layerEnd= FromListPtr->End();
  
  LayerNodeType * nodePtr;
  LayerNodeType * nodeTempPtr;
  
  while (layerIt != layerEnd)
    {
    // copy the node
    nodePtr= layerIt.GetPointer();
    ++layerIt;
    
    nodeTempPtr= m_Data[ThreadId].m_LayerNodeStore->Borrow();
    nodeTempPtr->m_Index= nodePtr->m_Index;
    
    // insert
    ToListPtr->PushFront (nodeTempPtr);
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ClearList (unsigned int ThreadId, LayerPointerType ListPtr)
{
  LayerNodeType * nodePtr;
  
  while (! ListPtr->Empty())
    {
    nodePtr= ListPtr->Front();
    // remove node from layer
    ListPtr->PopFront();
    // return node to node-pool
    m_Data[ThreadId].m_LayerNodeStore->Return (nodePtr);
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::CopyInsertInterNeighborNodeTransferBufferLayers (unsigned int ThreadId, LayerPointerType List,
                                                   unsigned int InOrOut, unsigned int BufferLayerNumber)
{
  if (ThreadId != 0)
    {
    CopyInsertList(ThreadId,
                   m_Data[this->GetThreadNumber(m_Boundary[ThreadId-1])].m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber][ThreadId],
                   List);
    }
  
  if (m_Boundary[ThreadId] != m_ZSize - 1)
    {
    CopyInsertList(ThreadId,
                   m_Data[this->GetThreadNumber (m_Boundary[ThreadId] + 1)].m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber][ThreadId],
                   List);
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ClearInterNeighborNodeTransferBufferLayers (unsigned int ThreadId, unsigned int InOrOut,
                                              unsigned int BufferLayerNumber)
{
  for (unsigned int i= 0; i < m_NumOfThreads; i++)
    {
    ClearList(ThreadId, m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber][i]);
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedProcessFirstLayerStatusLists (unsigned int InputLayerNumber, unsigned int OutputLayerNumber,
                                        StatusType SearchForStatus,
                                        unsigned int InOrOut, unsigned int BufferLayerNumber, unsigned int ThreadId)
{
  LayerNodeType* nodePtr;
  StatusType from, neighbor_status;
  ValueType value, value_temp, delta;
  bool found_neighbor_flag;
  
  IndexType center_index, n_index;
  
  unsigned int neighbor_Size = m_NeighborList.GetSize();
  LayerPointerType InputList, OutputList;
  
  //InOrOut == 1, inside, more negative, uplist
  //InOrOut == 0, outside
  if (InOrOut == 1)
    {
    delta =  - m_ConstantGradientValue;
    from = 2;
    InputList  = m_Data[ThreadId].UpList[InputLayerNumber];
    OutputList = m_Data[ThreadId].UpList[OutputLayerNumber];
    }
  else
    {
    delta = m_ConstantGradientValue;
    from = 1;
    InputList  = m_Data[ThreadId].DownList[InputLayerNumber];
    OutputList = m_Data[ThreadId].DownList[OutputLayerNumber];
    }
  
  // 1. nothing to clear
  // 2. make a copy of the node on the
  //    m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber - 1][i]
  //    for all neighbors i ... and insert it in one's own InputList
  CopyInsertInterNeighborNodeTransferBufferLayers(ThreadId, InputList, InOrOut,
                                                  BufferLayerNumber - 1);
  
  typename LayerType::Iterator layerIt  = InputList->Begin();
  typename LayerType::Iterator layerEnd = InputList->End();
  while (layerIt != layerEnd)
    {
    nodePtr = layerIt.GetPointer();
    ++layerIt;
    
    center_index = nodePtr->m_Index;
    
    // remove node from InputList
    InputList->Unlink(nodePtr);
    
    // check if this is not a duplicate pixel in the InputList
    // In the case when the thread boundaries differ by just 1 pixel some
    // nodes may get added twice in the InputLists Even if the boundaries are
    // more than 1 pixel wide the *_shape_* of the layer may allow this to
    // happen. Solution: If a pixel comes multiple times than we would find
    // that the Status image would already be reflecting the new status after
    // the pixel was encountered the first time 
    if (m_StatusImage->GetPixel(center_index) == 0)
      {
      // duplicate node => return it to the node pool
      m_Data[ThreadId].m_LayerNodeStore->Return (nodePtr);      
      continue;
      }
    
    // set status to zero
    m_StatusImage->SetPixel(center_index, 0);
    // add node to the layer-0
    m_Data[ThreadId].m_Layers[0]->PushFront(nodePtr);

    m_Data[ThreadId].m_ZHistogram[ nodePtr->m_Index[m_SplitAxis] ]
      = m_Data[ThreadId].m_ZHistogram[ nodePtr->m_Index[m_SplitAxis] ] + 1;
      
    value = m_OutputImage->GetPixel(center_index);
    found_neighbor_flag = false;
    for (unsigned int i = 0; i < neighbor_Size; ++i)
      {
      n_index = center_index + m_NeighborList.GetNeighborhoodOffset(i);
      neighbor_status = m_StatusImage->GetPixel(n_index);
      
      // Have we bumped up against the boundary?  If so, turn on bounds checking.
      if ( neighbor_status == m_StatusBoundaryPixel )
        {
        m_BoundsCheckingActive = true;
        }
      
      if (neighbor_status ==  from)
        {
        value_temp = m_OutputImage->GetPixel(n_index);
        
        if (found_neighbor_flag == false)
          {
          value = value_temp;
          }
        else
          {
            if (vnl_math_abs(value_temp+delta) < vnl_math_abs(value+delta))
              {
                // take the value closest to zero
                value= value_temp;
              }
          }
        found_neighbor_flag = true;
        }
      
      if (neighbor_status == SearchForStatus)
        { 
        // mark this pixel so we MAY NOT add it twice
        // This STILL DOES NOT GUARANTEE RACE CONDITIONS BETWEEN THREADS. This
        // is handled at the next stage
        m_StatusImage->SetPixel(n_index, m_StatusChanging);
        
        unsigned int tmpId = this->GetThreadNumber(n_index[m_SplitAxis]);
        
        nodePtr = m_Data[ThreadId].m_LayerNodeStore->Borrow();
        nodePtr->m_Index = n_index;
           
        if (tmpId != ThreadId)
          {
          m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber][tmpId]->PushFront(nodePtr);
          }
        else
          {
          OutputList->PushFront(nodePtr);
          }
        }
      }
    m_OutputImage->SetPixel(center_index, value + delta );
    // This function can be overridden in the derived classes to process pixels entering the active layer.
    this->ThreadedProcessPixelEnteringActiveLayer (center_index, value + delta, ThreadId);
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedProcessPixelEnteringActiveLayer (const IndexType itkNotUsed(index),
                                           const ValueType itkNotUsed(value),
                                           const unsigned int itkNotUsed(ThreadId))
{
  // This function can be overridden in the derived classes to process pixels entering the active layer.
  return;
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedProcessStatusList (unsigned int InputLayerNumber, unsigned int OutputLayerNumber,
                             StatusType ChangeToStatus, StatusType SearchForStatus,
                             unsigned int InOrOut, unsigned int BufferLayerNumber, unsigned int ThreadId)
{
  unsigned int i;
  LayerNodeType* nodePtr;
  StatusType neighbor_status;
  
  IndexType   center_index, n_index;
  
  LayerPointerType InputList, OutputList;
  
  // Push each index in the input list into its appropriate status layer
  // (ChangeToStatus) and update the status image value at that index.
  // Also examine the neighbors of the index to determine which need to go onto
  // the output list (search for SearchForStatus).
  if (InOrOut == 1)
    {
    InputList  = m_Data[ThreadId].UpList[InputLayerNumber];
    OutputList = m_Data[ThreadId].UpList[OutputLayerNumber];
    }
  else
    {
    InputList  = m_Data[ThreadId].DownList[InputLayerNumber];
    OutputList = m_Data[ThreadId].DownList[OutputLayerNumber];
    }
  
  // 1. clear one's own
  // m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber - 2][i]
  // for all threads i.
  if (BufferLayerNumber >= 2)
    {
    ClearInterNeighborNodeTransferBufferLayers(ThreadId, InOrOut,
                                               BufferLayerNumber - 2);
    }
  // SPECIAL CASE: clear one's own
  // m_InterNeighborNodeTransferBufferLayers[InOrOut][m_NumberOfLayers][i] for
  // all threads i
  if (BufferLayerNumber == 0)
    {
    ClearInterNeighborNodeTransferBufferLayers(ThreadId, InOrOut, m_NumberOfLayers);
    }
  // obtain the pixels (from last iteration) that were given to you from other
  // (neighboring) threads 2. make a copy of the node on the
  // m_InterNeighborNodeTransferBufferLayers[InOrOut][LastLayer - 1][i] for all
  // thread neighbors i ... ... and insert it in one's own InputList
  if (BufferLayerNumber > 0)
    {
    CopyInsertInterNeighborNodeTransferBufferLayers(ThreadId, InputList,
                                                    InOrOut, BufferLayerNumber - 1);
    }
  
  unsigned int neighbor_size = m_NeighborList.GetSize();
  while ( ! InputList->Empty() )
    {
    nodePtr = InputList->Front();
    center_index = nodePtr->m_Index;
      
    InputList->PopFront();
      
    // Check if this is not a duplicate pixel in the InputList.
    // Solution: If a pixel comes multiple times than we would find that the
    // Status image would already be reflecting 
    // the new status after the pixel was encountered the first time 
    if ((BufferLayerNumber != 0)
        && (m_StatusImage->GetPixel(center_index) == ChangeToStatus)) 
      {
      // duplicate node => return it to the node pool
      m_Data[ThreadId].m_LayerNodeStore->Return (nodePtr);
      
      continue;
      }
    
    // add to layer
    m_Data[ThreadId].m_Layers[ChangeToStatus]->PushFront (nodePtr);
    // change the status
    m_StatusImage->SetPixel(center_index, ChangeToStatus);
    
    for (i = 0; i < neighbor_size; ++i)
      {
      n_index = center_index + m_NeighborList.GetNeighborhoodOffset(i);
      
      neighbor_status = m_StatusImage->GetPixel(n_index);
      
      // Have we bumped up against the boundary?  If so, turn on bounds checking.
      if ( neighbor_status == m_StatusBoundaryPixel )
        {
        m_BoundsCheckingActive = true;
        }
      
      if (neighbor_status == SearchForStatus)
        {
        // mark this pixel so we MAY NOT add it twice
        // This STILL DOES NOT AVOID RACE CONDITIONS BETWEEN THREADS (This is
        // handled at the next stage) 
        m_StatusImage->SetPixel(n_index, m_StatusChanging);
        
        unsigned int tmpId = this->GetThreadNumber (n_index[m_SplitAxis]);
        
        nodePtr = m_Data[ThreadId].m_LayerNodeStore->Borrow();
        nodePtr->m_Index = n_index;
        
        if (tmpId != ThreadId)
          {
          m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber][tmpId]->PushFront(nodePtr);
          }
        else
          {
          OutputList->PushFront(nodePtr);
          }
        }
      }
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedProcessOutsideList (unsigned int InputLayerNumber, StatusType ChangeToStatus,
                              unsigned int InOrOut, unsigned int BufferLayerNumber, unsigned int ThreadId)
{
  LayerPointerType OutsideList;
  if (InOrOut == 1)
    {
    OutsideList= m_Data[ThreadId].UpList  [InputLayerNumber];
    }
  else
    {
    OutsideList= m_Data[ThreadId].DownList[InputLayerNumber];
    }
  
  // obtain the pixels (from last iteration of ThreadedProcessStatusList() )
  // that were given to you from other (neighboring) threads
  // 1. clear one's own
  //    m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber - 2][i]
  //    for all threads i. 
  ClearInterNeighborNodeTransferBufferLayers(ThreadId, InOrOut, BufferLayerNumber - 2);
  
  // 2. make a copy of the node on the
  //    m_InterNeighborNodeTransferBufferLayers[InOrOut][LastLayer - 1][i] for
  //    all thread neighbors i ... ... and insert it in one's own InoutList
  CopyInsertInterNeighborNodeTransferBufferLayers(ThreadId, OutsideList, InOrOut,
                                                  BufferLayerNumber - 1);
  
  // Push each index in the input list into its appropriate status layer
  // (ChangeToStatus) and ... ... update the status image value at that index 
  LayerNodeType* nodePtr;
  while ( ! OutsideList->Empty() )
    {
    nodePtr = OutsideList->Front();
    OutsideList->PopFront();
      
    m_StatusImage->SetPixel(nodePtr->m_Index, ChangeToStatus); 
    m_Data[ThreadId].m_Layers[ChangeToStatus]->PushFront (nodePtr);
    }
}

template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedPropagateLayerValues(StatusType from, StatusType to, StatusType promote,
                               unsigned int InOrOut, unsigned int ThreadId)
{
  ValueType value, value_temp, delta;
  bool found_neighbor_flag;
  typename LayerType::Iterator toIt;
  typename LayerType::Iterator toEnd;
  LayerNodeType* nodePtr;
  StatusType past_end = static_cast<StatusType>( m_Layers.size() ) - 1;
  
  // Are we propagating values inward (more negative) or outward (more positive)?
  if (InOrOut == 1)
    {
    delta = - m_ConstantGradientValue;
    }
  else
    {
    delta =   m_ConstantGradientValue;
    }
  
  unsigned int Neighbor_Size = m_NeighborList.GetSize();
  toIt  =  m_Data[ThreadId].m_Layers[to]->Begin();
  toEnd =  m_Data[ThreadId].m_Layers[to]->End();
  
  IndexType  centerIndex, nIndex;
  StatusType centerStatus, nStatus;
  
  while ( toIt != toEnd )
    {
      centerIndex = toIt->m_Index;
      
      centerStatus = m_StatusImage->GetPixel(centerIndex);
      
      if (centerStatus != to)
        {
        // delete nodes NOT deleted earlier          
        nodePtr = toIt.GetPointer();
        ++toIt;
        
        // remove the node from the layer
        m_Data[ThreadId].m_Layers[to]->Unlink( nodePtr );
        m_Data[ThreadId].m_LayerNodeStore->Return( nodePtr );
        continue;
        }
      
      value = m_ValueZero;
      found_neighbor_flag = false;
      for (unsigned int i = 0; i < Neighbor_Size ; ++i)
        {
        nIndex = centerIndex + m_NeighborList.GetNeighborhoodOffset(i);
        nStatus = m_StatusImage->GetPixel(nIndex);
        // If this neighbor is in the "from" list, compare its absolute value
        // to any previous values found in the "from" list.  Keep only the
        // value with the smallest magnitude.
        
        if (nStatus == from)
          {
          value_temp = m_OutputImage->GetPixel(nIndex);
          
          if (found_neighbor_flag == false)
            {
            value = value_temp;
            }
          else
            {
              if (vnl_math_abs(value_temp+delta) < vnl_math_abs(value+delta))
                {
                  // take the value closest to zero
                  value= value_temp;
                }
            }
          found_neighbor_flag = true;
          }
        }
      if (found_neighbor_flag == true)
        {
        // Set the new value using the smallest magnitude found in our "from"
        // neighbors
        m_OutputImage->SetPixel (centerIndex, value + delta);
        ++toIt;
        }
      else
        {
        // Did not find any neighbors on the "from" list, then promote this
        // node.  A "promote" value past the end of my sparse field size
        // means delete the node instead.  Change the status value in the
        // status image accordingly.
        nodePtr  = toIt.GetPointer();
        ++toIt;
        m_Data[ThreadId].m_Layers[to]->Unlink( nodePtr );
        
        if ( promote > past_end )
          {
          m_Data[ThreadId].m_LayerNodeStore->Return( nodePtr );
          m_StatusImage->SetPixel(centerIndex, m_StatusNull);
          }
        else
          {
          m_Data[ThreadId].m_Layers[promote]->PushFront( nodePtr );
          m_StatusImage->SetPixel(centerIndex, promote);
          }
        }
    }
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::CheckLoadBalance()
{
  unsigned int i, j;
  
  // This parameter defines a degree of unbalancedness of the load among threads.
  const float MAX_PIXEL_DIFFERENCE_PERCENT = 0.025;
  m_BoundaryChanged = false;
  
  // work load division based on the nodes on the active layer (layer-0)
  long int min = NumericTraits<long int>::max();
  long int max = 0;
  long int total= 0; // the total nodes in the active layer of the surface

  for (i = 0; i < m_NumOfThreads; i++)
    {
    long int count = m_Data[i].m_Layers[0]->Size();
    total += count;
    if (min > count) min = count;
    if (max < count) max = count;
    }
  
  if (max - min < MAX_PIXEL_DIFFERENCE_PERCENT * total / m_NumOfThreads)
    {
    // if the difference between max and min is NOT even x% of the average
    // nodes in the thread layers then no need to change the boundaries next
    return;
    }
  
  // Change the boundaries --------------------------
  
  // compute the global histogram from the individual histograms
  for (i= 0; i < m_NumOfThreads; i++)
    {
    for (j= (i == 0 ? 0 : m_Boundary[i-1] + 1); j <= m_Boundary[i]; j++)
      {
      m_GlobalZHistogram[j] = m_Data[i].m_ZHistogram[j];      
      }
    }
  
  // compute the cumulative frequency distribution using the histogram
  m_ZCumulativeFrequency[0] = m_GlobalZHistogram[0];
  for (i= 1; i < m_ZSize; i++)
    {
    m_ZCumulativeFrequency[i] = m_ZCumulativeFrequency[i-1] + m_GlobalZHistogram[i];
    }
  
  // now define the boundaries
  m_Boundary[m_NumOfThreads - 1] = m_ZSize - 1; // special case: the last bound
  
  for (i= 0; i < m_NumOfThreads - 1; i++)
    {
    // compute m_Boundary[i]    
    float cutOff= 1.0f * (i+1) * m_ZCumulativeFrequency[m_ZSize-1] / m_NumOfThreads;
    
    // find the position in the cumulative freq dist where this cutoff is met
    for (j= (i == 0 ? 0 : m_Boundary[i-1]); j < m_ZSize; j++) 
      {
      if (cutOff > m_ZCumulativeFrequency[j])
        {
        continue;
        }
      else
        {
        // do some optimization !
        // go further FORWARD and find the first index (k) in the cumulative
        // freq distribution s.t. m_ZCumulativeFrequency[k] !=
        // m_ZCumulativeFrequency[j]. This is to be done because if we have a
        // flat patch in the cum freq dist then ... . we can choose a bound
        // midway in that flat patch 
        unsigned int k;
        for (k= 1; j+k < m_ZSize; k++)
          {
          if (m_ZCumulativeFrequency[j+k] != m_ZCumulativeFrequency[j])
            {
            break;
            }
          }
        
        // if ALL new boundaries same as the original then NO NEED TO DO
        // ThreadedLoadBalance() next !!! 
        unsigned int newBoundary= static_cast<unsigned int> ((j + (j+k)) / 2);
        if (newBoundary != m_Boundary[i])
          {
          //
          m_BoundaryChanged= true;
          m_Boundary[i]= newBoundary;
          }
        break;
        }
      }
    }
  
  if (m_BoundaryChanged == false)
    {
    return;
    }
  
  // Reset the individual histograms to reflect the new distrbution
  // Also reset the mapping from the Z value --> the thread number i.e. m_MapZToThreadNumber[]
  for (i= 0; i < m_NumOfThreads; i++)
    {
    if (i != 0)
      {
      for (j= 0; j <= m_Boundary[i-1]; j++)
        {
        m_Data[i].m_ZHistogram[j] = 0;
        }
      }
    
    for (j= (i == 0 ? 0 : m_Boundary[i-1] + 1); j <= m_Boundary[i]; j++)
      {
      // this Z histogram value should be given to thread-i
      m_Data[i].m_ZHistogram[j] = m_GlobalZHistogram[j];
      
      // this Z belongs to the region associated with thread-i
      m_MapZToThreadNumber[j]= i;      
      }
      
    for (j= m_Boundary[i] + 1; j < m_ZSize; j++)
      {
      m_Data[i].m_ZHistogram[j] = 0;
      }
    }  
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedLoadBalance(unsigned int ThreadId)
{
  // the situation at this point in time::
  // the OPTIMAL boundaries (that divide work equally) have changed but ...
  // the thread data lags behind the boundaries (it is still following the old
  // boundaries) the m_ZHistogram[], however, reflects the latest optimal
  // boundaries
  
  // The task:
  // 1. Every thread checks for pixels with itself that should NOT be with
  //    itself anymore (because of the changed boundaries).
  //    These pixels are now put in extra "buckets" for other threads to grab
  // 2. WaitForAll ().
  // 3. Every thread grabs those pixels, from every other thread, that come
  //    within its boundaries (from the extra buckets).
  
  ////////////////////////////////////////////////////
  // 1.

  unsigned int i, j;
  // cleanup the layers first
  for (i = 0; i < 2 * static_cast<unsigned int>(m_NumberOfLayers) + 1; i++)
    {
    for (j= 0; j < m_NumOfThreads; j++)
      {
      if (j == ThreadId)
        {
        // a thread does NOT pass nodes to istelf
        continue;
        }
      
      ClearList(ThreadId, m_Data[ThreadId].m_LoadTransferBufferLayers[i][j]);
      }
    }
  
  LayerNodeType * nodePtr;
  for (i = 0; i < 2 * static_cast<unsigned int>(m_NumberOfLayers) + 1; i++) // for all layers
    {
    typename LayerType::Iterator layerIt  = m_Data[ThreadId].m_Layers[i]->Begin();
    typename LayerType::Iterator layerEnd = m_Data[ThreadId].m_Layers[i]->End();
    
    while (layerIt != layerEnd)
      {
      nodePtr= layerIt.GetPointer();
      ++layerIt;
      
      // use the latest (just updated in CheckLoadBalance) boundaries to
      // determine to which thread region does the pixel now belong
      unsigned int tmpId = this->GetThreadNumber(nodePtr->m_Index[m_SplitAxis]);
      
      if (tmpId != ThreadId) // this pixel no longer belongs to this thread
        {
        // remove from the layer
        m_Data[ThreadId].m_Layers[i]->Unlink(nodePtr);
        
        // insert temporarily into the special-layers TO BE LATER taken by the
        // other thread
        // NOTE: What is pushed is a node belonging to the LayerNodeStore of
        // ThreadId. This is deleted later (during the start of the next
        // SpecialIteration).  What is taken by the other thread is NOT this
        // node BUT a copy of it.
        m_Data[ThreadId].m_LoadTransferBufferLayers[i][tmpId]->PushFront(nodePtr);
        }
      }
    }
  
  ////////////////////////////////////////////////////
  // 2.
  this->WaitForAll();
  
  ////////////////////////////////////////////////////
  // 3.
  for (i = 0; i < 2 * static_cast<unsigned int>(m_NumberOfLayers) + 1; i++)
    {
    // check all other threads
    for (j= 0; j < m_NumOfThreads; j++)
      {
      if (j == ThreadId)
        {
        continue; // exclude oneself
        }
      
      CopyInsertList(ThreadId, m_Data[j].m_LoadTransferBufferLayers[i][ThreadId],
                     m_Data[ThreadId].m_Layers[i]);
      }
    }
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::GetThreadRegionSplitByBoundary(unsigned int ThreadId, ThreadRegionType & ThreadRegion)
{
  // Initialize the ThreadRegion to the output's requested region
  ThreadRegion = m_OutputImage->GetRequestedRegion();
  
  // compute lower bound on the index
  typename TOutputImage::IndexType threadRegionIndex = ThreadRegion.GetIndex();
  if (ThreadId != 0)
    {
    if (m_Boundary[ThreadId-1] < m_Boundary[m_NumOfThreads -1])
      {
      threadRegionIndex[m_SplitAxis] += m_Boundary[ThreadId-1] + 1;
      }
    else
      {
      threadRegionIndex[m_SplitAxis] += m_Boundary[ThreadId-1];
      }
    }
  
  ThreadRegion.SetIndex (threadRegionIndex);
  
  // compute the size of the region
  typename TOutputImage::SizeType threadRegionSize = ThreadRegion.GetSize();
  threadRegionSize[m_SplitAxis] = (ThreadId == 0
                                   ? (m_Boundary[0] + 1)
                                   : m_Boundary[ThreadId] - m_Boundary[ThreadId-1]);
  ThreadRegion.SetSize(threadRegionSize);
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::GetThreadRegionSplitUniformly(unsigned int ThreadId, ThreadRegionType & ThreadRegion)
{
  // Initialize the ThreadRegion to the output's requested region
  ThreadRegion = m_OutputImage->GetRequestedRegion();
  
  typename TOutputImage::IndexType threadRegionIndex = ThreadRegion.GetIndex();
  threadRegionIndex[m_SplitAxis]
    += static_cast<unsigned int> (1.0 * ThreadId * m_ZSize / m_NumOfThreads);
  ThreadRegion.SetIndex(threadRegionIndex);
  
  typename TOutputImage::SizeType  threadRegionSize = ThreadRegion.GetSize();

  // compute lower bound on the index and the size of the region
  if (ThreadId < m_NumOfThreads - 1) // this is NOT the last thread
    {
    threadRegionSize [m_SplitAxis]  = static_cast<unsigned int> (1.0 * (ThreadId+1) * m_ZSize / m_NumOfThreads)
      - static_cast<unsigned int> (1.0 * ThreadId * m_ZSize / m_NumOfThreads);
    }
  else
    {
    threadRegionSize [m_SplitAxis]  = m_ZSize
      - static_cast<unsigned int> (1.0 * ThreadId * m_ZSize / m_NumOfThreads);
    }
  ThreadRegion.SetSize(threadRegionSize);
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::ThreadedPostProcessOutput(const ThreadRegionType & regionToProcess)
{
  // Assign background pixels INSIDE the sparse field layers to a new level set
  // with value less than the innermost layer.  Assign background pixels
  // OUTSIDE the sparse field layers to a new level set with value greater than
  // the outermost layer.  
  const ValueType max_layer = static_cast<ValueType>(m_NumberOfLayers);
  const ValueType outside_value  = (max_layer+1) * m_ConstantGradientValue;
  const ValueType inside_value = -(max_layer+1) * m_ConstantGradientValue;
  
  ImageRegionConstIterator <StatusImageType> statusIt(m_StatusImage, regionToProcess);
  ImageRegionIterator      <OutputImageType> outputIt(m_OutputImage, regionToProcess);
  
  for (outputIt = outputIt.Begin(), statusIt = statusIt.Begin();
       ! outputIt.IsAtEnd(); ++outputIt, ++statusIt)
    {
    if (statusIt.Get() == m_StatusNull || statusIt.Get() == m_StatusBoundaryPixel)
      {
      if (outputIt.Get() > m_ValueZero)
        {
        outputIt.Set (outside_value);
        }
      else
        {
        outputIt.Set (inside_value);
        }
      }
    }
}

template<class TInputImage, class TOutputImage>
unsigned int
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::GetThreadNumber (unsigned int splitAxisValue)
{
  return ( m_MapZToThreadNumber[splitAxisValue] );
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::SignalNeighborsAndWait (unsigned int ThreadId)
{
  // This is the case when a thread has no pixels to process
  // This case is analogous to NOT using that thread at all
  // Hence this thread does not need to signal / wait for any other neighbor
  // thread during the iteration 
  if (ThreadId != 0)
    {
    if (m_Boundary[ThreadId-1] == m_Boundary[ThreadId])
      {
      m_Data[ThreadId].m_SemaphoreArrayNumber=  1
        - m_Data[ThreadId].m_SemaphoreArrayNumber;
      return;
      }
    }
  
  unsigned int lastThreadId = m_NumOfThreads - 1;
  if (lastThreadId == 0)
    {
    return; // only 1 thread => no need to wait
    }
  
  // signal neighbors that work is done
  if (ThreadId != 0) // not the first thread
    {
    this->SignalNeighbor(m_Data[ThreadId].m_SemaphoreArrayNumber,
                         this->GetThreadNumber ( m_Boundary[ThreadId-1] ));
    }
  if (m_Boundary[ThreadId] != m_ZSize - 1) // not the last thread
    {
    this->SignalNeighbor (m_Data[ThreadId].m_SemaphoreArrayNumber,
                          this->GetThreadNumber ( m_Boundary[ThreadId] + 1 ));
    }
  
  // wait for signal from neighbors signifying that their work is done
  if ((ThreadId == 0) || (m_Boundary[ThreadId] == m_ZSize - 1))
    {
    // do it just once for the first and the last threads because they share
    // just 1 boundary (just 1 neighbor) 
    this->WaitForNeighbor (m_Data[ThreadId].m_SemaphoreArrayNumber, ThreadId);
    m_Data[ThreadId].m_SemaphoreArrayNumber= 1 - m_Data[ThreadId].m_SemaphoreArrayNumber;
    }
  else
    {
    // do twice because share 2 boundaries with neighbors
    this->WaitForNeighbor (m_Data[ThreadId].m_SemaphoreArrayNumber, ThreadId);
    this->WaitForNeighbor (m_Data[ThreadId].m_SemaphoreArrayNumber, ThreadId);
    
    m_Data[ThreadId].m_SemaphoreArrayNumber=  1 - m_Data[ThreadId].m_SemaphoreArrayNumber;
    }
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::SignalNeighbor(unsigned int SemaphoreArrayNumber, unsigned int ThreadId)
{
  m_Data[ThreadId].m_Semaphore[SemaphoreArrayNumber]->Up();
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::WaitForNeighbor(unsigned int SemaphoreArrayNumber, unsigned int ThreadId)
{
  m_Data[ThreadId].m_Semaphore[SemaphoreArrayNumber]->Down();
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::WaitForAll ()
{
  m_Barrier->Wait();
}

template<class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
  
  unsigned int i;
  os << indent << "m_IsoSurfaceValue: " << m_IsoSurfaceValue << std::endl;
  os << indent << "m_LayerNodeStore: " << m_LayerNodeStore;
  unsigned int ThreadId;
  for (ThreadId=0; ThreadId < m_NumOfThreads; ThreadId++)
    {
      os << indent << "ThreadId: " << ThreadId << std::endl;
      if (m_Data != 0)
        {
        for (i=0; i < m_Data[ThreadId].m_Layers.size(); i++)
          {
          os << indent << "m_Layers[" << i << "]: size="
             << m_Data[ThreadId].m_Layers[i]->Size() << std::endl;
          os << indent << m_Data[ThreadId].m_Layers[i];
          }
        }
    }
}
/*
template <class TInputImage, class TOutputImage>
void
ParallelSparseFieldLevelSetImageFilterBugFix<TInputImage, TOutputImage>
::WriteActivePointsToFile()
{
  std::cout << "WriteActivePointsToFile called ..." << std::endl << std::flush;
  
  typename LayerType::Iterator layerIt, end;
  
  FILE* out;
  char filename[100];
  sprintf (filename, "activeLayerPoints_%d.pts", this->GetElapsedIterations());
  out= fopen(filename, "wt");
  if(!out) std::cout<<"Can not open "<<filename<<" for writing"<<std::endl << std::flush;
  
  for(unsigned int i = 0; i < m_NumOfThreads; i++)
    {
      layerIt = m_Data[i].m_Layers[0]->Begin(); 
      end     = m_Data[i].m_Layers[0]->End(); 
      
      while(layerIt != end)
        {
          for(unsigned int j = 0; j < static_cast<unsigned int>(ImageDimension); j++)
            {
              fprintf (out,"%d ", static_cast<unsigned int> (layerIt->m_Index[j]));
            }
          fprintf (out, "\n");
    
          ++layerIt;
        }
    }
  fclose(out);
}
*/
} // end namespace itk

#endif