File: DICOMAppHelper.cxx

package info (click to toggle)
insighttoolkit 3.20.1%2Bgit20120521-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 80,652 kB
  • sloc: cpp: 458,133; ansic: 196,223; fortran: 28,000; python: 3,839; tcl: 1,811; sh: 1,184; java: 583; makefile: 430; csh: 220; perl: 193; xml: 20
file content (2446 lines) | stat: -rw-r--r-- 86,266 bytes parent folder | download | duplicates (2)
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
/*=========================================================================

  Program:   DICOMParser
  Module:    DICOMAppHelper.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2003 Matt Turek
  All rights reserved.
  See Copyright.txt 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 notice for more information.

=========================================================================*/

#ifdef _MSC_VER
#pragma warning ( disable : 4514 )
#pragma warning ( disable : 4786 )
#pragma warning ( disable : 4503 )
#pragma warning ( disable : 4710 )
#pragma warning ( disable : 4702 )
#pragma warning ( push, 3 )
#endif 

#include "DICOMConfig.h"
#include "DICOMAppHelper.h"
#include "DICOMCallback.h"

#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <math.h>
#include <algorithm>

namespace DICOMPARSER_NAMESPACE
{
//#define DEBUG_DICOM_APP_HELPER

class DICOMAppHelperImplementation
{
public:
  // map from series UID to vector of instance UIDs in the series
  typedef dicom_stl::map<dicom_stl::string, dicom_stl::vector<dicom_stl::string>, ltstdstr> SeriesUIDToInstanceUIDMapType;
  SeriesUIDToInstanceUIDMapType SeriesUIDToInstanceUIDMap;

  // map from a series Description to an instance UID 
  typedef dicom_stl::map<dicom_stl::string, dicom_stl::string, ltstdstr> SeriesUIDToSeriesDescriptionMapType;
  SeriesUIDToSeriesDescriptionMapType SeriesUIDToSeriesDescriptionMap;

  // map from a series body part to an instance UID 
  typedef dicom_stl::map<dicom_stl::string, dicom_stl::string, ltstdstr> SeriesUIDToBodyPartMapType;
  SeriesUIDToBodyPartMapType  SeriesUIDToBodyPartMap;

  // map from a series scan option to an instance UID 
  typedef dicom_stl::map<dicom_stl::string, dicom_stl::string, ltstdstr> SeriesUIDToScanOptionsMapType;
  SeriesUIDToScanOptionsMapType  SeriesUIDToScanOptionsMap;

  // map from an instance UID to a series UID
  typedef dicom_stl::map<dicom_stl::string, dicom_stl::string, ltstdstr> InstanceUIDToSeriesUIDMapType;
  InstanceUIDToSeriesUIDMapType InstanceUIDToSeriesUIDMap;

  // map from an instance UID to a filename
  typedef dicom_stl::map<dicom_stl::string, dicom_stl::string, ltstdstr> InstanceUIDToFileNameMapType;
  InstanceUIDToFileNameMapType InstanceUIDToFileNameMap;
  
  // map from instance UID to intraseries sortable tags
  typedef dicom_stl::map<dicom_stl::string, DICOMOrderingElements, ltstdstr> InstanceUIDToSliceOrderingMapType;
  InstanceUIDToSliceOrderingMapType InstanceUIDToSliceOrderingMap;

  // map for (group, element) to tag info
  typedef dicom_stl::map<dicom_stl::pair<doublebyte, doublebyte>, DICOMTagInfo> TagMapType;
  TagMapType TagMap;

  // data structure for a contour (store points as x,y,z,x,y,z,...)
  // Do we want to have different contour types? POINT, OPEN_PLANAR, CLOSED_PLANAR
  typedef dicom_stl::vector<float> ContourType;

  // vector of contours
  typedef dicom_stl::vector<ContourType> ContoursVectorType;

  // map from series UID to vector of contours in that series
  typedef dicom_stl::map<dicom_stl::string, ContoursVectorType, ltstdstr> SeriesUIDToContoursMapType;
  SeriesUIDToContoursMapType SeriesUIDToContoursMap;

  // vector of instance UIDs
  typedef dicom_stl::vector<dicom_stl::string> InstanceUIDVectorType;
  
  // map from series UID to referenced instance uid
  typedef dicom_stl::map<dicom_stl::string, InstanceUIDVectorType, ltstdstr> SeriesUIDToReferencedInstanceUIDMapType;
  SeriesUIDToReferencedInstanceUIDMapType SeriesUIDToReferencedInstanceUIDMap;
};


struct lt_pair_int_string
{
  bool operator()(const dicom_stl::pair<int, dicom_stl::string> s1, 
                  const dicom_stl::pair<int, dicom_stl::string> s2) const
  {
    return s1.first < s2.first;
  }
};


struct lt_pair_float_string
{
  bool operator()(const dicom_stl::pair<float, dicom_stl::string> s1, 
                  const dicom_stl::pair<float, dicom_stl::string> s2) const
  {
    return s1.first < s2.first;
  }
};


struct gt_pair_int_string
{
  bool operator()(const dicom_stl::pair<int, dicom_stl::string> s1, 
                  const dicom_stl::pair<int, dicom_stl::string> s2) const
  {
    return s1.first > s2.first;
  }
};


struct gt_pair_float_string
{
  bool operator()(const dicom_stl::pair<float, dicom_stl::string> s1, 
                  const dicom_stl::pair<float, dicom_stl::string> s2) const
  {
    return s1.first > s2.first;
  }
};


DICOMAppHelper::DICOMAppHelper()
{
  this->FileCount = 0;
  this->BitsAllocated = 8;
  this->ByteSwapData = false;
  this->PixelSpacing[0] = this->PixelSpacing[1] = this->PixelSpacing[2] = 1.0f;
  this->Dimensions[0] = this->Dimensions[1] = 0;
  this->Width = this->Height = 0;
  this->PhotometricInterpretation = NULL;
  this->TransferSyntaxUID = NULL;
  this->CurrentSeriesUID = "";
  this->InstanceUID = "";
  this->RescaleOffset = 0.0f;
  this->RescaleSlope = 1.0f;
  this->ImageData = NULL;
  this->ImageDataLengthInBytes = 0;

  // Initialize the arrays
  m_NumberOfSeriesInStudy[0]='\0';
  m_PatientName[0]='\0';
  m_PatientID[0]='\0';
  m_PatientDOB[0]='\0';
  m_StudyID[0]='\0';
  m_StudyDescription[0]='\0';
  m_BodyPart[0]='\0';
  m_NumberOfSeriesInStudy[0]='\0';
  m_NumberOfStudyRelatedSeries[0]='\0';
  m_PatientSex[0]='\0';
  m_PatientAge[0]='\0';
  m_StudyDate[0]='\0';
  m_Modality[0]='\0';
  m_Manufacturer[0]='\0';
  m_Institution[0]='\0';
  m_Model[0]='\0';
  m_ScanOptions[0]='\0';


  this->SeriesUIDCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->SeriesDescriptionCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->InstanceUIDCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->SliceNumberCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->SliceLocationCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ImagePositionPatientCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ImageOrientationPatientCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->TransferSyntaxCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ToggleSwapBytesCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->BitsAllocatedCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->PixelSpacingCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->HeightCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->WidthCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->PixelRepresentationCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->PhotometricInterpretationCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->RescaleOffsetCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->RescaleSlopeCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->PixelDataCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ROIContourSequenceCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ContourImageSequenceCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ContourSequenceCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ContourDataCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->NumberOfContourPointsCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ContourGeometricTypeCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ReferencedInstanceUIDCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->PatientNameCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->PatientIDCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->PatientSexCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->PatientAgeCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->PatientDOBCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->StudyIDCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->StudyDescriptionCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->BodyPartCB  = new DICOMMemberCallback<DICOMAppHelper>;
  this->NumberOfSeriesInStudyCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->NumberOfStudyRelatedSeriesCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->StudyDateCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ModalityCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ManufacturerCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->InstitutionCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ModelCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->ScanOptionsCB = new DICOMMemberCallback<DICOMAppHelper>;
  this->DefaultCB = new DICOMMemberCallback<DICOMAppHelper>;
  
  this->Implementation = new DICOMAppHelperImplementation;
}

DICOMAppHelper::~DICOMAppHelper()
{
  this->Clear();

  this->HeaderFile.close();

  //
  // Fix warning here.
  //
  if (this->ImageData)
    {
    delete [] (static_cast<char*> (this->ImageData));
    }
  if (this->TransferSyntaxUID)
    {
    delete this->TransferSyntaxUID;
    }
  if (this->PhotometricInterpretation)
    {
    delete this->PhotometricInterpretation;
    }

  delete this->SeriesUIDCB;
  delete this->SeriesDescriptionCB;
  delete this->InstanceUIDCB;
  delete this->SliceNumberCB;
  delete this->SliceLocationCB;
  delete this->ImagePositionPatientCB;
  delete this->ImageOrientationPatientCB;
  delete this->TransferSyntaxCB;
  delete this->ToggleSwapBytesCB;
  delete this->BitsAllocatedCB;
  delete this->PixelSpacingCB;
  delete this->HeightCB;
  delete this->WidthCB;
  delete this->PixelRepresentationCB;
  delete this->PhotometricInterpretationCB;
  delete this->RescaleOffsetCB;
  delete this->RescaleSlopeCB;
  delete this->PixelDataCB;
  delete this->ROIContourSequenceCB;
  delete this->ContourImageSequenceCB;
  delete this->ContourSequenceCB;
  delete this->ContourDataCB;
  delete this->NumberOfContourPointsCB;
  delete this->ContourGeometricTypeCB;
  delete this->ReferencedInstanceUIDCB;
  delete this->PatientNameCB;
  delete this->PatientIDCB;
  delete this->PatientSexCB;
  delete this->PatientAgeCB;
  delete this->PatientDOBCB;
  delete this->StudyIDCB;
  delete this->StudyDescriptionCB;
  delete this->BodyPartCB;
  delete this->NumberOfSeriesInStudyCB;
  delete this->NumberOfStudyRelatedSeriesCB;
  delete this->StudyDateCB;
  delete this->ModalityCB;
  delete this->ManufacturerCB;
  delete this->InstitutionCB;
  delete this->ModelCB;
  delete this->ScanOptionsCB;

  delete this->DefaultCB;

  delete this->Implementation;
}

void DICOMAppHelper::RegisterCallbacks(DICOMParser* parser)
{
  if (!parser)
    {
    dicom_stream::cerr << "Null parser!" << dicom_stream::endl;
    }

  // Default callback. Typically used to register a callback for
  // sequences where we are not interested in the sequence itself but
  // an element within the sequence.
  DefaultCB->SetCallbackFunction(this, &DICOMAppHelper::DefaultCallback);

  //
  //
  //
  SeriesUIDCB->SetCallbackFunction(this, &DICOMAppHelper::SeriesUIDCallback);
  parser->AddDICOMTagCallback(0x0020, 0x000e, DICOMParser::VR_UI, SeriesUIDCB);

  InstanceUIDCB->SetCallbackFunction(this, &DICOMAppHelper::InstanceUIDCallback);
  parser->AddDICOMTagCallback(0x0008, 0x0018, DICOMParser::VR_UI, InstanceUIDCB);
  
  SeriesDescriptionCB->SetCallbackFunction(this, &DICOMAppHelper::SeriesDescriptionCallback);
  parser->AddDICOMTagCallback(0x0008, 0x103e, DICOMParser::VR_LO, SeriesDescriptionCB);

  SliceNumberCB->SetCallbackFunction(this, &DICOMAppHelper::SliceNumberCallback);
  parser->AddDICOMTagCallback(0x0020, 0x0013, DICOMParser::VR_IS, SliceNumberCB);

  SliceLocationCB->SetCallbackFunction(this, &DICOMAppHelper::SliceLocationCallback);
  parser->AddDICOMTagCallback(0x0020, 0x1041, DICOMParser::VR_DS, SliceLocationCB);

  ImagePositionPatientCB->SetCallbackFunction(this, &DICOMAppHelper::ImagePositionPatientCallback);
  parser->AddDICOMTagCallback(0x0020, 0x0032, DICOMParser::VR_SH, ImagePositionPatientCB);

  ImageOrientationPatientCB->SetCallbackFunction(this, &DICOMAppHelper::ImageOrientationPatientCallback);
  parser->AddDICOMTagCallback(0x0020, 0x0037, DICOMParser::VR_SH, ImageOrientationPatientCB);
  
  TransferSyntaxCB->SetCallbackFunction(this, &DICOMAppHelper::TransferSyntaxCallback);
  parser->AddDICOMTagCallback(0x0002, 0x0010, DICOMParser::VR_UI, TransferSyntaxCB);

  ToggleSwapBytesCB->SetCallbackFunction(this, &DICOMAppHelper::ToggleSwapBytesCallback);

  BitsAllocatedCB->SetCallbackFunction(this, &DICOMAppHelper::BitsAllocatedCallback);
  parser->AddDICOMTagCallback(0x0028, 0x0100, DICOMParser::VR_US, BitsAllocatedCB);

  PixelSpacingCB->SetCallbackFunction(this, &DICOMAppHelper::PixelSpacingCallback);
  parser->AddDICOMTagCallback(0x0028, 0x0030, DICOMParser::VR_FL, PixelSpacingCB);
  parser->AddDICOMTagCallback(0x0018, 0x0050, DICOMParser::VR_FL, PixelSpacingCB);

  WidthCB->SetCallbackFunction(this, &DICOMAppHelper::WidthCallback);
  parser->AddDICOMTagCallback(0x0028, 0x0011, DICOMParser::VR_US, WidthCB);

  HeightCB->SetCallbackFunction(this, &DICOMAppHelper::HeightCallback);
  parser->AddDICOMTagCallback(0x0028, 0x0010, DICOMParser::VR_US, HeightCB);

  PixelRepresentationCB->SetCallbackFunction(this, &DICOMAppHelper::PixelRepresentationCallback);
  parser->AddDICOMTagCallback(0x0028, 0x0103, DICOMParser::VR_US, PixelRepresentationCB);

  PhotometricInterpretationCB->SetCallbackFunction(this, &DICOMAppHelper::PhotometricInterpretationCallback);
  parser->AddDICOMTagCallback(0x0028, 0x0004, DICOMParser::VR_CS, PhotometricInterpretationCB);

  RescaleOffsetCB->SetCallbackFunction(this, &DICOMAppHelper::RescaleOffsetCallback);
  parser->AddDICOMTagCallback(0x0028, 0x1052, DICOMParser::VR_DS, RescaleOffsetCB);

  RescaleSlopeCB->SetCallbackFunction(this, &DICOMAppHelper::RescaleSlopeCallback);
  parser->AddDICOMTagCallback(0x0028, 0x1053, DICOMParser::VR_DS, RescaleSlopeCB);

  ROIContourSequenceCB->SetCallbackFunction(this, &DICOMAppHelper::ROIContourSequenceCallback);
  parser->AddDICOMTagCallback(0x3006, 0x0039, DICOMParser::VR_SQ, ROIContourSequenceCB);

  ContourSequenceCB->SetCallbackFunction(this, &DICOMAppHelper::ContourSequenceCallback);
  parser->AddDICOMTagCallback(0x3006, 0x0040, DICOMParser::VR_SQ, ContourSequenceCB);

  ContourGeometricTypeCB->SetCallbackFunction(this, &DICOMAppHelper::ContourGeometricTypeCallback);
  parser->AddDICOMTagCallback(0x3006, 0x0042, DICOMParser::VR_CS, ContourGeometricTypeCB);

  NumberOfContourPointsCB->SetCallbackFunction(this, &DICOMAppHelper::NumberOfContourPointsCallback);
  parser->AddDICOMTagCallback(0x3006, 0x0046, DICOMParser::VR_IS, NumberOfContourPointsCB);

  ContourDataCB->SetCallbackFunction(this, &DICOMAppHelper::ContourDataCallback);
  parser->AddDICOMTagCallback(0x3006, 0x0050, DICOMParser::VR_DS, ContourDataCB);

  ContourImageSequenceCB->SetCallbackFunction(this, &DICOMAppHelper::ContourImageSequenceCallback);
  parser->AddDICOMTagCallback(0x3006, 0x0016, DICOMParser::VR_SQ, ContourImageSequenceCB);

  ReferencedInstanceUIDCB->SetCallbackFunction(this, &DICOMAppHelper::ReferencedInstanceUIDCallback);
  parser->AddDICOMTagCallback(0x0008, 0x1155, DICOMParser::VR_UI, ReferencedInstanceUIDCB);

  PatientNameCB->SetCallbackFunction(this, &DICOMAppHelper::PatientNameCallback);
  parser->AddDICOMTagCallback(0x0010, 0x0010, DICOMParser::VR_PN, PatientNameCB);

  PatientIDCB->SetCallbackFunction(this, &DICOMAppHelper::PatientIDCallback);
  parser->AddDICOMTagCallback(0x0010, 0x0020, DICOMParser::VR_LO, PatientIDCB);

  PatientSexCB->SetCallbackFunction(this, &DICOMAppHelper::PatientSexCallback);
  parser->AddDICOMTagCallback(0x0010, 0x0040, DICOMParser::VR_CS, PatientSexCB);

  PatientAgeCB->SetCallbackFunction(this, &DICOMAppHelper::PatientAgeCallback);
  parser->AddDICOMTagCallback(0x0010, 0x1010, DICOMParser::VR_AS, PatientAgeCB);
 
  PatientDOBCB->SetCallbackFunction(this, &DICOMAppHelper::PatientDOBCallback);
  parser->AddDICOMTagCallback(0x0010, 0x0030, DICOMParser::VR_DA, PatientDOBCB);

  StudyIDCB->SetCallbackFunction(this, &DICOMAppHelper::StudyIDCallback);
  parser->AddDICOMTagCallback(0x0020, 0x0010, DICOMParser::VR_SH, StudyIDCB);

  StudyDescriptionCB->SetCallbackFunction(this, &DICOMAppHelper::StudyDescriptionCallback);
  parser->AddDICOMTagCallback(0x0008, 0x1030, DICOMParser::VR_LO, StudyDescriptionCB);

  BodyPartCB->SetCallbackFunction(this, &DICOMAppHelper::BodyPartCallback);
  parser->AddDICOMTagCallback(0x0018, 0x0015, DICOMParser::VR_CS, BodyPartCB);

  NumberOfSeriesInStudyCB->SetCallbackFunction(this, &DICOMAppHelper::NumberOfSeriesInStudyCallback);
  parser->AddDICOMTagCallback(0x0020, 0x1000, DICOMParser::VR_IS, NumberOfSeriesInStudyCB);

  NumberOfStudyRelatedSeriesCB->SetCallbackFunction(this, &DICOMAppHelper::NumberOfStudyRelatedSeriesCallback);
  parser->AddDICOMTagCallback(0x0020, 0x1206, DICOMParser::VR_IS, NumberOfStudyRelatedSeriesCB);

  StudyDateCB->SetCallbackFunction(this, &DICOMAppHelper::StudyDateCallback);
  parser->AddDICOMTagCallback(0x0008, 0x0020, DICOMParser::VR_DA, StudyDateCB);

  ModalityCB->SetCallbackFunction(this, &DICOMAppHelper::ModalityCallback);
  parser->AddDICOMTagCallback(0x0008, 0x0060, DICOMParser::VR_CS, ModalityCB);

  ManufacturerCB->SetCallbackFunction(this, &DICOMAppHelper::ManufacturerCallback);
  parser->AddDICOMTagCallback(0x0008, 0x0070, DICOMParser::VR_LO, ManufacturerCB);

  InstitutionCB->SetCallbackFunction(this, &DICOMAppHelper::InstitutionCallback);
  parser->AddDICOMTagCallback(0x0008, 0x0080, DICOMParser::VR_LO, InstitutionCB);

  ModelCB->SetCallbackFunction(this, &DICOMAppHelper::ModelCallback);
  parser->AddDICOMTagCallback(0x0008, 0x1090, DICOMParser::VR_LO, ModelCB);

  ScanOptionsCB->SetCallbackFunction(this, &DICOMAppHelper::ScanOptionsCallback);
  parser->AddDICOMTagCallback(0x0018, 0x0022, DICOMParser::VR_CS, ScanOptionsCB);

  // Add in default callbacks for tags we need to see but not cache
  //parser->AddDICOMTagCallback(0x3006, 0x0012, DICOMParser::VR_DS, DefaultCB);
  DICOMTagInfo dicom_tags[] = {
    {0x0002, 0x0002, DICOMParser::VR_UI, "Media storage SOP class uid"},
    {0x0002, 0x0003, DICOMParser::VR_UI, "Media storage SOP inst uid"},
    {0x0002, 0x0010, DICOMParser::VR_UI, "Transfer syntax uid"},
    {0x0002, 0x0012, DICOMParser::VR_UI, "Implementation class uid"},
    {0x0008, 0x0018, DICOMParser::VR_UI, "Image UID"},
    {0x0008, 0x0020, DICOMParser::VR_DA, "Series date"},
    {0x0008, 0x0030, DICOMParser::VR_TM, "Series time"},
    {0x0008, 0x0060, DICOMParser::VR_SH, "Modality"},
    {0x0008, 0x0070, DICOMParser::VR_SH, "Manufacturer"},
    {0x0008, 0x0080, DICOMParser::VR_LO, "Institution"},
    {0x0008, 0x1060, DICOMParser::VR_SH, "Physician"},
    {0x0008, 0x1090, DICOMParser::VR_LO, "Model"},
    {0x0008, 0x103E, DICOMParser::VR_LO, "Series description"},
    {0x0010, 0x0010, DICOMParser::VR_PN, "Patient name"},
    {0x0010, 0x0020, DICOMParser::VR_LO, "Patient ID"},
    {0x0010, 0x0040, DICOMParser::VR_CS, "Patient sex"},
    {0x0010, 0x1010, DICOMParser::VR_AS, "Patient age"},
    {0x0010, 0x0030, DICOMParser::VR_DA, "Patient Date of birth"},
    {0x0020, 0x0010, DICOMParser::VR_SH, "Study ID"},
    {0x0008, 0x1030, DICOMParser::VR_LO, "Study Description"},
    {0x0018, 0x0015, DICOMParser::VR_CS, "Body Part"},
    {0x0020, 0x1000, DICOMParser::VR_IS, "Number of series in study"},
    {0x0020, 0x1206, DICOMParser::VR_IS, "Number of study related series"},
    {0x0018, 0x0022, DICOMParser::VR_FL, "Scan options"},  
    {0x0018, 0x0050, DICOMParser::VR_FL, "slice thickness"},
    {0x0018, 0x0060, DICOMParser::VR_FL, "kV"},
    {0x0018, 0x0088, DICOMParser::VR_FL, "slice spacing"},
    {0x0018, 0x1100, DICOMParser::VR_SH, "Recon diameter"},
    {0x0018, 0x1151, DICOMParser::VR_FL, "mA"},
    {0x0018, 0x1210, DICOMParser::VR_SH, "Recon kernel"},
    {0x0020, 0x000d, DICOMParser::VR_UI, "Study UID"},
    {0x0020, 0x000e, DICOMParser::VR_UI, "Series UID"},
    {0x0020, 0x0013, DICOMParser::VR_IS, "Image number"},
    {0x0020, 0x0032, DICOMParser::VR_SH, "Patient position"},
    {0x0020, 0x0037, DICOMParser::VR_SH, "Patient position cosines"},
    {0x0020, 0x1041, DICOMParser::VR_SS, "Slice location"},
    {0x0028, 0x0010, DICOMParser::VR_FL, "Num rows"},
    {0x0028, 0x0011, DICOMParser::VR_FL, "Num cols"},
    {0x0028, 0x0030, DICOMParser::VR_FL, "pixel spacing"},
    {0x0028, 0x0100, DICOMParser::VR_US, "Bits allocated"},
    {0x0028, 0x0120, DICOMParser::VR_UL, "pixel padding"},
    {0x0028, 0x1052, DICOMParser::VR_FL, "pixel offset"},
    {0x3006, 0x0039, DICOMParser::VR_SQ, "ROI Contour Sequence"},
    {0x3006, 0x0040, DICOMParser::VR_SQ, "Contour Sequence"},
    {0x3006, 0x0046, DICOMParser::VR_IS, "Number Of Contour Points"},
    {0x3006, 0x0050, DICOMParser::VR_DS, "Contour Data"}
  };

  int num_tags = sizeof(dicom_tags)/sizeof(DICOMTagInfo);

#ifdef DEBUG_DICOM_APP_HELPER
  DICOMMemberCallback<DICOMAppHelper>** callbackArray = new DICOMMemberCallback<DICOMAppHelper>*[num_tags];
#endif

  for (int j = 0; j < num_tags; j++)
    {
    //
    // Setup internal map.
    //
    DICOMTagInfo tagStruct = dicom_tags[j];
    doublebyte group = tagStruct.group;
    doublebyte element = tagStruct.element;

    dicom_stl::pair<doublebyte, doublebyte> gePair(group, element);
    dicom_stl::pair<const dicom_stl::pair<doublebyte, doublebyte>, DICOMTagInfo> mapPair(gePair, tagStruct);
    this->Implementation->TagMap.insert(mapPair);

#ifdef aDEBUG_DICOM_APP_HELPER
    //
    // Make callback
    //
    callbackArray[j] = new DICOMMemberCallback<DICOMAppHelper>;
    callbackArray[j]->SetCallbackFunction(this, &DICOMAppHelper::ArrayCallback);
    //
    // Set callback on parser.
    //
    parser->AddDICOMTagCallback(group, element,datatype, callbackArray[j]);
#endif

    }

}

void DICOMAppHelper::DefaultCallback(DICOMParser *,
                                     doublebyte,
                                     doublebyte,
                                     DICOMParser::VRTypes,
                                     unsigned char*,
                                     quadbyte)
{
#ifdef DEBUG_DICOM_APP_HELPER  
  dicom_stream::cout << "Default callback " << dicom_stream::endl;
#endif
}

void DICOMAppHelper::InstanceUIDCallback(DICOMParser *parser,
                                       doublebyte,
                                       doublebyte,
                                       DICOMParser::VRTypes,
                                       unsigned char* val,
                                       quadbyte len) 
{
  if (len == 0)
    {
#ifdef DEBUG_DICOM_APP_HELPER  
    dicom_stream::cout << "Instance UID: (EMPTY)" << dicom_stream::endl;
#endif
    
    // empty the string
    this->InstanceUID = dicom_stl::string();

    // just return, don't bother updating the internal databases of UID's
    return;
    }
  
  char* newString = (char*) val;
  dicom_stl::string newStdString(newString);

  // An anonymized UID, generate one
  if (newStdString == "0.0.0.0")
    {
    char fakeUID[2048];
    sprintf (fakeUID, "%d.%d.%d.%d", 0, 0, 0, ++this->FileCount);
    newStdString = fakeUID;
    }
  // cache the instance UID
  this->InstanceUID = newStdString;
  
#ifdef DEBUG_DICOM_APP_HELPER  
  dicom_stream::cout << "Instance UID: " << newStdString << dicom_stream::endl;
#endif

  // Put the instance UID into the internal database mapping instance UIDs
  // to filenames
  this->Implementation
    ->InstanceUIDToFileNameMap.insert(dicom_stl::pair<const dicom_stl::string, dicom_stl::string>(this->InstanceUID, parser->GetFileName() ));
}


void DICOMAppHelper::ReferencedInstanceUIDCallback(DICOMParser *,
                                                   doublebyte,
                                                   doublebyte,
                                                   DICOMParser::VRTypes,
                                                   unsigned char* val,
                                                   quadbyte len) 
{
  if (len == 0)
    {
#ifdef DEBUG_DICOM_APP_HELPER  
    dicom_stream::cout << "Referenced Instance UID: (EMPTY)" << dicom_stream::endl;
#endif
    
    // just return, don't bother updating the internal databases of UID's
    return;
    }

  char* newString = (char*) val;
  dicom_stl::string newStdString(newString);

#ifdef DEBUG_DICOM_APP_HELPER  
  dicom_stream::cout << "Referenced Instance UID: " << newStdString << dicom_stream::endl;
#endif
  
  // store the referenced instance UID in the map for this series.
  // This vector of referenced instance UIDs should be in lock step
  // with the contours
  this->Implementation->SeriesUIDToReferencedInstanceUIDMap[this->CurrentSeriesUID].push_back( newStdString );
}

void DICOMAppHelper::ContourImageSequenceCallback(DICOMParser *,
                                                  doublebyte,
                                                  doublebyte,
                                                  DICOMParser::VRTypes,
                                                  unsigned char*,
                                                  quadbyte) 
{
  // Add a contour to the list of contours
  DICOMAppHelperImplementation::ContourType contour;
  this->Implementation->SeriesUIDToContoursMap[this->CurrentSeriesUID].push_back(contour);

#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "Contour Image Sequence. " << dicom_stream::endl;
#endif
}

void DICOMAppHelper::SeriesUIDCallback(DICOMParser *,
                                       doublebyte,
                                       doublebyte,
                                       DICOMParser::VRTypes,
                                       unsigned char* val,
                                       quadbyte len) 
{
  if (len == 0)
    {
#ifdef DEBUG_DICOM_APP_HELPER  
    dicom_stream::cout << "Series UID: (EMPTY)" << dicom_stream::endl;
#endif

    // clear the cached series uid
    this->CurrentSeriesUID = dicom_stl::string();
    
    // just return, don't bother updating the internal databases of UID's
    return;
    }

  char* newString = (char*) val;
  dicom_stl::string newStdString(newString);

  // An anonymized UID, set the the UID to 0.0.0,1
  if (newStdString == "0.0.0.0")
    {
    char fakeUID[2048];
    sprintf (fakeUID, "%d.%d.%d.%d", 0, 0, 0, 1);
    newStdString = fakeUID;
    }

#ifdef DEBUG_DICOM_APP_HELPER  
  dicom_stream::cout << "Series UID: " << newStdString << dicom_stream::endl;
#endif

  // Put the series UID into the internal database mapping instance
  // UIDs to SeriesUIDs
  this->Implementation
    ->InstanceUIDToSeriesUIDMap.insert(dicom_stl::pair<const dicom_stl::string, dicom_stl::string>(this->InstanceUID, newStdString ));
  
  // Put the series UID into the internal database mapping series UIDs
  // to InstanceUIDs
  DICOMAppHelperImplementation::SeriesUIDToInstanceUIDMapType::iterator iiter = this->Implementation->SeriesUIDToInstanceUIDMap.find(newStdString);
  if ( iiter == this->Implementation->SeriesUIDToInstanceUIDMap.end())
    {
    dicom_stl::vector<dicom_stl::string> newVector;
    
    newVector.push_back(this->InstanceUID);
    this->Implementation->SeriesUIDToInstanceUIDMap.insert(dicom_stl::pair<const dicom_stl::string, dicom_stl::vector<dicom_stl::string> > (newStdString, newVector));
    }
  else
    {
    (*iiter).second.push_back(this->InstanceUID);
    }
  
  // Put the series UID into the internal database mapping series UIDs
  // to contours
  DICOMAppHelperImplementation::SeriesUIDToContoursMapType::iterator citer = this->Implementation->SeriesUIDToContoursMap.find(newStdString);
  if ( citer == this->Implementation->SeriesUIDToContoursMap.end())
    {
    DICOMAppHelperImplementation::ContoursVectorType newVector;
    
    this->Implementation->SeriesUIDToContoursMap.insert(dicom_stl::pair<const dicom_stl::string, DICOMAppHelperImplementation::ContoursVectorType> (newStdString, newVector));
    }
  // Put the series UID into the internal database mapping series UIDs
  // to referenced instance UIDs
  DICOMAppHelperImplementation::SeriesUIDToReferencedInstanceUIDMapType::iterator riter = this->Implementation->SeriesUIDToReferencedInstanceUIDMap.find(newStdString);
  if ( riter == this->Implementation->SeriesUIDToReferencedInstanceUIDMap.end())
    {
    DICOMAppHelperImplementation::InstanceUIDVectorType newVector;
    
    this->Implementation->SeriesUIDToReferencedInstanceUIDMap.insert(dicom_stl::pair<const dicom_stl::string, DICOMAppHelperImplementation::InstanceUIDVectorType> (newStdString, newVector));
    }
  // cache the current series UID
  this->CurrentSeriesUID = newStdString;
}


void DICOMAppHelper::SeriesDescriptionCallback(DICOMParser *,
                                       doublebyte,
                                       doublebyte,
                                       DICOMParser::VRTypes,
                                       unsigned char* val,
                                       quadbyte len ) 
{
  if (len == 0)
    {
#ifdef DEBUG_DICOM_APP_HELPER  
    dicom_stream::cout << "Series Description: (EMPTY)" << dicom_stream::endl;
#endif

    // clear the cached series uid
    this->CurrentSeriesDescription = dicom_stl::string();
    
    // just return, don't bother updating the internal databases of UID's
    return;
    }

  char* newString = (char*) val;
  dicom_stl::string newStdString(newString);

#ifdef DEBUG_DICOM_APP_HELPER  
  dicom_stream::cout << "Series Description: " << newStdString << dicom_stream::endl;
#endif
  // Put the series description into the internal database mapping series UIDs
  // to InstanceUIDs
  DICOMAppHelperImplementation::SeriesUIDToSeriesDescriptionMapType::iterator iiter = this->Implementation->SeriesUIDToSeriesDescriptionMap.find(this->CurrentSeriesUID);
  if ( iiter == this->Implementation->SeriesUIDToSeriesDescriptionMap.end()) // if not found we insert
    {
    this->Implementation->SeriesUIDToSeriesDescriptionMap.insert(dicom_stl::pair<const dicom_stl::string, dicom_stl::string> (this->CurrentSeriesUID, newStdString));
    }
  this->CurrentSeriesDescription = newStdString;
}

void DICOMAppHelper::OutputSeries()
{
  dicom_stream::cout << dicom_stream::endl << dicom_stream::endl;
        
  for (DICOMAppHelperImplementation::SeriesUIDToInstanceUIDMapType::iterator iter = this->Implementation->SeriesUIDToInstanceUIDMap.begin();
       iter != this->Implementation->SeriesUIDToInstanceUIDMap.end();
       iter++)
    {
    dicom_stream::cout << "SERIES: " << (*iter).first.c_str() << dicom_stream::endl;
    dicom_stl::vector<dicom_stl::string>& v_ref = (*iter).second;
             
    for (dicom_stl::vector<dicom_stl::string>::iterator v_iter = v_ref.begin();
         v_iter != v_ref.end();
         v_iter++)
      {
      DICOMAppHelperImplementation::InstanceUIDToSliceOrderingMapType::iterator sn_iter = Implementation->InstanceUIDToSliceOrderingMap.find(*v_iter);

      int slice = -1;
      if (sn_iter != Implementation->InstanceUIDToSliceOrderingMap.end())
        {
        slice = (*sn_iter).second.SliceNumber;
        }
      dicom_stream::cout << "\t" << (*v_iter).c_str() << " : "
                         << this->Implementation->InstanceUIDToFileNameMap[*v_iter] << " : ";
      if (slice != -1)
        {
        dicom_stream::cout << " [SliceNumber = " << slice<< "] ";
        }
      if (this->Implementation->SeriesUIDToContoursMap[(*iter).first].size() != 0)
        {
        dicom_stream::cout << " [Number of contours = "
                           << this->Implementation->SeriesUIDToContoursMap[(*iter).first].size() << "] ";
        }
      dicom_stream::cout << dicom_stream::endl;
      }
                
    }
}





void DICOMAppHelper::ArrayCallback(DICOMParser *parser,
                                   doublebyte group,
                                   doublebyte element,
                                   DICOMParser::VRTypes datatype,
                                   unsigned char* val,
                                   quadbyte len) 
{
  const char* desc = "No description";
  
  TagMapType::iterator iter = this->Implementation->TagMap.find(dicom_stl::pair<doublebyte, doublebyte> (group, element));
  if (iter != this->Implementation->TagMap.end())
    {
    desc = (*iter).second.description;
    }

  int t2 = int((0x0000FF00 & datatype) >> 8);
  int t1 = int((0x000000FF & datatype));

  char ct2(t2);
  char ct1(t1);

    
  HeaderFile << "(0x";

  HeaderFile.width(4);
  char prev = HeaderFile.fill('0');

  HeaderFile << dicom_stream::hex << group;
  HeaderFile << ",0x";

  HeaderFile.width(4);
  HeaderFile.fill('0');
    
  HeaderFile << dicom_stream::hex << element;
  HeaderFile << ") ";

  HeaderFile.fill(prev);
  HeaderFile << dicom_stream::dec;
  HeaderFile << " " << ct1 << ct2 << " ";
  HeaderFile << "[" << len << " bytes] ";
  
  HeaderFile << desc << " : ";
  
  unsigned int uival = 0;
  float fval = 0;
  double dval = 0;
  int ival = 0;

  if (val)
    {
    switch (datatype)
      {
      case DICOMParser::VR_AE:
      case DICOMParser::VR_AS:
      case DICOMParser::VR_CS:
      case DICOMParser::VR_UI:
      case DICOMParser::VR_DA:
      case DICOMParser::VR_DS:
      case DICOMParser::VR_DT:
      case DICOMParser::VR_LO:
      case DICOMParser::VR_LT:
      case DICOMParser::VR_OB: // ordered bytes
      case DICOMParser::VR_OW: // ordered words
      case DICOMParser::VR_PN:
      case DICOMParser::VR_ST:
      case DICOMParser::VR_TM:
      case DICOMParser::VR_UN:
      case DICOMParser::VR_UT:
      case DICOMParser::VR_SQ: // sequence
      case DICOMParser::VR_SH: // strings
      case DICOMParser::VR_IS:
        HeaderFile << val;
        break;
      case DICOMParser::VR_FL: // float
        fval = static_cast<float> (atof((char*) val));
        HeaderFile << fval;
        break;
      case DICOMParser::VR_FD: // float double
        fval = static_cast<float> (atof((char*) val));
        HeaderFile << dval;
        break;
      case DICOMParser::VR_UL: // unsigned long
      case DICOMParser::VR_SL: // signed long
      case DICOMParser::VR_AT:
        HeaderFile << uival;
        break;
      //case DICOMParser::VR_IS:
      //  ival = DICOMFile::ReturnAsSignedLong(val, parser->GetDICOMFile()->GetPlatformIsBigEndian()); 
      //  HeaderFile << ival;
      //  break;
      case DICOMParser::VR_SS:
        ival = DICOMFile::ReturnAsSignedShort(val, parser->GetDICOMFile()->GetPlatformIsBigEndian()); 
        HeaderFile << ival;
        break;
      case DICOMParser::VR_US: // unsigned short
        uival = DICOMFile::ReturnAsUnsignedShort(val, parser->GetDICOMFile()->GetPlatformIsBigEndian()); 
        HeaderFile << uival;
        break;
      default:
        HeaderFile << val << dicom_stream::endl;
        break;
      }
    }
  else
    {
    HeaderFile << "NULL";
    }
  
  HeaderFile << dicom_stream::dec << dicom_stream::endl;
  HeaderFile.fill(prev);

  delete [] val;
}
    
void DICOMAppHelper::SliceNumberCallback(DICOMParser *,
                                         doublebyte,
                                         doublebyte,
                                         DICOMParser::VRTypes,
                                         unsigned char* val,
                                         quadbyte len) 
{
  // Look for the current instance UID in the map of slice ordering data
  DICOMAppHelperImplementation::InstanceUIDToSliceOrderingMapType::iterator it;
  it = this->Implementation->InstanceUIDToSliceOrderingMap.find( this->InstanceUID );
  if (it == Implementation->InstanceUIDToSliceOrderingMap.end())
    {
    // instance UID not found, create a new entry
    DICOMOrderingElements ord;
    if (len > 0)
      {
      ord.SliceNumber = atoi( (char *) val);
      }

    // insert into the map
    this->Implementation->InstanceUIDToSliceOrderingMap.insert(dicom_stl::pair<const dicom_stl::string, DICOMOrderingElements>(this->InstanceUID, ord));
    }
  else
    {
    // file found, add new values
    if (len > 0)
      {
      (*it).second.SliceNumber = atoi( (char *)val );
      }
    }

  // cache the slice number
  if (len > 0)
    {
    this->SliceNumber = atoi( (char *) val);
    }
  else
    {
    this->SliceNumber = -1; // default to an unset slice number
    }
}


void DICOMAppHelper::SliceLocationCallback(DICOMParser *,
                                           doublebyte,
                                           doublebyte,
                                           DICOMParser::VRTypes,
                                           unsigned char* val,
                                           quadbyte len) 
{
  // Look for the current instance UID in the map of slice ordering data
  DICOMAppHelperImplementation::InstanceUIDToSliceOrderingMapType::iterator it;
  it = this->Implementation->InstanceUIDToSliceOrderingMap.find( this->InstanceUID );
  if (it == Implementation->InstanceUIDToSliceOrderingMap.end())
    {
    // instance UID not found, create a new entry
    DICOMOrderingElements ord;
    if (len > 0)
      {
      ord.SliceLocation = (float)atof( (char *) val);
      }

    // insert into the map
    this->Implementation->InstanceUIDToSliceOrderingMap.insert(dicom_stl::pair<const dicom_stl::string, DICOMOrderingElements>(this->InstanceUID, ord));
    }
  else
    {
    // file found, add new values
    if (len > 0)
      {
      (*it).second.SliceLocation = (float)atof( (char *)val );
      }
    }
}

void DICOMAppHelper::ImagePositionPatientCallback(DICOMParser *,
                                                  doublebyte,
                                                  doublebyte,
                                                  DICOMParser::VRTypes,
                                                  unsigned char* val,
                                                  quadbyte) 
{
  // Look for the current instance UID in the map of slice ordering data
  DICOMAppHelperImplementation::InstanceUIDToSliceOrderingMapType::iterator it;
  it = this->Implementation->InstanceUIDToSliceOrderingMap.find( this->InstanceUID );
  if (it == Implementation->InstanceUIDToSliceOrderingMap.end())
    {
    // instance UID not found, create a new entry
    DICOMOrderingElements ord;

    if (val)
      {
      sscanf( (char*)(val), "%f\\%f\\%f",
              &ord.ImagePositionPatient[0],
              &ord.ImagePositionPatient[1],
              &ord.ImagePositionPatient[2] );
      }
    else
      {
      // no actual position specified, default to the origin
      ord.ImagePositionPatient[0] = 0.0f;
      ord.ImagePositionPatient[1] = 0.0f;
      ord.ImagePositionPatient[2] = 0.0f;
      }
      
    // insert into the map
    this->Implementation->InstanceUIDToSliceOrderingMap.insert(dicom_stl::pair<const dicom_stl::string, DICOMOrderingElements>(this->InstanceUID, ord));

    // cache the value
    memcpy( this->ImagePositionPatient, ord.ImagePositionPatient,
            3*sizeof(float) );
    }
  else
    {
    if (val)
      {
      // file found, add new values
      sscanf( (char*)(val), "%f\\%f\\%f",
              &(*it).second.ImagePositionPatient[0],
              &(*it).second.ImagePositionPatient[1],
              &(*it).second.ImagePositionPatient[2] );
      }
    else
      {
      // no actual position specified, default to the origin
      (*it).second.ImagePositionPatient[0] = 0.0f;
      (*it).second.ImagePositionPatient[1] = 0.0f;
      (*it).second.ImagePositionPatient[2] = 0.0f;
      }
    
    // cache the value
    memcpy( this->ImagePositionPatient, (*it).second.ImagePositionPatient,
            3*sizeof(float) );
    }
}


void DICOMAppHelper::ImageOrientationPatientCallback(DICOMParser *,
                                                     doublebyte,
                                                     doublebyte,
                                                     DICOMParser::VRTypes,
                                                     unsigned char* val,
                                                     quadbyte) 
{
  // Look for the current instance UID in the map of slice ordering data
  DICOMAppHelperImplementation::InstanceUIDToSliceOrderingMapType::iterator it;
  it = this->Implementation->InstanceUIDToSliceOrderingMap.find(this->InstanceUID);
  if (it == Implementation->InstanceUIDToSliceOrderingMap.end())
    {
    // instance UID not found, create a new entry
    DICOMOrderingElements ord;
    if (val)
      {
      sscanf( (char*)(val), "%f\\%f\\%f\\%f\\%f\\%f",
              &ord.ImageOrientationPatient[0],
              &ord.ImageOrientationPatient[1],
              &ord.ImageOrientationPatient[2],
              &ord.ImageOrientationPatient[3],
              &ord.ImageOrientationPatient[4],
              &ord.ImageOrientationPatient[5] );
      }
    else
      {
      // no orientation defined, default to an standard axial orientation
      ord.ImageOrientationPatient[0] = 1.0f;
      ord.ImageOrientationPatient[1] = 0.0f;
      ord.ImageOrientationPatient[2] = 0.0f;
      ord.ImageOrientationPatient[3] = 0.0f;
      ord.ImageOrientationPatient[4] = 1.0f;
      ord.ImageOrientationPatient[5] = 0.0f;
      }
    
    // insert into the map
    this->Implementation->InstanceUIDToSliceOrderingMap.insert(dicom_stl::pair<const dicom_stl::string, DICOMOrderingElements>(this->InstanceUID, ord));
    }
  else
    {
    // file found, add new values
    if (val)
      {
      sscanf( (char*)(val), "%f\\%f\\%f\\%f\\%f\\%f",
              &(*it).second.ImageOrientationPatient[0],
              &(*it).second.ImageOrientationPatient[1],
              &(*it).second.ImageOrientationPatient[2],
              &(*it).second.ImageOrientationPatient[3],
              &(*it).second.ImageOrientationPatient[4],
              &(*it).second.ImageOrientationPatient[5] );
      }
    else
      {
      // no orientation defined, default to an standard axial orientation
      (*it).second.ImageOrientationPatient[0] = 1.0f;
      (*it).second.ImageOrientationPatient[1] = 0.0f;
      (*it).second.ImageOrientationPatient[2] = 0.0f;
      (*it).second.ImageOrientationPatient[3] = 0.0f;
      (*it).second.ImageOrientationPatient[4] = 1.0f;
      (*it).second.ImageOrientationPatient[5] = 0.0f;
      }
    }
}


void DICOMAppHelper::TransferSyntaxCallback(DICOMParser *parser,
                                            doublebyte,
                                            doublebyte,
                                            DICOMParser::VRTypes,
                                            unsigned char* val,
                                            quadbyte) 
{

#ifdef DEBUG_DICOM_APP_HELPER
#ifdef WIN32
  char platformByteOrder = 'L';
#else
  char platformByteOrder = 'B';
#endif
  dicom_stream::cout << "Platform byte order: " << platformByteOrder << dicom_stream::endl;
#endif

  static const char* TRANSFER_UID_EXPLICIT_BIG_ENDIAN = "1.2.840.10008.1.2.2";

  // Only add the ToggleSwapBytes callback when we need it.
  if (strcmp(TRANSFER_UID_EXPLICIT_BIG_ENDIAN, (char*) val) == 0)
    {
    this->ByteSwapData = true;
    parser->AddDICOMTagCallback(0x0800, 0x0000, DICOMParser::VR_UNKNOWN, ToggleSwapBytesCB);
#ifdef DEBUG_DICOM_APP_HELPER
    dicom_stream::cerr <<"Registering callback for swapping bytes." << dicom_stream::endl;
#endif
    }
  
  if (this->TransferSyntaxUID)
    {
    delete this->TransferSyntaxUID;
    }
  this->TransferSyntaxUID = new dicom_stl::string((char*) val);

#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "Transfer Syntax UID: " << *this->TransferSyntaxUID;
  dicom_stream::cout << " " << this->TransferSyntaxUIDDescription(this->TransferSyntaxUID->c_str()) << dicom_stream::endl;
#endif
}

void DICOMAppHelper::BitsAllocatedCallback(DICOMParser *parser,
                                           doublebyte,
                                           doublebyte,
                                           DICOMParser::VRTypes,
                                           unsigned char* val,
                                           quadbyte len) 
{
  if (len == 0)
    {
    // no value, clear the cached field, return to default BitsAllocated
    this->BitsAllocated = 8;
    return;
    }
  
  this->BitsAllocated = parser->GetDICOMFile()->ReturnAsUnsignedShort(val, parser->GetDICOMFile()->GetPlatformIsBigEndian());
#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "Bits allocated: " << this->BitsAllocated << dicom_stream::endl;
#endif
}


void DICOMAppHelper::ToggleSwapBytesCallback(DICOMParser *parser,
                                             doublebyte,
                                             doublebyte,
                                             DICOMParser::VRTypes,
                                             unsigned char* ,
                                             quadbyte len) 
{
#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "ToggleSwapBytesCallback" << dicom_stream::endl;
#endif
  bool bs = parser->GetDICOMFile()->GetPlatformIsBigEndian();
  parser->GetDICOMFile()->SetPlatformIsBigEndian(!bs);

#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "Set byte swap to: " << parser->GetDICOMFile()->GetPlatformIsBigEndian() << dicom_stream::endl;
#endif

  long pos = parser->GetDICOMFile()->Tell();

  //
  // The +4 is probably a hack, but it's a guess at the length of the previous field.
  //
  parser->GetDICOMFile()->SkipToPos(pos - len + 4);
}


void DICOMAppHelper::PixelSpacingCallback(DICOMParser *parser,
                                          doublebyte group,
                                          doublebyte element,
                                          DICOMParser::VRTypes,
                                          unsigned char* val,
                                          quadbyte len) 
{

  if (group == 0x0028 && element == 0x0030)
    {
    float fval = 1.0f; // defaul of 1mm
    if (len > 0)
      {
      fval = DICOMFile::ReturnAsFloat(val, parser->GetDICOMFile()->GetPlatformIsBigEndian());
      this->PixelSpacing[1] = fval;
      unsigned char * val2 = val;  // search for separator
      while( *val2 != '\\' && *val2 != 0 ) val2++;
      if( *val2 == 0 )
        {
        dicom_stream::cerr << "Pixel spacing is missing separator!" << dicom_stream::endl;
        }
      else
        {
        val2++; // start in the character after the delimiter.
        fval = DICOMFile::ReturnAsFloat(val2, parser->GetDICOMFile()->GetPlatformIsBigEndian());
        this->PixelSpacing[0] = fval;
        }
      }
    else
      {
      this->PixelSpacing[0] = this->PixelSpacing[1] = fval;
      }
    }
  else if (group == 0x0018 && element == 0x0050)
    {
    float fval = 1.0f; // defaul of 1mm
    if (len > 0)
      {
      fval = DICOMFile::ReturnAsFloat(val, parser->GetDICOMFile()->GetPlatformIsBigEndian());
      }
    this->PixelSpacing[2] = fval;
    }
}

void DICOMAppHelper::WidthCallback(DICOMParser *parser,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  unsigned short uival = 0;

  if (len > 0)
    {
    uival = DICOMFile::ReturnAsUnsignedShort(val, parser->GetDICOMFile()->GetPlatformIsBigEndian());
    }
  
#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "Width: " << uival << dicom_stream::endl;
#endif

  this->Width = uival;
  this->Dimensions[0] = this->Width;
}

void DICOMAppHelper::HeightCallback(DICOMParser *parser,
                                    doublebyte,
                                    doublebyte,
                                    DICOMParser::VRTypes,
                                    unsigned char* val,
                                    quadbyte len) 
{
  unsigned short uival = 0;

  if (len > 0)
    {
    uival = DICOMFile::ReturnAsUnsignedShort(val, parser->GetDICOMFile()->GetPlatformIsBigEndian());
    }
  
#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "Height: " << uival << dicom_stream::endl;
#endif
  this->Height = uival;
  this->Dimensions[1] = this->Height;
}


void DICOMAppHelper::PixelRepresentationCallback( DICOMParser *parser,
                                                  doublebyte,
                                                  doublebyte,
                                                  DICOMParser::VRTypes,
                                                  unsigned char* val,
                                                  quadbyte len)
{
  unsigned short uival = 1; // default of unsigned

  if (len > 0)
    {
    uival = DICOMFile::ReturnAsUnsignedShort(val, parser->GetDICOMFile()->GetPlatformIsBigEndian());
    }
  
#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "Pixel Representation: " << (uival ? "Signed" : "Unsigned") << dicom_stream::endl;
#endif
  this->PixelRepresentation = uival;
}

void DICOMAppHelper::PhotometricInterpretationCallback( DICOMParser *,
                                                        doublebyte,
                                                        doublebyte,
                                                        DICOMParser::VRTypes,
                                                        unsigned char* val,
                                                        quadbyte len)
{
#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "Photometric Interpretation: " << (char*) val << dicom_stream::endl;
#endif
  if (this->PhotometricInterpretation)
    {
    delete this->PhotometricInterpretation;
    }

  if (len > 0)
    {
    this->PhotometricInterpretation = new dicom_stl::string((char*) val);
    }
  else
    {
    this->PhotometricInterpretation = NULL;
    }
}

void DICOMAppHelper::PixelDataCallback( DICOMParser *,
                                        doublebyte,
                                        doublebyte,
                                        DICOMParser::VRTypes,
                                        unsigned char* data,
                                        quadbyte len)
{
  int numPixels = this->Dimensions[0] * this->Dimensions[1] * this->GetNumberOfComponents();

  // if length was undefined, i.e. 0xffff, then use numpixels
  if (len == 0xffff)
    {
    numPixels = numPixels;
    }
  else
    {
    // length was specified, but only read up to len bytes (as
    // opposed to the image size times number of components)
    if (len < numPixels)
      {
      numPixels = len;
      }
    if (numPixels < 0)
      {
      numPixels = 0;
      }
    }

#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "numPixels : " << numPixels << dicom_stream::endl;
#endif

  int ptrIncr = int(this->BitsAllocated/8.0);

  unsigned short* ushortInputData = reinterpret_cast<unsigned short*>(data);
  unsigned char* ucharInputData = data;
  short* shortInputData = reinterpret_cast<short*> (data);

  float* floatOutputData; // = NULL;
  
  bool isFloat = this->RescaledImageDataIsFloat();

  if (isFloat)
    {
#ifdef DEBUG_DICOM_APP_HELPER
    dicom_stream::cout << "Slope and offset are not integer valued : ";
    dicom_stream::cout << this->RescaleSlope << ", " << this->RescaleOffset << dicom_stream::endl;
#endif
    if (this->ImageData)
      {
      delete [] (static_cast<char*> (this->ImageData));
      }
    this->ImageData = new float[numPixels];
    floatOutputData = static_cast<float*> (this->ImageData);

    this->ImageDataType = DICOMParser::VR_FL;
    this->ImageDataLengthInBytes = numPixels * sizeof(float);
    float newFloatPixel;

    if (ptrIncr == 1)
      {
      for (int i = 0; i < numPixels; i++)
        {
        newFloatPixel = float(this->RescaleSlope * ucharInputData[i] + this->RescaleOffset);
        floatOutputData[i] = newFloatPixel;
        }
#ifdef DEBUG_DICOM_APP_HELPER
      dicom_stream::cout << "Did rescale, offset to float from char." << dicom_stream::endl;
      dicom_stream::cout << numPixels << " pixels." << dicom_stream::endl;
#endif
      }
    else if (ptrIncr == 2)
      {
      for (int i = 0; i < numPixels; i++)
        {
        newFloatPixel = float(this->RescaleSlope * ushortInputData[i] + this->RescaleOffset);
        floatOutputData[i] = newFloatPixel;
        }
#ifdef DEBUG_DICOM_APP_HELPER
      dicom_stream::cout << "Did rescale, offset to float from short." << dicom_stream::endl;
      dicom_stream::cout << numPixels << " pixels." << dicom_stream::endl;
#endif
      }
    }
  else
    {
#ifdef DEBUG_DICOM_APP_HELPER
    dicom_stream::cout << "Slope and offset are integer valued : ";
    dicom_stream::cout << this->RescaleSlope << ", " << this->RescaleOffset << dicom_stream::endl;
#endif

    if (ptrIncr == 1)
      {
      if (this->ImageData)
        {
        delete [] (static_cast<char*> (this->ImageData));
        }
      this->ImageData = new char[numPixels];
  
      char*  charOutputData =  static_cast<char*>  (this->ImageData);

      this->ImageDataType = DICOMParser::VR_OB;
      this->ImageDataLengthInBytes = numPixels * sizeof(char);
      char newCharPixel;

      for (int i = 0; i < numPixels; i++)
        {
        newCharPixel = char(this->RescaleSlope * ucharInputData[i] + this->RescaleOffset);
        charOutputData[i] = newCharPixel;
        }
#ifdef DEBUG_DICOM_APP_HELPER
      dicom_stream::cout << "Did rescale, offset to char from char." << dicom_stream::endl;
      dicom_stream::cout << numPixels << " pixels." << dicom_stream::endl;
#endif
      }
    else if (ptrIncr == 2)
      {
      if (this->ImageData)
        {
        delete [] (static_cast<char*> (this->ImageData));
        }
      this->ImageData = new short[numPixels];
      short* shortOutputData = static_cast<short*> (this->ImageData);

      this->ImageDataType = DICOMParser::VR_OW;
      this->ImageDataLengthInBytes = numPixels * sizeof(short);
      short newShortPixel;
      for (int i = 0; i < numPixels; i++)
        {
        newShortPixel = short(this->RescaleSlope * shortInputData[i] + this->RescaleOffset);
        shortOutputData[i] = newShortPixel;
        }
#ifdef DEBUG_DICOM_APP_HELPER
      dicom_stream::cout << "Did rescale, offset to short from short." << dicom_stream::endl;
      dicom_stream::cout << numPixels << " pixels." << dicom_stream::endl;
#endif
      }
    }
}


void DICOMAppHelper::ROIContourSequenceCallback( DICOMParser *,
                                        doublebyte,
                                        doublebyte,
                                        DICOMParser::VRTypes,
                                        unsigned char*,
                                        quadbyte )
{

#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "ROIContourSequence. " << dicom_stream::endl;
#endif

}

void DICOMAppHelper::ContourSequenceCallback( DICOMParser *,
                                        doublebyte,
                                        doublebyte,
                                        DICOMParser::VRTypes,
                                        unsigned char*,
                                        quadbyte)
{
  
#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "ContourSequence." << dicom_stream::endl;
#endif

}

void DICOMAppHelper::ContourGeometricTypeCallback( DICOMParser *,
                                                   doublebyte,
                                                   doublebyte,
                                                   DICOMParser::VRTypes,
                                                   unsigned char*,
                                                   quadbyte)
{
  
#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "ContourGeometricType." << dicom_stream::endl;
#endif

}

void DICOMAppHelper::ContourDataCallback( DICOMParser *,
                                        doublebyte,
                                        doublebyte,
                                        DICOMParser::VRTypes,
                                        unsigned char* data,
                                        quadbyte len)
{

  // If we haven't added a contour yet, then we must have missed the tag
  // to start the contour
  if (this->Implementation->SeriesUIDToContoursMap[this->CurrentSeriesUID].size() == 0)
    {
    dicom_stream::cerr << "DICOMAppHelper:: Found contour data tag (0x3006, 0x0050) without a matching contour sequence tag (0x3006, 0x0040)." << dicom_stream::endl;
    }
  // If the number of points in the contour is zero, then we were not
  // expecting any data or we missed the tag for the number of contour
  // points.
  else if (this->Implementation->SeriesUIDToContoursMap[this->CurrentSeriesUID].back().size() == 0)  // Note the test for equality
    {
    dicom_stream::cerr << "DICOMAppHelper:: Found contour data tag (0x3006, 0x0050) without a matching number of contour points tag (0x3006, 0x0046)." << dicom_stream::endl;
    }
  else
    {
    // read the number of points Contours.back().size()
    //
    //
    unsigned int i;
    float p;
    
    // get a reference to the contour 
    DICOMAppHelperImplementation::ContourType
      &contour = this->Implementation->SeriesUIDToContoursMap[this->CurrentSeriesUID].back();

    // read the coordinates. the space for the points has already been
    // allocated in NumberOfContourPointsCallback().  we just need to
    // parse the (x, y, z) values and put them in the contour vector.
    // Points are stored in a vector of floats (x, y, z, x, y, z, ...)
    //

    // create a temporary (null terminated) buffer that we can tokenize
    unsigned char *tdata = new unsigned char[len+1];
    memcpy((char *) tdata, (char *)data, len);
    tdata[len] = '\0';

    // tokenize and parse the buffer
    unsigned char *tPtr;
    tPtr = (unsigned char *)strtok((char *)tdata, "\\");
    for (i=0; i < contour.size(); i += 3)
      {
      sscanf( (char*)(tPtr), "%f", &p);
      contour[i] = p;
      tPtr = (unsigned char *)strtok(NULL, "\\");
      sscanf( (char*)(tPtr), "%f", &p);
      contour[i+1] = p;
      tPtr = (unsigned char *)strtok(NULL, "\\");
      sscanf( (char*)(tPtr), "%f", &p);
      contour[i+2] = p;
      tPtr = (unsigned char *)strtok(NULL, "\\");
      }

    delete [] tdata;
    }


#ifdef DEBUG_DICOM_APP_HELPER
  DICOMAppHelperImplementation::ContourType contour = this->Implementation->SeriesUIDToContoursMap[this->CurrentSeriesUID].back();
  dicom_stream::cout << "Contour with " << contour.size() / 3 << " points." << dicom_stream::endl;
  for (unsigned int i=0; i < contour.size(); i+=3)
    {
    dicom_stream::cout << "[" << contour[i] << ", " << contour[i+1] << ", " << contour[i+2] << "]"
                      << dicom_stream::endl;
    }
#endif

}

void DICOMAppHelper::NumberOfContourPointsCallback( DICOMParser *,
                                                    doublebyte,
                                                    doublebyte,
                                                    DICOMParser::VRTypes,
                                                    unsigned char* data,
                                                    quadbyte)
{

  int n;
  sscanf( (char*)(data), "%d", &n);


  // If we haven't added a contour yet, then we must have missed the tag
  // to start the contour
  if (this->Implementation->SeriesUIDToContoursMap[this->CurrentSeriesUID].size() == 0)
    {
    dicom_stream::cerr << "DICOMAppHelper:: Found number of contour points tag (0x3006, 0x0046) without a matching contour sequence tag (0x3006, 0x0040)." << dicom_stream::endl;
    }
  // If the last contour is not empty, then we haven't started the
  // current contour.  A preceding call to ContourSequenceCallback()
  // would have created an empty contour at the end of the Contour
  // list.
  else if (this->Implementation->SeriesUIDToContoursMap[this->CurrentSeriesUID].back().size() != 0) 
    {
    dicom_stream::cerr << "DICOMAppHelper:: Found number of contour points tag (0x3006, 0x0046) without a matching contour geometric type tag (0x3006, 0x0042)." << dicom_stream::endl;
    }
  else
    {
    // reserve enough space for the points in the contour (3 floats
    // per point).  note that we trigger off this size later to parse
    // the coordinates of the contours
    this->Implementation->SeriesUIDToContoursMap[this->CurrentSeriesUID].back().resize( 3*n ); 
    }
  
#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "NumberOfContourPoints : " ;
  dicom_stream::cout << n << dicom_stream::endl;
#endif

}


void DICOMAppHelper::RegisterPixelDataCallback(DICOMParser* parser)
{
  this->PixelDataCB->SetCallbackFunction(this, &DICOMAppHelper::PixelDataCallback);
  parser->AddDICOMTagCallback(0x7FE0, 0x0010, DICOMParser::VR_OW, this->PixelDataCB);
}


const char* DICOMAppHelper::TransferSyntaxUIDDescription(const char* uid)
{
  static const char* DICOM_IMPLICIT_VR_LITTLE_ENDIAN = "1.2.840.10008.1.2";
  static const char* DICOM_LOSSLESS_JPEG = "1.2.840.10008.1.2.4.70";
  static const char* DICOM_LOSSY_JPEG_8BIT = "1.2.840.10008.1.2.4.50";
  static const char* DICOM_LOSSY_JPEG_16BIT = "1.2.840.10008.1.2.4.51";
  static const char* DICOM_EXPLICIT_VR_LITTLE_ENDIAN = "1.2.840.10008.1.2.1";
  static const char* DICOM_EXPLICIT_VR_BIG_ENDIAN = "1.2.840.10008.1.2.2";
  static const char* DICOM_GE_PRIVATE_IMPLICIT_BIG_ENDIAN = "1.2.840.113619.5.2";

  if (!strcmp(DICOM_IMPLICIT_VR_LITTLE_ENDIAN, uid))
    {
    return "Implicit VR, Little Endian";
    }
  else if (!strcmp(DICOM_LOSSLESS_JPEG, uid))
    {
    return "Lossless JPEG";
    }
  else if (!strcmp(DICOM_LOSSY_JPEG_8BIT, uid))
    {
    return "Lossy JPEG 8 bit";
    }
  else if (!strcmp(DICOM_LOSSY_JPEG_16BIT, uid))
    {
    return "Lossy JPEG 16 bit.";
    }
  else if (!strcmp(DICOM_EXPLICIT_VR_LITTLE_ENDIAN, uid))
    {
    return "Explicit VR, Little Endian.";
    }
  else if (!strcmp(DICOM_EXPLICIT_VR_BIG_ENDIAN, uid))
    {
    return "Explicit VR, Big Endian.";
    }
  else if (!strcmp(DICOM_GE_PRIVATE_IMPLICIT_BIG_ENDIAN, uid))
    {
    return "GE Private, Implicit VR, Big Endian Image Data.";
    }
  else
    {
    return "Unknown.";
    }

}


void DICOMAppHelper::RescaleOffsetCallback( DICOMParser *parser,
                                            doublebyte,
                                            doublebyte,
                                            DICOMParser::VRTypes,
                                            unsigned char* val,
                                            quadbyte len)
{
  float fval = 0.0f;

  if (len > 0)
    {
    fval = DICOMFile::ReturnAsFloat(val, parser->GetDICOMFile()->GetPlatformIsBigEndian());
    }
  
  this->RescaleOffset = fval;
#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "Pixel offset: " << this->RescaleOffset << dicom_stream::endl;
#endif
}

void DICOMAppHelper::RescaleSlopeCallback(DICOMParser *parser,
                                          doublebyte,
                                          doublebyte ,
                                          DICOMParser::VRTypes ,
                                          unsigned char* val,
                                          quadbyte len)
{
  float fval = 1.0f;

  if (len > 0)
    {
    fval = DICOMFile::ReturnAsFloat(val,
                      parser->GetDICOMFile()->GetPlatformIsBigEndian ());
    }
  
#ifdef DEBUG_DICOM_APP_HELPER
  dicom_stream::cout << "Rescale slope: " << fval << dicom_stream::endl;
#endif
  this->RescaleSlope = fval;
}

void DICOMAppHelper::PatientNameCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_PatientName, (const char*)val, len1);
    m_PatientName[len1] = '\0';
    }
  else
    {
    m_PatientName[0] = '\0';
    }
}

void DICOMAppHelper::PatientIDCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_PatientID, (const char*)val, len1);
    m_PatientID[len1] = '\0';
    }
  else
    {
    m_PatientID[0] = '\0';
    }
}

void DICOMAppHelper::PatientSexCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_PatientSex, (const char*)val, len1);
    m_PatientSex[len1] = '\0';
    }
  else
    {
    m_PatientSex[0] = '\0';
    }
}

void DICOMAppHelper::PatientAgeCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_PatientAge, (const char*)val, len1);
    m_PatientAge[len1] = '\0';
    }
  else
    {
    m_PatientAge[0] = '\0';
    }
}

void DICOMAppHelper::PatientDOBCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_PatientDOB, (const char*)val, len1);
    m_PatientDOB[len1] = '\0';
    }
  else
    {
    m_PatientDOB[0] = '\0';
    }
}


void DICOMAppHelper::StudyIDCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_StudyID, (const char*)val, len1);
    m_StudyID[len1] = '\0';
    }
  else
    {
    m_StudyID[0] = '\0';
    }
}


void DICOMAppHelper::StudyDescriptionCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_StudyDescription, (const char*)val, len1);
    m_StudyDescription[len1] = '\0';
    }
  else
    {
    m_StudyDescription[0] = '\0';
    }
}

void DICOMAppHelper::BodyPartCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_BodyPart, (const char*)val, len1);
    m_BodyPart[len1] = '\0';
    }
  else
    {
    m_BodyPart[0] = '\0';
    return;
    }

  char* newString = (char*) val;
  dicom_stl::string newStdString(newString);

#ifdef DEBUG_DICOM_APP_HELPER  
  dicom_stream::cout << "Body Part: " << newStdString << dicom_stream::endl;
#endif
  // Put the series description into the internal database mapping series UIDs
  // to InstanceUIDs
  DICOMAppHelperImplementation::SeriesUIDToBodyPartMapType::iterator iiter = this->Implementation->SeriesUIDToBodyPartMap.find(this->CurrentSeriesUID);
  if ( iiter == this->Implementation->SeriesUIDToBodyPartMap.end()) // if not found we insert
    {
    this->Implementation->SeriesUIDToBodyPartMap.insert(dicom_stl::pair<const dicom_stl::string, dicom_stl::string> (this->CurrentSeriesUID, newStdString));
    }
  this->CurrentBodyPart = newStdString;
} 


void DICOMAppHelper::NumberOfSeriesInStudyCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_NumberOfSeriesInStudy, (const char*)val, len1);
    m_NumberOfSeriesInStudy[len1] = '\0';
    }
  else
    {
    m_NumberOfSeriesInStudy[0] = '\0';
    }
}

void DICOMAppHelper::NumberOfStudyRelatedSeriesCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_NumberOfStudyRelatedSeries, (const char*)val, len1);
    m_NumberOfStudyRelatedSeries[len1] = '\0';
    }
  else
    {
    m_NumberOfStudyRelatedSeries[0] = '\0';
    }
} 

void DICOMAppHelper::StudyDateCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_StudyDate, (const char*)val, len1);
    m_StudyDate[len1] = '\0';
    }
  else
    {
    m_StudyDate[0] = '\0';
    }
}

void DICOMAppHelper::ModalityCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_Modality, (const char*)val, len1);
    m_Modality[len1] = '\0';
    }
  else
    {
    m_Modality[0] = '\0';
    }
}

void DICOMAppHelper::ManufacturerCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_Manufacturer, (const char*)val, len1);
    m_Manufacturer[len1] = '\0';
    }
  else
    {
    m_Manufacturer[0] = '\0';
    }
}

void DICOMAppHelper::InstitutionCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_Institution, (const char*)val, len1);
    m_Institution[len1] = '\0';
    }
  else
    {
    m_Institution[0] = '\0';
    }
}

void DICOMAppHelper::ModelCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_Model, (const char*)val, len1);
    m_Model[len1] = '\0';
    }
  else
    {
    m_Model[0] = '\0';
    }
}


void DICOMAppHelper::ScanOptionsCallback(DICOMParser *,
                                   doublebyte,
                                   doublebyte,
                                   DICOMParser::VRTypes,
                                   unsigned char* val,
                                   quadbyte len)
{
  if (val)
    {
    quadbyte len1 = (len<512) ? len : 511;
    strncpy(m_ScanOptions, (const char*)val, len1);
    m_ScanOptions[len1] = '\0';
    }
  else
    {
    m_ScanOptions[0] = '\0';
    return;
    }

  char* newString = (char*) val;
  dicom_stl::string newStdString(newString);

#ifdef DEBUG_DICOM_APP_HELPER  
  dicom_stream::cout << "Scan Options: " << newStdString << dicom_stream::endl;
#endif
  // Put the series description into the internal database mapping series UIDs
  // to InstanceUIDs
  DICOMAppHelperImplementation::SeriesUIDToScanOptionsMapType::iterator iiter = this->Implementation->SeriesUIDToScanOptionsMap.find(this->CurrentSeriesUID);
  if ( iiter == this->Implementation->SeriesUIDToScanOptionsMap.end()) // if not found we insert
    {
    this->Implementation->SeriesUIDToScanOptionsMap.insert(dicom_stl::pair<const dicom_stl::string, dicom_stl::string> (this->CurrentSeriesUID, newStdString));
    }
  this->CurrentScanOptions = newStdString;
}

bool DICOMAppHelper::RescaledImageDataIsFloat()
{
  int s = int(this->RescaleSlope);
  int o = int(this->RescaleOffset);

  float sf = float(s);
  float of = float(o);

  double d1 = fabs(sf - this->RescaleSlope);
  double d2 = fabs(of - this->RescaleOffset);

  if (d1 > 0.0 || d2 > 0.0)
    {
    return true;
    }
  else
    {
    return false;
    }
}

void DICOMAppHelper::GetImageData(void*& data, DICOMParser::VRTypes& dataType, unsigned long& len)
{
  data = this->ImageData;
  dataType = this->ImageDataType;
  len = this->ImageDataLengthInBytes;
}

bool DICOMAppHelper::RescaledImageDataIsSigned()
{
  bool rescaleSigned = (this->RescaleSlope < 0.0);
  bool pixelRepSigned = (this->PixelRepresentation == 1);
  bool offsetSigned = (this->RescaleOffset < 0.0);
 
  return (rescaleSigned || pixelRepSigned || offsetSigned);
}

dicom_stl::string
DICOMAppHelper::GetFileName( const dicom_stl::string &instanceUID )
{
  dicom_stl::string ret("");

  DICOMAppHelperImplementation::InstanceUIDToFileNameMapType::iterator
    it = this->Implementation->InstanceUIDToFileNameMap.find( instanceUID );

  if (it != this->Implementation->InstanceUIDToFileNameMap.end() )
    {
    ret = (*it).second;
    }

  return ret;
}


void DICOMAppHelper::GetSliceNumberFilenamePairs(const dicom_stl::string &seriesUID,
                                                 dicom_stl::vector<dicom_stl::pair<int, dicom_stl::string> >& v,
                                                 bool ascending)
{
  v.clear();

  DICOMAppHelperImplementation::SeriesUIDToInstanceUIDMapType::iterator miter  = this->Implementation->SeriesUIDToInstanceUIDMap.find(seriesUID);

  if (miter == this->Implementation->SeriesUIDToInstanceUIDMap.end() )
    {
    return;
    }

  // grab the instance uids for the specified series
  dicom_stl::vector<dicom_stl::string> instanceUIDs = (*miter).second;

  for (dicom_stl::vector<dicom_stl::string>::iterator instanceIter = instanceUIDs.begin();
       instanceIter != instanceUIDs.end();
       instanceIter++)
       {
       dicom_stl::pair<int, dicom_stl::string> p;
       p.second = dicom_stl::string(this->Implementation->InstanceUIDToFileNameMap[*instanceIter]);
       int slice_number;
       DICOMAppHelperImplementation::InstanceUIDToSliceOrderingMapType::iterator sn_iter = Implementation->InstanceUIDToSliceOrderingMap.find(*instanceIter);
       // Only store files that have a valid slice number
       if (sn_iter != Implementation->InstanceUIDToSliceOrderingMap.end())
        {
        slice_number = (*sn_iter).second.SliceNumber;
        p.first = slice_number;
        v.push_back(p);
        }
       }
  if (ascending)
    {
    dicom_stl::sort(v.begin(), v.end(), lt_pair_int_string());
    }
  else
    {
    dicom_stl::sort(v.begin(), v.end(), gt_pair_int_string());
    }
}

void DICOMAppHelper::GetSliceNumberFilenamePairs(dicom_stl::vector<dicom_stl::pair<int, dicom_stl::string> >& v, bool ascending)
{
  // Default to using the first series
  if (this->Implementation->SeriesUIDToInstanceUIDMap.size() > 0)
    {
    this->GetSliceNumberFilenamePairs( (*this->Implementation->SeriesUIDToInstanceUIDMap.begin()).first, v, ascending );
    }
  else
    {
    v.clear();
    }
}

void DICOMAppHelper::GetSliceLocationFilenamePairs(const dicom_stl::string &seriesUID,
                                                   dicom_stl::vector<dicom_stl::pair<float, dicom_stl::string> >& v,
                                                   bool ascending)
{
  v.clear();

  DICOMAppHelperImplementation::SeriesUIDToInstanceUIDMapType::iterator miter  = this->Implementation->SeriesUIDToInstanceUIDMap.find(seriesUID);

  if (miter == this->Implementation->SeriesUIDToInstanceUIDMap.end() )
    {
    return;
    }

  // grab the instance UIDs for the specified series
  dicom_stl::vector<dicom_stl::string> instanceUIDs = (*miter).second;

  for (dicom_stl::vector<dicom_stl::string>::iterator instanceIter = instanceUIDs.begin();
       instanceIter != instanceUIDs.end();
       instanceIter++)
       {
       dicom_stl::pair<float, dicom_stl::string> p;
       p.second = dicom_stl::string(this->Implementation->InstanceUIDToFileNameMap[*instanceIter]);
       float slice_location;
       DICOMAppHelperImplementation::InstanceUIDToSliceOrderingMapType::iterator sn_iter = Implementation->InstanceUIDToSliceOrderingMap.find(*instanceIter);

       if (sn_iter != Implementation->InstanceUIDToSliceOrderingMap.end())
        {
        slice_location = (*sn_iter).second.SliceLocation;
        p.first = slice_location;
        v.push_back(p);
        }
       }
  if (ascending)
    {
    dicom_stl::sort(v.begin(), v.end(), lt_pair_float_string());
    }
  else
    {
    dicom_stl::sort(v.begin(), v.end(), gt_pair_float_string());
    }
}

void DICOMAppHelper::GetSliceLocationFilenamePairs(dicom_stl::vector<dicom_stl::pair<float, dicom_stl::string> >& v,
                                                   bool ascending)
{
  // Default to using the first series
  if (this->Implementation->SeriesUIDToInstanceUIDMap.size() > 0)
    {
    this->GetSliceLocationFilenamePairs( (*this->Implementation->SeriesUIDToInstanceUIDMap.begin()).first,
                                         v,
                                         ascending );
    }
  else
    {
    v.clear();
    }
}

void DICOMAppHelper::GetImagePositionPatientFilenamePairs(const dicom_stl::string &seriesUID, dicom_stl::vector<dicom_stl::pair<float, dicom_stl::string> >& v,
                                                          bool ascending)
{
  v.clear();

  DICOMAppHelperImplementation::SeriesUIDToInstanceUIDMapType::iterator miter  = this->Implementation->SeriesUIDToInstanceUIDMap.find(seriesUID);

  if (miter == this->Implementation->SeriesUIDToInstanceUIDMap.end() )
    {
    return;
    }

  // grab the instance UIDs for the specified series
  dicom_stl::vector<dicom_stl::string> instanceUIDs = (*miter).second;

  for (dicom_stl::vector<dicom_stl::string>::iterator instanceIter = instanceUIDs.begin();
       instanceIter != instanceUIDs.end();
       instanceIter++)
       {
       dicom_stl::pair<float, dicom_stl::string> p;
       p.second = dicom_stl::string(this->Implementation->InstanceUIDToFileNameMap[*instanceIter]);

       float image_position;
       float normal[3];
       
       DICOMAppHelperImplementation::InstanceUIDToSliceOrderingMapType::iterator sn_iter = Implementation->InstanceUIDToSliceOrderingMap.find(*instanceIter);

       if (sn_iter != Implementation->InstanceUIDToSliceOrderingMap.end())
        {
        // compute the image patient position wrt to the slice image
        // plane normal

        normal[0] = ((*sn_iter).second.ImageOrientationPatient[1]
                     * (*sn_iter).second.ImageOrientationPatient[5])
          - ((*sn_iter).second.ImageOrientationPatient[2]
             * (*sn_iter).second.ImageOrientationPatient[4]);
        normal[1] = ((*sn_iter).second.ImageOrientationPatient[2]
                     * (*sn_iter).second.ImageOrientationPatient[3])
          - ((*sn_iter).second.ImageOrientationPatient[0]
             *(*sn_iter).second.ImageOrientationPatient[5]);
        normal[2] = ((*sn_iter).second.ImageOrientationPatient[0]
                     * (*sn_iter).second.ImageOrientationPatient[4])
          - ((*sn_iter).second.ImageOrientationPatient[1]
             * (*sn_iter).second.ImageOrientationPatient[3]);
        
        image_position = (normal[0]*(*sn_iter).second.ImagePositionPatient[0])
          + (normal[1]*(*sn_iter).second.ImagePositionPatient[1])
          + (normal[2]*(*sn_iter).second.ImagePositionPatient[2]);
        p.first = image_position;
        v.push_back(p);
        }
       }
  if (ascending)
    {
    dicom_stl::sort(v.begin(), v.end(), lt_pair_float_string());
    }
  else
    {
    dicom_stl::sort(v.begin(), v.end(), gt_pair_float_string());
    }
}

void DICOMAppHelper::GetImagePositionPatientFilenamePairs(dicom_stl::vector<dicom_stl::pair<float, dicom_stl::string> >& v,
                                                          bool ascending)
{
  // Default to using the first series
  if (this->Implementation->SeriesUIDToInstanceUIDMap.size() > 0)
    {
    this->GetImagePositionPatientFilenamePairs( (*this->Implementation->SeriesUIDToInstanceUIDMap.begin()).first, v, ascending );
    }
  else
    {
    v.clear();
    }
}


void DICOMAppHelper::GetContours(const dicom_stl::string &seriesUID,
                                 dicom_stl::vector<dicom_stl::vector<float> >& v)
{
  v.clear();

  DICOMAppHelperImplementation::SeriesUIDToContoursMapType::iterator iter = this->Implementation->SeriesUIDToContoursMap.find(seriesUID);
  
  if (iter == this->Implementation->SeriesUIDToContoursMap.end() )
    {
    return;
    }

  // All we need to do is copy the contours to the output
  v = (*iter).second;
}

void DICOMAppHelper::GetContours(dicom_stl::vector<dicom_stl::vector<float> >& v)
{
  // Default to using the first series
  if (this->Implementation->SeriesUIDToInstanceUIDMap.size() > 0)
    {
    this->GetContours( (*this->Implementation->SeriesUIDToInstanceUIDMap.begin()).first, v );
    }
  else
    {
    v.clear();
    }
}


void DICOMAppHelper::GetReferencedInstanceUIDs(const dicom_stl::string &seriesUID,
                                 dicom_stl::vector<dicom_stl::string>& v)
{
  v.clear();

  DICOMAppHelperImplementation::SeriesUIDToReferencedInstanceUIDMapType::iterator iter = this->Implementation->SeriesUIDToReferencedInstanceUIDMap.find(seriesUID);
  
  if (iter == this->Implementation->SeriesUIDToReferencedInstanceUIDMap.end() )
    {
    return;
    }

  // All we need to do is copy the referenced instanced to the output
  v = (*iter).second;
}

void DICOMAppHelper::GetReferencedInstanceUIDs(dicom_stl::vector<dicom_stl::string>& v)
{
  // Default to using the first series
  if (this->Implementation->SeriesUIDToInstanceUIDMap.size() > 0)
    {
    this->GetReferencedInstanceUIDs( (*this->Implementation->SeriesUIDToReferencedInstanceUIDMap.begin()).first, v );
    }
  else
    {
    v.clear();
    }
}


void DICOMAppHelper::GetSeriesUIDs(dicom_stl::vector<dicom_stl::string> &v)
{
  v.clear();

  DICOMAppHelperImplementation::SeriesUIDToInstanceUIDMapType::iterator miter;

  for (miter = this->Implementation->SeriesUIDToInstanceUIDMap.begin(); miter != this->Implementation->SeriesUIDToInstanceUIDMap.end();
       ++miter)
    {
    v.push_back( (*miter).first );
    }
}

void DICOMAppHelper::GetSeriesDescriptions(dicom_stl::vector<dicom_stl::string> &v)
{
  v.clear();

  DICOMAppHelperImplementation::SeriesUIDToInstanceUIDMapType::iterator miter;

  for (miter = this->Implementation->SeriesUIDToInstanceUIDMap.begin(); miter != this->Implementation->SeriesUIDToInstanceUIDMap.end();
       ++miter)
    {
    DICOMAppHelperImplementation::SeriesUIDToSeriesDescriptionMapType::iterator iiter = this->Implementation->SeriesUIDToSeriesDescriptionMap.find((*miter).first);
    if ( iiter != this->Implementation->SeriesUIDToSeriesDescriptionMap.end()) // if found we insert
      {
      v.push_back( (*iiter).second ); 
      }
    else
      {
      dicom_stl::string value = "";
      v.push_back( value );
      }
   }
}


void DICOMAppHelper::GetBodyParts(dicom_stl::vector<dicom_stl::string> &v)
{
  v.clear();

  DICOMAppHelperImplementation::SeriesUIDToInstanceUIDMapType::iterator miter;

  for (miter = this->Implementation->SeriesUIDToInstanceUIDMap.begin(); miter != this->Implementation->SeriesUIDToInstanceUIDMap.end();
       ++miter)
    {
    DICOMAppHelperImplementation::SeriesUIDToBodyPartMapType::iterator iiter = this->Implementation->SeriesUIDToBodyPartMap.find((*miter).first);
    if ( iiter != this->Implementation->SeriesUIDToBodyPartMap.end()) // if found we insert
      {
      v.push_back( (*iiter).second ); 
      }
    else
      {
      dicom_stl::string value = "";
      v.push_back( value );
      }
   }
}


void DICOMAppHelper::GetScanOptions(dicom_stl::vector<dicom_stl::string> &v)
{
  v.clear();

  DICOMAppHelperImplementation::SeriesUIDToInstanceUIDMapType::iterator miter;

  for (miter = this->Implementation->SeriesUIDToInstanceUIDMap.begin(); miter != this->Implementation->SeriesUIDToInstanceUIDMap.end();
       ++miter)
    {
    DICOMAppHelperImplementation::SeriesUIDToScanOptionsMapType::iterator iiter = this->Implementation->SeriesUIDToScanOptionsMap.find((*miter).first);
    if ( iiter != this->Implementation->SeriesUIDToScanOptionsMap.end()) // if found we insert
      {
      v.push_back( (*iiter).second ); 
      }
    else
      {
      dicom_stl::string value = "";
      v.push_back( value );
      }
   }
}



void DICOMAppHelper::Clear()
{ 
  this->Implementation->InstanceUIDToSeriesUIDMap.clear();
  this->Implementation->InstanceUIDToSliceOrderingMap.clear();
  this->Implementation->SeriesUIDToInstanceUIDMap.clear();
  this->Implementation->SeriesUIDToSeriesDescriptionMap.clear();
  this->Implementation->SeriesUIDToContoursMap.clear();
  this->Implementation->SeriesUIDToBodyPartMap.clear();
  this->Implementation->SeriesUIDToScanOptionsMap.clear();

  this->CurrentSeriesUID = "";
  this->CurrentSeriesDescription = "";
  this->InstanceUID = "";
}
}
#ifdef _MSC_VER
#pragma warning ( pop )
#endif