File: dcitem.cc

package info (click to toggle)
dcmtk 3.6.9-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 95,648 kB
  • sloc: ansic: 426,874; cpp: 318,177; makefile: 6,401; sh: 4,341; yacc: 1,026; xml: 482; lex: 321; perl: 277
file content (4864 lines) | stat: -rw-r--r-- 174,258 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
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
/*
 *
 *  Copyright (C) 1994-2024, OFFIS e.V.
 *  All rights reserved.  See COPYRIGHT file for details.
 *
 *  This software and supporting documentation were developed by
 *
 *    OFFIS e.V.
 *    R&D Division Health
 *    Escherweg 2
 *    D-26121 Oldenburg, Germany
 *
 *
 *  Module:  dcmdata
 *
 *  Author:  Gerd Ehlers
 *
 *  Purpose: class DcmItem
 *
 */


#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */

#include "dcmtk/dcmdata/dcitem.h"
#include "dcmtk/dcmdata/dcdeftag.h"   /* for name constants */
#include "dcmtk/dcmdata/dcistrma.h"   /* for class DcmInputStream */
#include "dcmtk/dcmdata/dcobject.h"
#include "dcmtk/dcmdata/dcostrma.h"   /* for class DcmOutputStream */
#include "dcmtk/dcmdata/dcovlay.h"
#include "dcmtk/dcmdata/dcpixel.h"
#include "dcmtk/dcmdata/dcsequen.h"
#include "dcmtk/dcmdata/dcswap.h"
#include "dcmtk/dcmdata/dcvr.h"
#include "dcmtk/dcmdata/dcvrae.h"
#include "dcmtk/dcmdata/dcvras.h"
#include "dcmtk/dcmdata/dcvrat.h"
#include "dcmtk/dcmdata/dcvrcs.h"
#include "dcmtk/dcmdata/dcvrda.h"
#include "dcmtk/dcmdata/dcvrds.h"
#include "dcmtk/dcmdata/dcvrdt.h"
#include "dcmtk/dcmdata/dcvrfd.h"
#include "dcmtk/dcmdata/dcvrfl.h"
#include "dcmtk/dcmdata/dcvris.h"
#include "dcmtk/dcmdata/dcvrlo.h"
#include "dcmtk/dcmdata/dcvrlt.h"
#include "dcmtk/dcmdata/dcvrobow.h"
#include "dcmtk/dcmdata/dcvrod.h"
#include "dcmtk/dcmdata/dcvrof.h"
#include "dcmtk/dcmdata/dcvrol.h"
#include "dcmtk/dcmdata/dcvrov.h"
#include "dcmtk/dcmdata/dcvrpn.h"
#include "dcmtk/dcmdata/dcvrsh.h"
#include "dcmtk/dcmdata/dcvrsl.h"
#include "dcmtk/dcmdata/dcvrss.h"
#include "dcmtk/dcmdata/dcvrst.h"
#include "dcmtk/dcmdata/dcvrsv.h"
#include "dcmtk/dcmdata/dcvrtm.h"
#include "dcmtk/dcmdata/dcvruc.h"
#include "dcmtk/dcmdata/dcvrui.h"
#include "dcmtk/dcmdata/dcvrul.h"
#include "dcmtk/dcmdata/dcvrulup.h"
#include "dcmtk/dcmdata/dcvrur.h"
#include "dcmtk/dcmdata/dcvrus.h"
#include "dcmtk/dcmdata/dcvrut.h"
#include "dcmtk/dcmdata/dcvruv.h"
#include "dcmtk/dcmdata/dcxfer.h"
#include "dcmtk/dcmdata/dcspchrs.h"   /* for class DcmSpecificCharacterSet */
#include "dcmtk/dcmdata/dcjson.h"

#include "dcmtk/ofstd/ofstream.h"
#include "dcmtk/ofstd/ofstring.h"
#include "dcmtk/ofstd/ofcast.h"
#include "dcmtk/ofstd/ofstd.h"

#include <cstring>                    /* for memset() */

// ********************************


DcmItem::DcmItem()
  : DcmObject(DCM_ItemTag),
    elementList(NULL),
    lastElementComplete(OFTrue),
    fStartPosition(0),
    privateCreatorCache()
{
    elementList = new DcmList;
}


DcmItem::DcmItem(const DcmTag &tag,
                 const Uint32 len)
  : DcmObject(tag, len),
    elementList(NULL),
    lastElementComplete(OFTrue),
    fStartPosition(0),
    privateCreatorCache()
{
    elementList = new DcmList;
}


DcmItem::DcmItem(const DcmItem &old)
  : DcmObject(old),
    elementList(new DcmList),
    lastElementComplete(old.lastElementComplete),
    fStartPosition(old.fStartPosition),
    privateCreatorCache()
{
    if (!old.elementList->empty())
    {
        elementList->seek(ELP_first);
        old.elementList->seek(ELP_first);
        do
        {
            DcmObject *dO = old.elementList->get()->clone();
            elementList->insert(dO, ELP_next);
            // remember the parent
            dO->setParent(this);
        } while (old.elementList->seek(ELP_next));
    }
}


DcmItem& DcmItem::operator=(const DcmItem& obj)
{
    if (this != &obj)
    {
        // copy parent's member variables
        DcmObject::operator=(obj);

        // delete any existing elements
        elementList->deleteAllElements();

        // copy DcmItem's member variables
        lastElementComplete = obj.lastElementComplete;
        fStartPosition = obj.fStartPosition;
        if (!obj.elementList->empty())
        {
            elementList->seek(ELP_first);
            obj.elementList->seek(ELP_first);
            do
            {
                DcmObject *dO = obj.elementList->get()->clone();
                elementList->insert(dO, ELP_next);
                // remember the parent
                dO->setParent(this);
            } while (obj.elementList->seek(ELP_next));
        }
    }
    return *this;
}


int DcmItem::compare(const DcmItem& rhs) const
{
    if (this == &rhs)
        return 0;

    // cast away constness (dcmdata is not const correct...)
    DcmItem* myThis = NULL;
    DcmItem* myRhs = NULL;
    myThis = OFconst_cast(DcmItem*, this);
    myRhs =  OFconst_cast(DcmItem*, &rhs);

    // check length, i.e. number of elements in item
    unsigned long thisNumValues = myThis->card();
    unsigned long rhsNumValues = myRhs->card();
    if (thisNumValues < rhsNumValues)
    {
        return -1;
    }
    else if (thisNumValues > rhsNumValues)
    {
        return 1;
    }
    // iterate over all items and test equality
    for (unsigned long count = 0; count < thisNumValues; count++)
    {
        DcmElement* val = myThis->getElement(count);
        if (val)
        {
            DcmElement* rhsVal = myRhs->getElement(count);
            if (rhsVal)
            {
                int result = val->compare(*rhsVal);
                if (result != 0)
                {
                    return result;
                }
                // otherwise they are equal, continue comparison
            }
        }
    }

    // all values as well as VM equal: objects are equal
    return 0;
}


OFCondition DcmItem::copyFrom(const DcmObject& rhs)
{
  if (this != &rhs)
  {
      if (rhs.ident() != ident()) return EC_IllegalCall;
      *this = OFstatic_cast(const DcmItem &, rhs);
  }
  return EC_Normal;
}


DcmItem::~DcmItem()
{
    elementList->deleteAllElements();
    delete elementList;
}


// ********************************


OFBool DcmItem::foundVR(const Uint8* atposition)
{
    const Uint8 c1 = atposition[0];
    const Uint8 c2 = atposition[1];
    OFBool valid = OFFalse;

    if (isalpha(c1) && isalpha(c2))
    {
        Uint8 vrName[3];
        vrName[0] = c1;
        vrName[1] = c2;
        vrName[2] = '\0';

        /* is this VR name a standard VR descriptor */
        DcmVR vr( OFreinterpret_cast(const char*, &vrName[0] ) );
        valid = vr.isStandard();
    } else {
        /* cannot be a valid VR name since non-characters */
        valid = OFFalse;
    }
    return valid;
}


// ********************************


E_TransferSyntax DcmItem::checkTransferSyntax(DcmInputStream &inStream)
{
    E_TransferSyntax transferSyntax;
    Uint8 tagAndVR[6];

    /* we need 6 bytes, if there is less available we can't do much */
    if (inStream.avail() < 6)
        return EXS_LittleEndianExplicit;

    /* read 6 bytes from the input stream (try to read tag and VR (data type)) */
    inStream.mark();
    inStream.read(tagAndVR, 6);               // check tag & VR
    inStream.putback();

    /* create two tag variables (one for little, one for big */
    /* endian) in order to figure out, if there is a valid tag */
    const Uint8 c1 = tagAndVR[0];
    const Uint8 c2 = tagAndVR[1];
    const Uint8 c3 = tagAndVR[2];
    const Uint8 c4 = tagAndVR[3];
    const Uint16 t1 = OFstatic_cast(unsigned short, (c1 & 0xff) + ((c2 & 0xff) << 8));  // explicit little endian
    const Uint16 t2 = OFstatic_cast(unsigned short, (c3 & 0xff) + ((c4 & 0xff) << 8));  // conversion
    DcmTag taglittle(t1, t2);
    DcmTag tagbig(swapShort(t1), swapShort(t2));

    /* now we want to determine the transfer syntax which was used to code the information in the stream. */
    /* The decision is based on two questions: a) Did we encounter a valid tag? and b) Do the last 2 bytes */
    /* which were read from the stream represent a valid VR? In certain special cases, where the transfer */
    /* cannot be determined without doubt, we want to guess the most probable transfer syntax. */

    /* if both tag variables show an error, we encountered an invalid tag */
    if ((taglittle.error().bad()) && (tagbig.error().bad()))
    {
        /* in case we encountered an invalid tag, we want to assume that the used transfer syntax */
        /* is a little endian transfer syntax. Now we have to figure out, if it is an implicit or */
        /* explicit transfer syntax. Hence, check if the last 2 bytes represent a valid VR. */
        if (foundVR(&tagAndVR[4]))
        {
            /* if the last 2 bytes represent a valid VR, we assume that the used */
            /* transfer syntax is the little endian explicit transfer syntax. */
            transferSyntax = EXS_LittleEndianExplicit;
        } else {
            /* if the last 2 bytes did not represent a valid VR, we assume that the */
            /* used transfer syntax is the little endian implicit transfer syntax. */
            transferSyntax = EXS_LittleEndianImplicit;
        }
    }
    /* if at least one tag variable did not show an error, we encountered a valid tag */
    else
    {
        /* in case we encountered a valid tag, we want to figure out, if it is an implicit or */
        /* explicit transfer syntax. Hence, check if the last 2 bytes represent a valid VR. */
        if (foundVR(&tagAndVR[4]))
        {
            /* having figured out that the last 2 bytes represent a valid */
            /* VR, we need to find out which of the two tags was valid */
            if (taglittle.error().bad())
            {
                /* if the little endian tag was invalid, the transfer syntax is big endian explicit */
                transferSyntax = EXS_BigEndianExplicit;
            }
            else if (tagbig.error().bad())
            {
                /* if the big endian tag was invalid, the transfer syntax is little endian explicit */
                transferSyntax = EXS_LittleEndianExplicit;
            } else {
                /* if both tags were valid, we take a look at the group numbers. Since */
                /* group 0008 is much more probable than group 0800 for the first tag */
                /* we specify the following: */
                if ((taglittle.getGTag() > 0xff)&&(tagbig.getGTag() <= 0xff)) transferSyntax = EXS_BigEndianExplicit;
                else transferSyntax = EXS_LittleEndianExplicit;
            }
        } else {
            /* having figured out that the last 2 bytes do not represent a */
            /* valid VR, we need to find out which of the two tags was valid */
            if (taglittle.error().bad())
            {
                /* if the little endian tag was invalid, the transfer syntax is big endian implicit */
                transferSyntax = EXS_BigEndianImplicit;
            }
            else if (tagbig.error().bad())
            {
                /* if the big endian tag was invalid, the transfer syntax is little endian implicit */
                transferSyntax = EXS_LittleEndianImplicit;
            } else {
                /* if both tags were valid, we take a look at the group numbers. Since */
                /* group 0008 is much more probable than group 0800 for the first tag */
                /* we specify the following: */
                if ((taglittle.getGTag() > 0xff)&&(tagbig.getGTag() <= 0xff)) transferSyntax = EXS_BigEndianImplicit;
                else transferSyntax = EXS_LittleEndianImplicit;
            }
        }
    }

    /* return determined transfer syntax */
    return transferSyntax;
}


// ********************************


OFBool DcmItem::checkAndUpdateVR(DcmItem &item,
                                 DcmTag &tag)
{
    OFBool result = OFFalse;
    /* handle special cases where the VR can be determined by some other element values */
    if (((tag == DCM_WaveformData) || (tag == DCM_WaveformPaddingValue) ||
        (tag == DCM_ChannelMinimumValue) || (tag == DCM_ChannelMaximumValue)) &&
        (tag.getEVR() == EVR_ox))
    {
        /* case 1 (WaveformData and others): see section 8.3 in PS 3.5 */
        Uint16 bitsAlloc;
        if (item.findAndGetUint16(DCM_WaveformBitsAllocated, bitsAlloc).good())
        {
            if (bitsAlloc == 8)
            {
                DCMDATA_DEBUG("DcmItem::checkAndUpdateVR() setting undefined VR of "
                    << tag.getTagName() << " " << tag << " to 'OB' because WaveformBitsAllocated "
                    << DCM_WaveformBitsAllocated << " has a value of 8");
                tag.setVR(EVR_OB);
                result = OFTrue;
            } else {
                DCMDATA_DEBUG("DcmItem::checkAndUpdateVR() setting undefined VR of "
                    << tag.getTagName() << " " << tag << " to 'OW' because WaveformBitsAllocated "
                    << DCM_WaveformBitsAllocated << " has a value that is different from 8");
                tag.setVR(EVR_OW);
                result = OFTrue;
            }
        }
    }
    else if (((tag == DCM_PixelPaddingValue) || (tag == DCM_PixelPaddingRangeLimit) ||
        (tag == DCM_HistogramFirstBinValue) || (tag == DCM_HistogramLastBinValue) ||
        (tag == DCM_ZeroVelocityPixelValue) || (tag == DCM_SmallestImagePixelValue) ||
        (tag == DCM_LargestImagePixelValue) || (tag == DCM_SmallestPixelValueInSeries) ||
        (tag == DCM_LargestPixelValueInSeries) || (tag == DCM_LUTDescriptor) ||
        (tag == DCM_RealWorldValueLastValueMapped) || (tag == DCM_RealWorldValueFirstValueMapped)) &&
        (tag.getEVR() == EVR_xs))
    {
        /* case 2 (PixelPaddingValue and others): see section C.7.5.1, C.7.6.16.x and C.11.5 in PS 3.3 */
        Uint16 pixelRep;
        if (item.findAndGetUint16(DCM_PixelRepresentation, pixelRep).good())
        {
            if (pixelRep == 0x0001)
            {
                DCMDATA_DEBUG("DcmItem::checkAndUpdateVR() setting undefined VR of " << tag.getTagName()
                    << " " << tag << " to 'SS' because PixelRepresentation "
                    << DCM_PixelRepresentation << " has a value of 1");
                tag.setVR(EVR_SS);
                result = OFTrue;
            } else {
                DCMDATA_DEBUG("DcmItem::checkAndUpdateVR() setting undefined VR of " << tag.getTagName()
                    << " " << tag << " to 'US' because PixelRepresentation "
                    << DCM_PixelRepresentation << " has a value that is different from 1");
                tag.setVR(EVR_US);
                result = OFTrue;
            }
        }
    }
    else if (((tag.getBaseTag() == DCM_OverlayData) && (tag.getEVR() == EVR_ox)) ||
        ((tag == DCM_PixelData) && (tag.getEVR() == EVR_px)))
    {
        /* case 3 (OverlayData and PixelData): see section 8.1.2 and 8.2 in PS 3.5 */
        DCMDATA_DEBUG("DcmItem::checkAndUpdateVR() setting undefined VR of "
            << tag.getTagName() << " " << tag << " to 'OW'");
        tag.setVR(EVR_OW);
        result = OFTrue;
    }
    else if ((tag.getBaseTag() == DCM_RETIRED_CurveData) && (tag.getEVR() == EVR_ox))
    {
        /* case 4 (CurveData): see section A.1 in PS 3.5-2004 */
        DCMDATA_DEBUG("DcmItem::checkAndUpdateVR() setting undefined VR of "
            << tag.getTagName() << " " << tag << " to 'OB'");
        tag.setVR(EVR_OB);
        result = OFTrue;
    }
    /* currently unhandled:
     * - LUTData (0028,3006), US or OW
     * - MappedPixelValue (0022,1452), US or SS
     * - RedPaletteColorLookupTableDescriptor (0028,1101), US or SS
     * - GreenPaletteColorLookupTableDescriptor (0028,1102), US or SS
     * - BluePaletteColorLookupTableDescriptor (0028,1103), US or SS
     * and some retired DICOM attributes as well as some DICONDE attributes
     */
    return result;
}


// ********************************


DcmEVR DcmItem::ident() const
{
    return EVR_item;
}


unsigned long DcmItem::getVM()
{
    return 1;
}


unsigned long DcmItem::getNumberOfValues()
{
    return elementList->card();
}


unsigned long DcmItem::card() const
{
    return elementList->card();
}


// ********************************


void DcmItem::print(STD_NAMESPACE ostream &out,
                    const size_t flags,
                    const int level,
                    const char *pixelFileName,
                    size_t *pixelCounter)
{
    if (flags & DCMTypes::PF_showTreeStructure)
    {
        /* print item line with empty text */
        printInfoLine(out, flags, level);
        /* print item content */
        if (!elementList->empty())
        {
            DcmObject *dO;
            elementList->seek(ELP_first);
            do {
                dO = elementList->get();
                dO->print(out, flags, level + 1, pixelFileName, pixelCounter);
            } while (elementList->seek(ELP_next));
        }
    } else {
        /* print item start line */
        OFOStringStream oss;
        oss << "(Item with ";
        if (getLengthField() == DCM_UndefinedLength)
            oss << "undefined";
        else
            oss << "explicit";
        oss << " length #=" << card() << ")" << OFStringStream_ends;
        OFSTRINGSTREAM_GETSTR(oss, tmpString)
        printInfoLine(out, flags, level, tmpString);
        OFSTRINGSTREAM_FREESTR(tmpString)
        /* print item content */
        if (!elementList->empty())
        {
            DcmObject *dO;
            elementList->seek(ELP_first);
            do {
                dO = elementList->get();
                dO->print(out, flags, level + 1, pixelFileName, pixelCounter);
            } while (elementList->seek(ELP_next));
        }
        /* print item end line */
        DcmTag delimItemTag(DCM_ItemDelimitationItemTag);
        if (getLengthField() == DCM_UndefinedLength)
            printInfoLine(out, flags, level, "(ItemDelimitationItem)", &delimItemTag);
        else
            printInfoLine(out, flags, level, "(ItemDelimitationItem for re-encoding)", &delimItemTag);
    }
}


// ********************************


OFCondition DcmItem::writeXML(STD_NAMESPACE ostream &out,
                              const size_t flags)
{
    OFCondition l_error = EC_Normal;
    if (!(flags & DCMTypes::XF_useNativeModel))
    {
        /* XML start tag for "item" */
        out << "<item";
        /* cardinality (number of attributes) = 1..n */
        out << " card=\"" << card() << "\"";
        /* value length in bytes = 0..max (if not undefined) */
        if (getLengthField() != DCM_UndefinedLength)
            out << " len=\"" << getLengthField() << "\"";
        out << ">" << OFendl;
    }
    /* write item content */
    if (!elementList->empty())
    {
        /* write content of all children */
        DcmObject *dO;
        elementList->seek(ELP_first);
        do {
            dO = elementList->get();
            l_error = dO->writeXML(out, flags);
        } while (l_error.good() && elementList->seek(ELP_next));
    }
    if (l_error.good())
    {
        if (!(flags & DCMTypes::XF_useNativeModel))
        {
            /* XML end tag for "item" */
            out << "</item>" << OFendl;
        }
    }
    return l_error;
}


// ********************************

OFCondition DcmItem::writeJson(STD_NAMESPACE ostream &out,
                               DcmJsonFormat &format)
{
    return writeJsonExt(out, format, OFTrue, OFFalse);
}


OFCondition DcmItem::writeJsonExt(STD_NAMESPACE ostream &out,
                               DcmJsonFormat &format,
                                OFBool printBraces,
                                OFBool printNewline)
{
    size_t num_printed = 0;
    OFBool first = OFTrue;
    DcmObject *elem = NULL;
    OFCondition status = EC_Normal;

    if (!elementList->empty())
    {
        // iterate through all elements in this item
        elementList->seek(ELP_first);
        do
        {
            // get next item
            elem = elementList->get();

            // check if this is a group length, and if so, ignore
            if (elem->getTag().getElement() != 0)
            {
              // if this is the first element to be printed, print opening braces if needed
              if (first && printBraces) out << "{" << format.newline();

              // if this is not the first element to be printed, start with a comma
              if (!first) out << "," << format.newline();

              // print element
              status = elem->writeJson(out, format);
              first = OFFalse;
              num_printed++;
            }
        }
        while (status.good() && elementList->seek(ELP_next));

        // print closing braces if and only if there were opening braces
        if (num_printed > 0 && printBraces)
        {
            out << format.newline() << format.indent() << "}";
            if (printNewline) out << format.newline();
        }
    }

    // if no element was printed (item empty or only group list elements)
    if (num_printed == 0)
    {
        if (printBraces)
        {
            // print empty braces if requested
            out << "{}";
            if (printNewline) out << format.newline();
        }
    }

    return status;

}


// ********************************


OFBool DcmItem::canWriteXfer(const E_TransferSyntax newXfer,
                             const E_TransferSyntax oldXfer)
{
    OFBool canWrite = OFTrue;
    if (newXfer == EXS_Unknown)
        canWrite = OFFalse;
    else if (!elementList->empty())
    {
        DcmObject *dO;
        elementList->seek(ELP_first);
        do {
            dO = elementList->get();
            canWrite = dO->canWriteXfer(newXfer, oldXfer);
        } while (elementList->seek(ELP_next) && canWrite);
    }
    return canWrite;
}


// ********************************


Uint32 DcmItem::calcElementLength(const E_TransferSyntax xfer,
                                  const E_EncodingType enctype)
{
    Uint32 itemlen = 0;
    DcmXfer xferSyn(xfer);
    /* Length of item's start header */
    const Uint32 headersize = xferSyn.sizeofTagHeader(getVR());
    /* Length of item's content, i.e. contained elements */
    itemlen = getLength(xfer, enctype);
    /* Since the item's total length can exceed the maximum length of 32 bit, it is
     * always necessary to check for overflows. The approach taken is not elegant
     * but should work...
     */
    if ( (itemlen == DCM_UndefinedLength) || OFStandard::check32BitAddOverflow(itemlen, headersize) )
      return DCM_UndefinedLength;
    itemlen += headersize;
    if (enctype == EET_UndefinedLength) // add bytes for closing item tag marker if necessary
    {
      if (OFStandard::check32BitAddOverflow(itemlen, 8))
        return DCM_UndefinedLength;
      else
        itemlen += 8;
    }
    return itemlen;
}


// ********************************


Uint32 DcmItem::getLength(const E_TransferSyntax xfer,
                          const E_EncodingType enctype)
{
    Uint32 itemlen = 0;
    Uint32 sublen = 0;
    if (!elementList->empty())
    {
        DcmObject *dO;
        elementList->seek(ELP_first);
        do {
            dO = elementList->get();
            sublen = dO->calcElementLength(xfer, enctype);
            /* explicit length: be sure that total size of contained elements fits into item's
               32 Bit length field. If not, switch encoding automatically to undefined
               length for this item. Nevertheless, any contained elements will be
               written with explicit length if possible.
             */
            if ( (enctype == EET_ExplicitLength) && OFStandard::check32BitAddOverflow(sublen, itemlen) )
            {
                if (dcmWriteOversizedSeqsAndItemsUndefined.get())
                {
                    DCMDATA_WARN("DcmItem: Explicit length of item exceeds 32-Bit length field, "
                        << "trying to encode with undefined length");
                }
                else
                {
                    DCMDATA_WARN("DcmItem: Explicit length of item exceeds 32-Bit length field, "
                        << "aborting write");
                    errorFlag = EC_SeqOrItemContentOverflow;
                }
                return DCM_UndefinedLength;
            }
            else
              itemlen += sublen;
        } while (elementList->seek(ELP_next));
    }
    return itemlen;
}


// ********************************


OFCondition DcmItem::computeGroupLengthAndPadding(const E_GrpLenEncoding glenc,
                                                  const E_PaddingEncoding padenc,
                                                  const E_TransferSyntax xfer,
                                                  const E_EncodingType enctype,
                                                  const Uint32 padlen,
                                                  const Uint32 subPadlen,
                                                  Uint32 instanceLength)
{
    /* if certain conditions are met, this is considered to be an illegal call. */
    if ((padenc == EPD_withPadding && (padlen % 2 || subPadlen % 2)) ||
        ((glenc == EGL_recalcGL || glenc == EGL_withGL ||
          padenc == EPD_withPadding) && xfer == EXS_Unknown))
        return EC_IllegalCall;

    /* if the caller specified that group length tags and padding */
    /* tags are not supposed to be changed, there is nothing to do. */
    if (glenc == EGL_noChange && padenc == EPD_noChange)
        return EC_Normal;

    /* if we get to this point, we need to do something. First of all, set the error indicator to normal. */
    OFCondition l_error = EC_Normal;
    /* collects group length elements that cannot be calculated due to length field overflows */
    OFList<DcmObject*> exceededGroupLengthElems;

    /* if there are elements in this item... */
    if (!elementList->empty())
    {
        /* initialize some variables */
        DcmObject *dO;
        OFBool beginning = OFTrue;
        Uint16 lastGrp = 0x0000;
        Uint16 actGrp;
        DcmUnsignedLong * actGLElem = NULL;
        DcmUnsignedLong * paddingGL = NULL;
        Uint32 grplen = 0;
        DcmXfer xferSyn(xfer);
        Uint32 sublen = 0;
        OFBool groupLengthExceeded = OFFalse;

        /* determine the current seek mode and set the list pointer to the first element */
        E_ListPos seekmode = ELP_next;
        elementList->seek(ELP_first);

        /* start a loop: we want to go through all elements as long as everything is okay */
        do
        {
            /* set the seek mode to "next" again, in case it has been modified in the last iteration */
            seekmode = ELP_next;

            /* get the current element and assign it to a local variable */
            dO = elementList->get();

            /* if the current element is a sequence, compute group length and padding for the sub sequence */
            if (dO->getVR() == EVR_SQ)
            {
                // add size of sequence header
                Uint32 templen = instanceLength + xferSyn.sizeofTagHeader(EVR_SQ);
                // call computeGroupLengthAndPadding for all contained items
                l_error = OFstatic_cast(DcmSequenceOfItems *, dO)->computeGroupLengthAndPadding
                    (glenc, padenc, xfer, enctype, subPadlen, subPadlen, templen);
            }

            /* if everything is ok so far */
            if (l_error.good())
            {
                /* in case one of the following two conditions is met */
                /*  (i) the caller specified that we want to add or remove group length elements and the current */
                /*      element's tag shows that it is a group length element (tag's element number equals 0x0000) */
                /*  (ii) the caller specified that we want to add or remove padding elements and the current */
                /*      element's tag shows that it is a padding element (tag is (0xfffc,0xfffc) */
                /* then we want to delete the current (group length or padding) element */
                if (((glenc ==  EGL_withGL || glenc == EGL_withoutGL) && dO->getETag() == 0x0000) ||
                    (padenc != EPD_noChange && dO->getTag() == DCM_DataSetTrailingPadding))
                {
                    delete elementList->remove();
                    seekmode = ELP_atpos; // remove advances 1 element forward -> make next seek() work
                    dO = NULL;
                }
                /* if the above mentioned conditions are not met but the caller specified that we want to add group */
                /* length tags for every group or that we want to recalculate values for existing group length tags */
                else  if (glenc == EGL_withGL || glenc == EGL_recalcGL)
                {
                    /* we need to determine the current element's group number */
                    actGrp = dO->getGTag();

                    /* and if the group number is different from the last remembered group number or */
                    /* if this id the very first element that is treated then we've found a new group */
                    if (actGrp != lastGrp || beginning) // new Group found
                    {
                        /* set beginning to false in order to specify that the */
                        /* very first element has already been treated */
                        beginning = OFFalse;

                        /* if the current element is a group length element and its data type */
                        /* is not UL replace this element with one that has a UL data type since */
                        /* group length elements are supposed to have this data type */
                        if (dO->getETag() == 0x0000 && dO->ident() != EVR_UL)
                        {
                            delete elementList->remove();
                            DcmTag tagUL(actGrp, 0x0000, EVR_UL);
                            DcmUnsignedLong *dUL = new DcmUnsignedLong(tagUL);
                            elementList->insert(dUL, ELP_prev);
                            dO = dUL;
                            // remember the parent
                            dO->setParent(this);
                            DCMDATA_WARN("DcmItem: Group Length with VR other than UL found, corrected");
                        }
                        /* if the above mentioned condition is not met but the caller specified */
                        /* that we want to add group length elements, we need to add such an element */
                        else if (glenc == EGL_withGL)
                        {
                            // Create GroupLength element
                            DcmTag tagUL(actGrp, 0x0000, EVR_UL);
                            DcmUnsignedLong *dUL = new DcmUnsignedLong(tagUL);
                            // insert new GroupLength element
                            elementList->insert(dUL, ELP_prev);
                            dO = dUL;
                            // remember the parent
                            dO->setParent(this);
                        }

                        /* in case we want to add padding elements and the current element is a */
                        /* padding element we want to remember the padding element so that the */
                        /* group length of this element can be stored later */
                        if (padenc == EPD_withPadding && actGrp == 0xfffc)
                            paddingGL = OFstatic_cast(DcmUnsignedLong *, dO);

                        /* if actGLElem contains a valid pointer it was set in one of the last iterations */
                        /* to the group length element of the last group. We need to write the current computed */
                        /* group length value to this element. Exception: If group length exceeds maximum possible */
                        /* value, than remove group length element instead of setting it */
                        if (actGLElem != NULL)
                        {
                            if (!groupLengthExceeded)
                            {
                                // do not use putUint32() in order to make sure that the resulting VM is really 1
                                actGLElem->putUint32Array(&grplen, 1);
                                DCMDATA_DEBUG("DcmItem::computeGroupLengthAndPadding() Length of Group 0x"
                                    << STD_NAMESPACE hex << STD_NAMESPACE setfill('0')
                                    << STD_NAMESPACE setw(4) << actGLElem->getGTag()
                                    << STD_NAMESPACE dec << STD_NAMESPACE setfill(' ')
                                    << " len=" << grplen);
                            }
                            else
                            {
                                DCMDATA_WARN("DcmItem: Group length of group 0x"
                                    << STD_NAMESPACE hex << STD_NAMESPACE setfill('0')
                                    << STD_NAMESPACE setw(4) << actGLElem->getGTag()
                                    << " exceeds 32-Bit length field. "
                                    << "Cannot calculate/write group length for this group.");
                                exceededGroupLengthElems.push_back(actGLElem);
                                groupLengthExceeded = OFFalse;
                            }
                        }

                        /* set the group length value to 0 since it is the beginning of the new group */
                        grplen = 0;

                        /* if the current element is a group length element, remember its address for later */
                        /* (we need to assign the group length value to this element in a subsequent iteration) */
                        /* in case the current element (at the beginning of the group) is not a group length */
                        /* element, set the actGLElem pointer to NULL. */
                        if (dO->getETag() == 0x0000)
                            actGLElem = OFstatic_cast(DcmUnsignedLong *, dO);
                        else
                            actGLElem = NULL;
                    }
                    /* if this is not a new group, calculate the element's length and add it */
                    /* to the currently computed group length value. If group length is larger */
                    /* than group length field permits, set flag to not add group length for this group */
                    else
                    {
                        sublen = dO->calcElementLength(xfer, enctype);
                        // test for 32-bit overflow return value
                        if ((sublen == DCM_UndefinedLength) || OFStandard::check32BitAddOverflow(sublen, grplen))
                        {
                            groupLengthExceeded = OFTrue;
                        }
                        else
                        {
                          grplen += sublen;
                        }
                    }

                    /* remember the current element's group number so that it is possible to */
                    /* figure out if a new group is treated in the following iteration */
                    lastGrp = actGrp;
                }
            }
        } while (l_error.good() && elementList->seek(seekmode));

        /* if there was no error and the caller specified that we want to add or recalculate */
        /* group length tags and if actGLElem has a valid value, we need to add the above */
        /* computed group length value to the last group's group length element. Exception: */
        /* If group length exceeds maximum possible value, remove group length element and */
        /* i.e. do not write it for this group. */
        if (l_error.good() && (glenc == EGL_withGL || glenc == EGL_recalcGL) && actGLElem)
        {
          if (groupLengthExceeded)
          {
            exceededGroupLengthElems.push_back(actGLElem);
          }
          else
          {
            actGLElem->putUint32(grplen);
          }
        }

        /* if the caller specified that we want to add padding elements and */
        /* if the length up to which shall be padded does not equal 0 we might */
        /* have to add a padding element */
        if (padenc == EPD_withPadding && padlen)
        {
            /* calculate how much space the entire padding element is supposed to occupy */
            Uint32 padding;
            if (ident() == EVR_dataset)
            {
                instanceLength += calcElementLength(xfer, enctype);
                padding = padlen - (instanceLength % padlen);
            } else
                padding = padlen - (getLength(xfer, enctype) % padlen);

            /* if now padding does not equal padlen we need to create a padding element. (if both values are equal */
            /* the element does have the exact required padlen length and does not need a padding element.) */
            if (padding != padlen)
            {
                /* Create new padding element */
                DcmOtherByteOtherWord * paddingEl = new DcmOtherByteOtherWord(DCM_DataSetTrailingPadding);

                /* calculate the length of the new element */
                Uint32 tmplen = paddingEl->calcElementLength(xfer, enctype);

                /* in case padding is smaller than the header of the padding element, we */
                /* need to increase padding (the value which specifies how much space the */
                /* entire padding element is supposed to occupy) until it is no longer smaller */
                while (tmplen > padding)
                    padding += padlen;

                /* determine the amount of bytes that have to be added to the */
                /* padding element so that it has the correct size */
                padding -= tmplen;

                /* create an array of a corresponding size and set the array fields */
                Uint8 * padBytes = new Uint8[padding];
                memset(padBytes, 0, size_t(padding));

                /* set information in the above created padding element (size and actual value) */
                paddingEl->putUint8Array(padBytes, padding);

                /* delete the above created array */
                delete[] padBytes;

                /* insert the padding element into this */
                insert(paddingEl);

                /* finally we need to update the group length for the padding element if it exists */
                if (paddingGL)
                {
                    Uint32 len;
                    paddingGL->getUint32(len);
                    len += paddingEl->calcElementLength(xfer, enctype);
                    paddingGL->putUint32(len);
                }
            }
        }
    }
    /* delete invalid group length elements from item. Cannot be done in */
    /* above while loop because then elementList iterator is invalidated */
    const size_t numElems = exceededGroupLengthElems.size();
    for (size_t i = 0; i < numElems; i++)
    {
        delete remove(exceededGroupLengthElems.front());
        exceededGroupLengthElems.pop_front();
    }

    return l_error;
}


// ********************************


OFCondition DcmItem::readTagAndLength(DcmInputStream &inStream,
                                      const E_TransferSyntax xfer,
                                      DcmTag &tag,
                                      Uint32 &length,
                                      Uint32 &bytesRead)
{
    OFCondition l_error = EC_Normal;
    Uint32 valueLength = 0;
    Uint16 groupTag = 0xffff;
    Uint16 elementTag = 0xffff;

    /* create a DcmXfer object based on the transfer syntax which was passed */
    DcmXfer xferSyn(xfer);

#ifdef DEBUG
    /* dump some information if required */
    DCMDATA_TRACE("DcmItem::readTagAndLength() TransferSyntax=\"" << xferSyn.getXferName() << "\"");
#endif

    /* bail out if at end of stream */
    if (inStream.eos())
        return EC_EndOfStream;

    /* check if either 4 (for implicit transfer syntaxes) or 6 (for explicit transfer */
    /* syntaxes) bytes are available in (i.e. can be read from) inStream. if an error */
    /* occurred while performing this check return this error */
    if (inStream.avail() < OFstatic_cast(offile_off_t, xferSyn.isExplicitVR() ? 6 : 4))
        return EC_StreamNotifyClient;

    /* determine the byte ordering of the transfer syntax which was passed; */
    /* if the byte ordering is unknown, this is an illegal call. */
    const E_ByteOrder byteOrder = xferSyn.getByteOrder();
    if (byteOrder == EBO_unknown)
        return EC_IllegalCall;

    /* read tag information (4 bytes) from inStream and create a corresponding DcmTag object */
    inStream.mark();
    inStream.read(&groupTag, 2);
    inStream.read(&elementTag, 2);
    swapIfNecessary(gLocalByteOrder, byteOrder, &groupTag, 2, 2);
    swapIfNecessary(gLocalByteOrder, byteOrder, &elementTag, 2, 2);
    // tag has been read
    bytesRead = 4;
    DcmTag newTag(groupTag, elementTag);
    DcmEVR newEVR = newTag.getEVR();
    // check whether tag is private
    OFBool isPrivate = groupTag & 1;

    /* if the transfer syntax which was passed is an explicit VR syntax and if the current */
    /* item is not a delimitation item (note that delimitation items do not have a VR), go */
    /* ahead and read 2 bytes from inStream. These 2 bytes contain this item's VR value. */
    if (xferSyn.isExplicitVR() && (newEVR != EVR_na))
    {
        char vrstr[3];
        vrstr[2] = '\0';

        /* read 2 bytes */
        inStream.read(vrstr, 2);

        /* create a corresponding DcmVR object */
        DcmVR vr(vrstr);

        /* if the VR which was read is not a standard VR (e.g. invalid), print a warning */
        if (!vr.isStandard())
        {
            OFOStringStream oss;
            oss << "DcmItem: " << (vr.isInvalid() ? "Invalid" : "Non-standard") << " VR '"
                << ((OFstatic_cast(unsigned char, vrstr[0]) < 32) ? ' ' : vrstr[0])
                << ((OFstatic_cast(unsigned char, vrstr[1]) < 32) ? ' ' : vrstr[1]) << "' ("
                << STD_NAMESPACE hex << STD_NAMESPACE setfill('0')
                << STD_NAMESPACE setw(2) << OFstatic_cast(unsigned int, vrstr[0] & 0xff) << "\\"
                << STD_NAMESPACE setw(2) << OFstatic_cast(unsigned int, vrstr[1] & 0xff)
                << ") encountered while parsing element " << newTag << OFStringStream_ends;
            OFSTRINGSTREAM_GETSTR(oss, tmpString)
            /* encoding of this data element might be wrong, try to correct it */
            if (dcmAcceptUnexpectedImplicitEncoding.get())
            {
                DCMDATA_WARN(tmpString << ", trying again with Implicit VR Little Endian");
                /* put back read bytes to input stream ... */
                inStream.putback();
                bytesRead = 0;
                /* ... and retry with Implicit VR Little Endian transfer syntax */
                return readTagAndLength(inStream, EXS_LittleEndianImplicit, tag, length, bytesRead);
            } else {
                DCMDATA_WARN(tmpString << ", assuming " << (vr.usesExtendedLengthEncoding() ? "4" : "2")
                    << " byte length field");
            }
            OFSTRINGSTREAM_FREESTR(tmpString)

            /* workaround: handle known issue with non-standard VR "OX" for PixelData element */
            if ((newTag == DCM_PixelData) && (strncmp(vrstr, "OX", 2) == 0))
            {
                DCMDATA_WARN("DcmItem: Non-standard VR 'OX' is known to be wrongly used for PixelData " << newTag
                    << ", setting VR to 'OW'");
                vr.setVR(EVR_OW);
            }
        }

        /* the VR in the dataset might be wrong, so the user can decide to ignore it */
        if (dcmPreferVRFromDataDictionary.get() && (newEVR != EVR_UNKNOWN) && (newEVR != EVR_UNKNOWN2B))
        {
            /* resolve ambiguous VRs, e.g. map the internal "ox" to either "OB" or "OW" */
            if (checkAndUpdateVR(*this, newTag))
                newEVR = newTag.getEVR();

            if (newEVR != vr.getEVR())
            {
                /* ignore explicit VR in dataset if tag is defined in data dictionary */
                DCMDATA_DEBUG("DcmItem::readTagAndLength() ignoring explicit VR in data set ("
                    << vr.getVRName() << ") for element " << newTag
                    << ", using the one from data dictionary (" << newTag.getVRName() << ")");
            }
        } else {
            /* set the VR which was read in the above created tag object */
            newTag.setVR(vr);
        }

        if (!dcmPreferLengthFieldSizeFromDataDictionary.get() || newEVR == EVR_UNKNOWN || newEVR == EVR_UNKNOWN2B) {
            /* determine VR read from dataset, because this VR specifies the number of bytes for the length-field */
            newEVR = vr.getEVR();
        } else {
            /* use the VR from the dictionary for deciding the length of the length field */
        }

        /* increase counter by 2 */
        bytesRead += 2;
    }

    /* special handling for private elements */
    if (isPrivate && (newTag.getElement() >= 0x1000))
    {
        const char *pc = privateCreatorCache.findPrivateCreator(newTag);
        if (pc)
        {
            // we have a private creator for this element
            newTag.setPrivateCreator(pc);

            if (xferSyn.isImplicitVR())
            {
                // try to update VR from dictionary now that private creator is known
                newTag.lookupVRinDictionary();
                // also update the VR
                newEVR = newTag.getEVR();
            }
        }
    }

    /* the next thing we want to do is read the value in the length field from inStream. */
    /* determine if there is a corresponding amount of bytes (for the length field) still */
    /* available in inStream. If not, return an error. */
    if (inStream.avail() < OFstatic_cast(offile_off_t, xferSyn.sizeofTagHeader(newEVR) - bytesRead))
    {
        inStream.putback();    // the UnsetPutbackMark is in readSubElement
        bytesRead = 0;
        l_error = EC_StreamNotifyClient;
        return l_error;
    }

    /* read the value in the length field. In some cases, it is 4 bytes wide, in other */
    /* cases only 2 bytes (see DICOM standard part 5, section 7.1.1) */
    if (xferSyn.isImplicitVR() || newEVR == EVR_na) // note that delimitation items don't have a VR
    {
        inStream.read(&valueLength, 4);            // length field is 4 bytes wide
        swapIfNecessary(gLocalByteOrder, byteOrder, &valueLength, 4, 4);
        bytesRead += 4;
    } else {                                       // the transfer syntax is explicit VR
        DcmVR vr(newEVR);
        if (vr.usesExtendedLengthEncoding())
        {
            Uint16 reserved;
            inStream.read(&reserved, 2);           // 2 reserved bytes
            inStream.read(&valueLength, 4);        // length field is 4 bytes wide
            swapIfNecessary(gLocalByteOrder, byteOrder, &valueLength, 4, 4);
            bytesRead += 6;
        } else {
            Uint16 tmpValueLength;
            inStream.read(&tmpValueLength, 2);     // length field is 2 bytes wide
            swapIfNecessary(gLocalByteOrder, byteOrder, &tmpValueLength, 2, 2);
            bytesRead += 2;
            valueLength = tmpValueLength;
        }
        /* check whether value in length field is appropriate for this VR */
        const size_t vrSize = vr.getValueWidth();
        if ((vrSize > 1) && (valueLength % vrSize != 0))
        {
            /* warning is only reported for standard, fixed-size VRs that require more than 1 byte per value */
            DCMDATA_WARN("DcmItem: Length of element " << newTag << " is not a multiple of " << vrSize << " (VR=" << vr.getVRName() << ")");
        }
    }
    /* if the value in the length field is odd, print an error message */
    if ((valueLength & 1) && (valueLength != DCM_UndefinedLength))
    {
        DCMDATA_WARN("DcmItem: Length of element " << newTag << " is odd");
    }

    /* if desired, handle private attributes with maximum length as VR SQ */
    if (isPrivate && dcmReadImplPrivAttribMaxLengthAsSQ.get() && (valueLength == DCM_UndefinedLength))
    {
        /* re-set tag to be a sequence and also delete private creator cache */
        newTag.setVR(EVR_SQ);
        newTag.setPrivateCreator("");
    }

    /* if desired, check if length is greater than length of surrounding item */
    const Uint32 valueLengthItem = getLengthField();
    if ((ident() == EVR_item /* e.g. meta info would have length 0 */) &&
        (valueLengthItem != DCM_UndefinedLength /* this does not work in undefined length items */) &&
        (valueLength != DCM_UndefinedLength) /* Also, do not check sequences with undefined length 0xFFFFFFFF */
       )
    {
        const offile_off_t remainingItemBytes = valueLengthItem - (inStream.tell() - fStartPosition);
        /* is the explicit item length too small to cover the full value of the element value length to be read? */
        if (remainingItemBytes < 0)
        {
            DCMDATA_WARN("DcmItem: Explicit item length (" << valueLengthItem << " bytes) too large for the elements contained in the item");
            /* if the next tag is the sequence delimiter item, we can adapt to the situation */
            if (newTag == DCM_SequenceDelimitationItem)
            {
                DCMDATA_WARN("DcmItem: Sequence delimitation occurred before all bytes announced by explicit item length could be read");
                l_error = EC_PrematureSequDelimitationItem;
                /* rewind to start of sequence delimiter which is read in a regular way */
                /* by DcmSequenceOfItems later (if error is ignored in DcmItem::read()) */
                inStream.putback();
            }
        }
        else if (OFstatic_cast(offile_off_t, valueLength) > remainingItemBytes)
        {
            DCMDATA_WARN("DcmItem: Element " << newTag.getTagName() << " " << newTag
                << " larger (" << valueLength << ") than remaining bytes ("
                /* need to cast remainingItemBytes to unsigned long because VC6 cannot print offile_off_t (int64_t). */
                << OFstatic_cast(unsigned long, remainingItemBytes) << ") of surrounding item");
            l_error = EC_ElemLengthLargerThanItem;
        }
    }

    /* assign values to out parameter */
    length = valueLength;
    tag = newTag;

    /* return return value */
    return l_error;
}


// ********************************


OFCondition DcmItem::readSubElement(DcmInputStream &inStream,
                                    DcmTag &newTag,
                                    const Uint32 newLength,
                                    const E_TransferSyntax xfer,
                                    const E_GrpLenEncoding glenc,
                                    const Uint32 maxReadLength)
{
    DcmElement *subElem = NULL;

    /* create a new DcmElement* object with corresponding tag and */
    /* length; the object will be accessible through subElem */
    OFBool readAsUN = OFFalse;
    OFCondition l_error = DcmItem::newDicomElement(subElem, newTag, newLength, &privateCreatorCache, readAsUN);

    /* if no error occurred and subElem does not equal NULL, go ahead */
    if (l_error.good() && subElem != NULL)
    {
        // inStream.UnsetPutbackMark(); // not needed anymore with new stream architecture

        /* insert the new element into the (sorted) element list and */
        /* assign information which was read from the inStream to it */
        subElem->transferInit();
        /* we need to read the content of the attribute, no matter if */
        /* inserting the attribute succeeds or fails */
        l_error = subElem->read(inStream, (readAsUN ? EXS_LittleEndianImplicit : xfer), glenc, maxReadLength);
        // try to insert element into item. Note that
        // "elementList->insert(subElem, ELP_next)" would be faster,
        // but this is better since this insert-function creates a
        // sorted element list.
        // We insert the element even if subElem->read() reported an error
        // because otherwise I/O suspension would fail.
        OFCondition temp_error = insert(subElem, OFFalse, OFTrue);

        if (temp_error.bad())
        {
            // produce diagnostics
            DCMDATA_WARN("DcmItem: Element " << newTag
                << " found twice in one data set or item, ignoring second entry");
            delete subElem;
        }
    }
    /* else if an error occurred, try to recover from this error */
    else if (l_error == EC_InvalidTag)
    {
        /* This is the second putback operation on the putback mark in */
        /* readTagAndLength but it is impossible that both can be executed */
        /* without setting the Mark twice. */
        inStream.putback();
        DCMDATA_WARN("DcmItem: Parse error while parsing element " << newTag);
    }
    else if (l_error == EC_UndefinedLengthOBOW)
    {
        // do nothing
    }
    else if (l_error == EC_VOI_LUT_OBOW)
    {
        // do nothing
    }
    else if (l_error != EC_ItemEnd)
    {
        // inStream.UnsetPutbackMark(); // not needed anymore with new stream architecture

        // dump some information if required
        if (dcmIgnoreParsingErrors.get() || (dcmReplaceWrongDelimitationItem.get() && (l_error == EC_SequEnd)))
        {
            DCMDATA_WARN("DcmItem: Parse error in sequence item, found " << newTag
                << " instead of item delimiter " << DCM_ItemDelimitationItem);
        } else {
            DCMDATA_ERROR("DcmItem: Parse error in sequence item, found " << newTag
                << " instead of item delimiter " << DCM_ItemDelimitationItem);
        }
        // some systems use the wrong delimitation item at the end of a sequence
        if (dcmReplaceWrongDelimitationItem.get() && (l_error == EC_SequEnd))
        {
            DCMDATA_DEBUG("DcmItem::readSubItem() replacing wrong sequence delimiter "
                << DCM_SequenceDelimitationItem << " by item delimiter "
                << DCM_ItemDelimitationItem << " because it is expected here");
            l_error = EC_ItemEnd;
        } else {
            DCMDATA_DEBUG("DcmItem::readSubElement() cannot create Sub Element " << newTag);
            // treat this incorrect encoding as an error
            if (!dcmIgnoreParsingErrors.get())
                l_error = EC_ItemDelimitationItemMissing;
        }
    } else {
        // inStream.UnsetPutbackMark(); // not needed anymore with new stream architecture
    }

    /* dump some information if required */
    DCMDATA_TRACE("DcmItem::readSubItem() returns error = " << l_error.text());
    /* return result value */
    return l_error;
}


// ********************************


OFCondition DcmItem::read(DcmInputStream & inStream,
                          const E_TransferSyntax xfer,
                          const E_GrpLenEncoding glenc,
                          const Uint32 maxReadLength)
{
    return DcmItem::readUntilTag(inStream, xfer, glenc, maxReadLength, DCM_UndefinedTagKey);
}

OFCondition DcmItem::readUntilTag(DcmInputStream & inStream,
                                  const E_TransferSyntax xfer,
                                  const E_GrpLenEncoding glenc,
                                  const Uint32 maxReadLength,
                                  const DcmTagKey &stopParsingAtElement)
{
    /* check if this is an illegal call; if so set the error flag and do nothing, else go ahead */
    if (getTransferState() == ERW_notInitialized)
    {
        errorFlag = EC_IllegalCall;
        return errorFlag;
    }

    /* figure out if the stream reported an error */
    errorFlag = inStream.status();
    /* if the stream reported an error or if it is the end of the */
    /* stream, set the error flag correspondingly; else go ahead */
    if (errorFlag.good() && inStream.eos())
        errorFlag = EC_EndOfStream;
    else if (errorFlag.good() && getTransferState() != ERW_ready)
    {
        /* if the transfer state of this item is ERW_init, get its start */
        /* position in the stream and set the transfer state to ERW_inWork */
        if (getTransferState() == ERW_init)
        {
            fStartPosition = inStream.tell();  // start position of this item
            setTransferState(ERW_inWork);
        }
        DcmTag newTag;
        OFBool readStopElem = OFFalse;
        /* start a loop in order to read all elements (attributes) which are contained in the inStream */
        while (inStream.good() && (getTransferredBytes() < getLengthField() || !lastElementComplete) && !readStopElem)
        {
            /* initialize variables */
            Uint32 newValueLength = 0;
            Uint32 bytes_tagAndLen = 0;
            /* if the reading of the last element was complete, go ahead and read the next element */
            if (lastElementComplete)
            {
                /* read this element's tag and length information */
                /* (and possibly also VR information) from the inStream */
                errorFlag = readTagAndLength(inStream, xfer, newTag, newValueLength, bytes_tagAndLen);
                /* increase counter correspondingly */
                incTransferredBytes(bytes_tagAndLen);

                /* if desired, try to ignore parse error -> skip item */
                if ((errorFlag == EC_ElemLengthLargerThanItem) && dcmIgnoreParsingErrors.get())
                {
                    DCMDATA_WARN("DcmItem: Element " << newTag.getTagName() << " " << newTag
                        << " too large, trying to skip over rest of item");
                    /* we can call getLengthField because error does only occur for explicit length items */
                    const offile_off_t bytesToSkip = getLengthField() - bytes_tagAndLen;
                    if (bytesToSkip > inStream.avail()) // no chance to recover
                       break;
                    inStream.skip(bytesToSkip);
                    errorFlag = EC_Normal;
                }
                /* if desired, accept premature sequence delimitation item and continue as if item has been completely read. */
                /* The stream position has been rewound to the start position of the sequence end */
                /* delimiter tag in order to let DcmSequenceOfItems handle the delimiter in the reading routine. */
                else if ((errorFlag == EC_PrematureSequDelimitationItem) && dcmIgnoreParsingErrors.get())
                {
                     DCMDATA_WARN("DcmItem: Sequence delimitation occurred before all bytes announced by explicit item length could be read"
                         << ", trying to continue as if item was completely read");
                    errorFlag = EC_ItemEnd;  // make sure that error code leads to normal return from item reading loop
                    break; // we are completed with the item since sequence is closed
                }
                else /* continue with normal case: parse rest of element */
                {
                    /* if there was an error while we were reading from the stream, terminate the while-loop */
                    /* (note that if the last element had been read from the inStream in the last iteration, */
                    /* another iteration will be started, and of course then readTagAndLength(...) above will */
                    /* return that it encountered the end of the stream. It is only then (and here) when the */
                    /* while loop will be terminated.) */
                    if (errorFlag.bad())
                        break;
                    /* If we get to this point, we just started reading the first part */
                    /* of an element; hence, lastElementComplete is not longer true */
                    lastElementComplete = OFFalse;
                    /* in case of implicit VR, check whether the "default VR" is really appropriate */
                    if (DcmXfer(xfer).isImplicitVR())
                        checkAndUpdateVR(*this, newTag);

                    /* check if we want to stop parsing at this point, in the main dataset only */
                    if ((stopParsingAtElement != DCM_UndefinedTagKey) && (newTag >= stopParsingAtElement) && (ident() == EVR_dataset))
                    {
                        lastElementComplete = OFTrue;
                        readStopElem = OFTrue;
                        DCMDATA_DEBUG("DcmItem: Element " << newTag.getTagName() << " " << newTag
                            << " encountered, skipping rest of dataset (as requested)");
                    }
                    else
                    {
                        /* read the actual data value which belongs to this element */
                        /* (attribute) and insert this information into the elementList */
                        errorFlag = readSubElement(inStream, newTag, newValueLength, xfer, glenc, maxReadLength);
                        /* if reading was successful, we read the entire data value information */
                        /* for this element; hence lastElementComplete is true again */
                        if (errorFlag.good())
                            lastElementComplete = OFTrue;

                        /* in data or command sets, group 0x0001 to 0x0003, 0x0005, 0x0007 and 0xFFFF are not allowed. */
                        /* (we cannot check for group 0x0000 since we do not know whether we read a data or command set.)*/
                        if (!newTag.hasValidGroup() || (newTag.getGroup() == 0x0002))
                            DCMDATA_WARN("DcmItem: Invalid Element " << newTag << " found in data set");
                    }
                }
            } else {
                /* if lastElementComplete is false, we have only read the current element's */
                /* tag and length (and possibly VR) information as well as maybe some data */
                /* data value information. We need to continue reading the data value */
                /* information for this particular element. */
                DcmObject *dO = elementList->get();
                if (dO)
                    errorFlag = dO->read(inStream, xfer, glenc, maxReadLength);
                else
                    errorFlag = EC_InternalError; // should never happen

                /* if reading was successful, we read the entire information */
                /* for this element; hence lastElementComplete is true */
                if (errorFlag.good())
                    lastElementComplete = OFTrue;
            }
            /* remember how many bytes were read */
            setTransferredBytes(OFstatic_cast(Uint32, inStream.tell() - fStartPosition));
            if (errorFlag.good())
            {
                // If we completed one element, update the private tag cache.
                if (lastElementComplete)
                {
                    privateCreatorCache.updateCache(elementList->get());
                    // evaluate option for skipping rest of dataset
                    if ( (dcmStopParsingAfterElement.get() != DCM_UndefinedTagKey) &&
                         (dcmStopParsingAfterElement.get() == elementList->get()->getTag()) &&
                          ident() == EVR_dataset)
                    {
                        DCMDATA_DEBUG("DcmItem: Element " << newTag.getTagName() << " " << newTag
                            << " encountered, skipping rest of data set (as requested)");
                        readStopElem = OFTrue;
                    }
                }
            } else
                break; // if some error was encountered terminate the while-loop
        } //while

        /* determine an appropriate result value; note that if the above called read function */
        /* encountered the end of the stream before all information for this element could be */
        /* read from the stream, the errorFlag has already been set to EC_StreamNotifyClient. */
        if (errorFlag.good())
        {
          // if stop element was read or end of stream occurs, tell parser end of stream is reached
          if (readStopElem || inStream.eos())
              errorFlag = EC_EndOfStream;
          // if all bytes could be read or last element read could not be completed, set to error
          else if ((getTransferredBytes() < getLengthField() || !lastElementComplete))
              errorFlag = EC_StreamNotifyClient;
        }
    } // else errorFlag
    /* modify the result value: three kinds of special error codes do not count as an error */
    if (errorFlag == EC_ItemEnd || errorFlag == EC_EndOfStream)
        errorFlag = EC_Normal;
    else if (errorFlag == EC_SequEnd)
    {
        if (dcmIgnoreParsingErrors.get())
        {
            /* do not treat the missing delimiter as an error */
            errorFlag = EC_Normal;
        } else
            errorFlag = EC_ItemDelimitationItemMissing;
    }

    /* if at this point the error flag indicates success, the item has */
    /* been read completely; hence, set the transfer state to ERW_ready. */
    /* Note that all information for this element could be read from the */
    /* stream, the errorFlag is still set to EC_StreamNotifyClient. */
    if (errorFlag.good())
        setTransferState(ERW_ready);

    /* dump information if required */
    DCMDATA_TRACE("DcmItem::read() returns error = " << errorFlag.text());

    /* return result value */
    return errorFlag;
}


// ********************************


OFCondition DcmItem::write(DcmOutputStream &outStream,
                           const E_TransferSyntax oxfer,
                           const E_EncodingType enctype,
                           DcmWriteCache *wcache)
{
  if (getTransferState() == ERW_notInitialized)
    errorFlag = EC_IllegalCall;
  else
  {
    errorFlag = outStream.status();
    if (errorFlag.good() && getTransferState() != ERW_ready)
    {
      if (getTransferState() == ERW_init)
      {
        // Force a compression filter (if any) to process the input buffer, by calling outStream.write().
        // This ensures that we cannot get stuck if there are just a few bytes available in the buffer
        outStream.write(NULL, 0);
        if (outStream.avail() >= 8)
        {
          if (enctype == EET_ExplicitLength)
            setLengthField(getLength(oxfer, enctype));
          else
            setLengthField(DCM_UndefinedLength);
          if (errorFlag == EC_SeqOrItemContentOverflow)
            return errorFlag;
          errorFlag = writeTag(outStream, getTag(), oxfer);
          Uint32 valueLength = getLengthField();
          DcmXfer outXfer(oxfer);
          const E_ByteOrder oByteOrder = outXfer.getByteOrder();
          if (oByteOrder == EBO_unknown) return EC_IllegalCall;
          swapIfNecessary(oByteOrder, gLocalByteOrder, &valueLength, 4, 4);
          outStream.write(&valueLength, 4); // 4 bytes length
          elementList->seek(ELP_first);
          setTransferState(ERW_inWork);
        } else {
          errorFlag = EC_StreamNotifyClient;
        }
      }
      if (getTransferState() == ERW_inWork)
      {
        // elementList->get() can be NULL if buffer was full after
        // writing the last item but before writing the sequence delimitation.
        if (!elementList->empty() && (elementList->get() != NULL))
        {
          DcmObject *dO = NULL;
          do
          {
              dO = elementList->get();
              if (dO->transferState() != ERW_ready)
                errorFlag = dO->write(outStream, oxfer, enctype, wcache);
          } while (errorFlag.good() && elementList->seek(ELP_next));
        }
        if (errorFlag.good())
        {
          setTransferState(ERW_ready);
          if (getLengthField() == DCM_UndefinedLength)
          {
            // Force a compression filter (if any) to process the input buffer, by calling outStream.write().
            // This ensures that we cannot get stuck if there are just a few bytes available in the buffer
            outStream.write(NULL, 0);
            if (outStream.avail() >= 8)
            {
                // write Item delimitation
                DcmTag delim(DCM_ItemDelimitationItemTag);
                errorFlag = writeTag(outStream, delim, oxfer);
                Uint32 delimLen = 0L;
                outStream.write(&delimLen, 4); // 4 bytes length
            }
            else
            {
                // Every subelement of the item is written but it
                // is not possible to write the delimitation item into the buffer.
                errorFlag = EC_StreamNotifyClient;
                setTransferState(ERW_inWork);
            }
          }
        }
      }
    }
  }
  return errorFlag;
}


// ********************************


OFCondition DcmItem::writeSignatureFormat(DcmOutputStream &outStream,
                                          const E_TransferSyntax oxfer,
                                          const E_EncodingType enctype,
                                          DcmWriteCache *wcache)
{
  if (getTransferState() == ERW_notInitialized)
    errorFlag = EC_IllegalCall;
  else
  {
    errorFlag = outStream.status();
    if (errorFlag.good() && getTransferState() != ERW_ready)
    {
      if (getTransferState() == ERW_init)
      {
        // Force a compression filter (if any) to process the input buffer, by calling outStream.write().
        // This ensures that we cannot get stuck if there are just a few bytes available in the buffer
        outStream.write(NULL, 0);
        if (outStream.avail() >= 4)
        {
          if (enctype == EET_ExplicitLength)
            setLengthField(getLength(oxfer, enctype));
          else
            setLengthField(DCM_UndefinedLength);
          errorFlag = writeTag(outStream, getTag(), oxfer);
          /* we don't write the item length */
          elementList->seek(ELP_first);
          setTransferState(ERW_inWork);
        } else
          errorFlag = EC_StreamNotifyClient;
      }
      if (getTransferState() == ERW_inWork)
      {
        // elementList->get() can be NULL if buffer was full after
        // writing the last item but before writing the sequence delimitation.
        if (!elementList->empty() && (elementList->get() != NULL))
        {
          DcmObject *dO = NULL;
          do
          {
            dO = elementList->get();
            if (dO->isSignable() && dO->transferState() != ERW_ready)
              errorFlag = dO->writeSignatureFormat(outStream, oxfer, enctype, wcache);
          } while (errorFlag.good() && elementList->seek(ELP_next));
        }
        if (errorFlag.good())
        {
          setTransferState(ERW_ready);
          /* we don't write an item delimitation even if the item has undefined length */
        }
      }
    }
  }
  return errorFlag;
}


// ********************************


OFBool DcmItem::isNested() const
{
    OFBool nested = OFFalse;
    if (getParent() != NULL)
    {
        // check for surrounding structure of sequence of items
        const DcmEVR parentIdent = getParent()->ident();
        if ((parentIdent == EVR_SQ) || (parentIdent == EVR_pixelSQ))
            nested = OFTrue;
    }
    return nested;
}


DcmItem *DcmItem::getParentItem()
{
    DcmItem *parentItem = NULL;
    if (getParent() != NULL)
    {
        // make sure that the direct parent has the correct type
        const DcmEVR parentIdent = getParent()->ident();
        if ((parentIdent == EVR_SQ) || (parentIdent == EVR_pixelSQ))
        {
            DcmObject *parent = getParent()->getParent();
            if (parent != NULL)
            {
                // make sure that it is really a class derived from DcmItem
                switch (parent->ident())
                {
                    case EVR_metainfo:
                    case EVR_dataset:
                    case EVR_item:
                    case EVR_dirRecord:
                        parentItem = OFreinterpret_cast(DcmItem *, parent);
                        break;
                    default:
                        DCMDATA_DEBUG("DcmItem::getParentItem() Parent object has wrong class identifier: "
                            << OFstatic_cast(int, parent->ident())
                            << " (" << DcmVR(parent->ident()).getVRName() << ")");
                        break;
                }
            }
        // When our parent is a fileformat, we should be a dataset or a metainfo.
        // In these cases, there really is no parent item, so no message.
        } else if (parentIdent != EVR_fileFormat) {
            DCMDATA_DEBUG("DcmItem::getParentItem() Direct parent object is not a sequence element");
        }
    }
    return parentItem;
}


// ********************************


void DcmItem::transferInit()
{
    DcmObject::transferInit();
    fStartPosition = 0;
    lastElementComplete = OFTrue;
    privateCreatorCache.clear();
    if (!elementList->empty())
    {
        elementList->seek(ELP_first);
        do {
            elementList->get()->transferInit();
        } while (elementList->seek(ELP_next));
    }
}


void DcmItem::transferEnd()
{
    DcmObject::transferEnd();
    privateCreatorCache.clear();
    if (!elementList->empty())
    {
        elementList->seek(ELP_first);
        do {
            elementList->get()->transferEnd();
        } while (elementList->seek(ELP_next));
    }
}


// ********************************


OFCondition DcmItem::insert(DcmElement *elem,
                            OFBool replaceOld,
                            OFBool checkInsertOrder)
{
    /* initialize error flag with ok */
    errorFlag = EC_Normal;
    /* do something only if the pointer which was passed does not equal NULL */
    if (elem != NULL)
    {
        DcmElement *dE;
        E_ListPos seekmode = ELP_last;
        /* iterate through elementList (from the last element to the first) */
        do {
            /* get current element from elementList */
            dE = OFstatic_cast(DcmElement *, elementList->seek(seekmode));
            /* if there is no element, i.e. elementList is empty */
            if (dE == NULL)
            {
                /* insert new element at the beginning of elementList */
                elementList->insert(elem, ELP_first);
                if (checkInsertOrder)
                {
                    // check if we have inserted at the end of the list
                    if (elem != OFstatic_cast(DcmElement *, elementList->seek(ELP_last)))
                    {
                        // produce diagnostics
                        DCMDATA_WARN("DcmItem: Dataset not in ascending tag order, at element " << elem->getTag());
                    }
                }
                /* dump some information if required */
                DCMDATA_TRACE("DcmItem::insert() Element " << elem->getTag()
                    << " VR=\"" << DcmVR(elem->getVR()).getVRName() << "\" inserted at beginning");
                /* check whether the new element already has a parent */
                if (elem->getParent() != NULL)
                {
                    DCMDATA_DEBUG("DcmItem::insert() Element " << elem->getTag() << " already has a parent: "
                      << elem->getParent()->getTag() << " VR=" << DcmVR(elem->getParent()->getVR()).getVRName());
                }
                /* remember the parent (i.e. the surrounding item/dataset) */
                elem->setParent(this);
                /* terminate do-while-loop */
                break;
            }
            /* else if the new element's tag is greater than the current element's tag */
            /* (i.e. we have found the position where the new element shall be inserted) */
            else if (elem->getTag() > dE->getTag().getTagKey() /* only compare the attribute tag */)
            {
                /* insert the new element after the current element */
                elementList->insert(elem, ELP_next);
                if (checkInsertOrder)
                {
                    // check if we have inserted at the end of the list
                    if (elem != OFstatic_cast(DcmElement *, elementList->seek(ELP_last)))
                    {
                        // produce diagnostics
                        DCMDATA_WARN("DcmItem: Dataset not in ascending tag order, at element " << elem->getTag());
                    }
                }
                /* dump some information if required */
                DCMDATA_TRACE("DcmItem::insert() Element " << elem->getTag()
                    << " VR=\"" << DcmVR(elem->getVR()).getVRName() << "\" inserted");
                /* check whether the new element already has a parent */
                if (elem->getParent() != NULL)
                {
                    DCMDATA_DEBUG("DcmItem::insert() Element " << elem->getTag() << " already has a parent: "
                        << elem->getParent()->getTag() << " VR=" << DcmVR(elem->getParent()->getVR()).getVRName());
                }
                /* remember the parent (i.e. the surrounding item/dataset) */
                elem->setParent(this);
                /* terminate do-while-loop */
                break;
            }
            /* else if the current element and the new element show the same tag */
            else if (elem->getTag() == dE->getTag().getTagKey() /* only compare the attribute tag */)
            {
                /* if new and current element are not identical */
                if (elem != dE)
                {
                    /* if the current (old) element shall be replaced */
                    if (replaceOld)
                    {
                        /* remove current element from list */
                        DcmObject *remObj = elementList->remove();

                        /* now the following holds: remObj == dE and elementList */
                        /* points to the element after the former current element. */

                        /* if the pointer to the removed object does not */
                        /* equal NULL (the usual case), delete this object */
                        /* and dump some information if required */
                        if (remObj != NULL)
                        {
                            /* dump some information if required */
                            DCMDATA_TRACE("DcmItem::insert() Element " << remObj->getTag()
                                << " VR=\"" << DcmVR(remObj->getVR()).getVRName()
                                << "\" p=" << OFstatic_cast(void *, remObj) << " removed and deleted");
                            delete remObj;
                        }
                        /* insert the new element before the current element */
                        elementList->insert(elem, ELP_prev);
                        /* dump some information if required */
                        DCMDATA_TRACE("DcmItem::insert() Element " << elem->getTag()
                            << " VR=\"" << DcmVR(elem->getVR()).getVRName()
                            << "\" p=" << OFstatic_cast(void *, elem) << " replaced older one");
                        /* check whether the new element already has a parent */
                        if (elem->getParent() != NULL)
                        {
                            DCMDATA_DEBUG("DcmItem::insert() Element " << elem->getTag() << " already has a parent: "
                                << elem->getParent()->getTag() << " VR=" << DcmVR(elem->getParent()->getVR()).getVRName());
                        }
                        /* remember the parent (i.e. the surrounding item/dataset) */
                        elem->setParent(this);
                    }   // if (replaceOld)
                    /* or else, i.e. the current element shall not be replaced by the new element */
                    else {
                        /* set the error flag correspondingly; we do not */
                        /* allow two elements with the same tag in elementList */
                        errorFlag = EC_DoubledTag;
                    }   // if (!replaceOld)
                }   // if (elem != dE)
                /* if the new and the current element are identical, the caller tries to insert */
                /* one element twice. Most probably an application error. */
                else {
                    errorFlag = EC_DoubledTag;
                }
                /* terminate do-while-loop */
                break;
            }
            /* set the seek mode to "get the previous element" */
            seekmode = ELP_prev;
        } while (dE);
    }
    /* if the pointer which was passed equals NULL, this is an illegal call */
    else
        errorFlag = EC_IllegalCall;
    /* return result value */
    return errorFlag;
}


// ********************************


DcmElement *DcmItem::getElement(const unsigned long num)
{
    errorFlag = EC_Normal;
    DcmElement *elem;
    elem = OFstatic_cast(DcmElement *, elementList->seek_to(num));
    /* reads element from list */
    if (elem == NULL)
        errorFlag = EC_IllegalCall;
    return elem;
}


// ********************************


DcmObject *DcmItem::nextInContainer(const DcmObject *obj)
{
    if (!obj)
        return elementList->get(ELP_first);
    else
    {
        if (elementList->get() != obj)
        {
            for(DcmObject * search_obj = elementList->seek(ELP_first);
                search_obj && search_obj != obj;
                search_obj = elementList->seek(ELP_next)
               ) {
                /* do nothing, just keep iterating */
            }
        }
        return elementList->seek(ELP_next);
    }
}


// ********************************


OFCondition DcmItem::nextObject(DcmStack &stack,
                                const OFBool intoSub)
{
    OFCondition l_error = EC_Normal;
    DcmObject * container = NULL;
    DcmObject * obj = NULL;
    DcmObject * result = NULL;
    OFBool examSub = intoSub;

    if (stack.empty())
    {
        stack.push(this);
        examSub = OFTrue;
    }

    obj = stack.top();
    if (obj->isLeaf() || !intoSub)
    {
        stack.pop();
        if (stack.card() > 0)
        {
            container = stack.top();
            result = container->nextInContainer(obj);
        }
    } else if (examSub)
        result = obj->nextInContainer(NULL);

    if (result)
        stack.push(result);
    else if (intoSub)
        l_error = nextUp(stack);
    else
        l_error = EC_SequEnd;

    return l_error;
}


// ********************************


DcmElement *DcmItem::remove(const unsigned long num)
{
    errorFlag = EC_Normal;
    DcmElement *elem;
    elem = OFstatic_cast(DcmElement *, elementList->seek_to(num));
    // read element from list
    if (elem != NULL)
    {
        elementList->remove();          // removes element from list but does not delete it
        elem->setParent(NULL);          // forget about the parent
    } else
        errorFlag = EC_IllegalCall;
    return elem;
}


// ********************************


DcmElement *DcmItem::remove(DcmObject *elem)
{
    errorFlag = EC_IllegalCall;
    if (!elementList->empty() && elem != NULL)
    {
        DcmObject *dO;
        elementList->seek(ELP_first);
        do {
            dO = elementList->get();
            if (dO == elem)
            {
                elementList->remove();     // removes element from list but does not delete it
                elem->setParent(NULL);     // forget about the parent
                errorFlag = EC_Normal;
                break;
            }
        } while (elementList->seek(ELP_next));
    }
    if (errorFlag == EC_IllegalCall)
        return NULL;
    else
        return OFstatic_cast(DcmElement *, elem);
}


// ********************************


DcmElement *DcmItem::remove(const DcmTagKey &tag)
{
    errorFlag = EC_TagNotFound;
    DcmObject *dO = NULL;
    if (!elementList->empty())
    {
        elementList->seek(ELP_first);
        do {
            dO = elementList->get();
            if (dO->getTag() == tag)
            {
                elementList->remove();     // removes element from list but does not delete it
                dO->setParent(NULL);       // forget about the parent
                errorFlag = EC_Normal;
                break;
            }
        } while (elementList->seek(ELP_next));
    }

    if (errorFlag == EC_TagNotFound)
        return NULL;
    else
        return OFstatic_cast(DcmElement *, dO);
}


// ********************************


OFCondition DcmItem::clear()
{
    errorFlag = EC_Normal;
    // remove all elements from item and delete them from memory
    elementList->deleteAllElements();
    setLengthField(0);

    return errorFlag;
}


OFBool DcmItem::isEmpty(const OFBool /*normalize*/)
{
    return elementList->empty();
}


// ********************************


OFCondition DcmItem::verify(const OFBool autocorrect)
{
    errorFlag = EC_Normal;
    if (!elementList->empty())
    {
        DcmObject *dO;
        elementList->seek(ELP_first);
        do {
            dO = elementList->get();
            if (dO->verify(autocorrect).bad())
                errorFlag = EC_CorruptedData;
        } while (elementList->seek(ELP_next));
    }
    if (autocorrect)
        setLengthField(getLength());
    return errorFlag;
}


// ********************************

// Precondition: elementList is non-empty!
// Result:       - return EC_Normal;
//                 push element pointer on resultStack
//               - return EC_TagNotFound;
//                 resultStack unmodified
// Search again: push pointer of sub-element on resultStack and
//               start sub-search

OFCondition DcmItem::searchSubFromHere(const DcmTagKey &tag,
                                       DcmStack &resultStack,
                                       OFBool searchIntoSub)
{
    DcmObject *dO;
    OFCondition l_error = EC_TagNotFound;
    if (!elementList->empty())
    {
        elementList->seek(ELP_first);
        do {
            dO = elementList->get();
            if (searchIntoSub)
            {
                resultStack.push(dO);
                if (dO->getTag() == tag)
                    l_error = EC_Normal;
                else
                    l_error = dO->search(tag, resultStack, ESM_fromStackTop, OFTrue);
                if (l_error.bad())
                    resultStack.pop();
            } else {
                if (dO->getTag() == tag)
                {
                    resultStack.push(dO);
                    l_error = EC_Normal;
                }
            }
        } while (l_error.bad() && elementList->seek(ELP_next));
        if (l_error==EC_Normal && dO->getTag()==tag)
        {
            DCMDATA_TRACE("DcmItem::searchSubFromHere() Element " << tag << " found");
        }
    }
    return l_error;
}


// ********************************


OFCondition DcmItem::search(const DcmTagKey &tag,
                            DcmStack &resultStack,
                            E_SearchMode mode,
                            OFBool searchIntoSub)
{
    DcmObject *dO = NULL;
    OFCondition l_error = EC_TagNotFound;
    if (mode == ESM_afterStackTop && resultStack.top() == this)
    {
        l_error = searchSubFromHere(tag, resultStack, searchIntoSub);
    }
    else if (!elementList->empty())
    {
        if (mode == ESM_fromHere || resultStack.empty())
        {
            resultStack.clear();
            l_error = searchSubFromHere(tag, resultStack, searchIntoSub);
        }
        else if (mode == ESM_fromStackTop)
        {
            dO = resultStack.top();
            if (dO == this)
                l_error = searchSubFromHere(tag, resultStack, searchIntoSub);
            else
            {   // gehe direkt zu Sub-Baum und suche dort weiter
                l_error = dO->search(tag, resultStack, mode, searchIntoSub);
// The next two lines destroy the stack->so delete them
//                if (l_error.bad()) // raeumt nur die oberste Stackebene
//                    resultStack.pop();      // ab; der Rest ist unveraendert
            }
        }
        else if (mode == ESM_afterStackTop && searchIntoSub)
        {
            // resultStack enthaelt Zielinformationen:
            // - stelle Zustand der letzen Suche in den einzelnen Suchroutinen
            //   wieder her
            // - finde Position von dO in Baum-Struktur
            //   1. suche eigenen Stack-Eintrag
            //      - bei Fehlschlag Suche beenden
            //   2. nehme naechsthoeheren Eintrag dnO
            //   3. stelle eigene Liste auf Position von dnO
            //   4. starte Suche ab dnO

            unsigned long i = resultStack.card();
            while (i > 0 && (dO = resultStack.elem(i-1)) != this)
            {
                i--;
            }
            if (dO != this && resultStack.card() > 0)
            {                            // oberste Ebene steht nie in resultStack
                i = resultStack.card()+1;// zeige jetzt auf hoechste Ebene+1
                dO = this;               // Treffer der hoechsten Ebene!
            }
            if (dO == this)
            {
                if (i == 1)                   // habe resultStack.top() gefunden
                    l_error = EC_TagNotFound; // markiere als kein Treffer, s.o.
                else                          //   siehe oben
                {
                    E_SearchMode submode = mode;
                    OFBool searchNode = OFTrue;
                    DcmObject *dnO;
                    dnO = resultStack.elem(i - 2); // Knoten der naechsten Ebene
                    elementList->seek(ELP_first);
                    do {
                        dO = elementList->get();
                        searchNode = searchNode ? (dO != dnO) : OFFalse;
                        if (!searchNode)
                        {                             // suche jetzt weiter
                            if (submode == ESM_fromStackTop)
                                resultStack.push(dO); // Stack aktualisieren
                            if (submode == ESM_fromStackTop && dO->getTag() == tag)
                                l_error = EC_Normal;
                            else
                                l_error = dO->search(tag, resultStack, submode, OFTrue);
                            if (l_error.bad())
                                resultStack.pop();
                            else
                                break;
                            submode = ESM_fromStackTop; // ab hier normale Suche
                        }
                    } while (elementList->seek(ELP_next));
                }
            } else
                l_error = EC_IllegalCall;
        } // (mode == ESM_afterStackTop
        else
            l_error = EC_IllegalCall;
    }
    return l_error;
}


// ********************************


OFCondition DcmItem::loadAllDataIntoMemory()
{
    OFCondition l_error = EC_Normal;
    if (!elementList->empty())
    {
        elementList->seek(ELP_first);
        do {
            OFCondition err = EC_Normal;
            DcmObject *dO = elementList->get();
            if ((err = dO->loadAllDataIntoMemory()).bad())
                l_error = err;
        } while (elementList->seek(ELP_next));
    }
    return l_error;
}


// ********************************


void DcmItem::compactElements(const Uint32 maxLength)
{
    DcmStack stack;
    DcmObject *object = NULL;
    /* iterate over all elements */
    while (nextObject(stack, OFTrue).good())
    {
        object = stack.top();
        // compact element if maximum length is exceeded
        if (object->isLeaf() && (object->getLength() > maxLength))
            OFstatic_cast(DcmElement *, object)->compact();
    }
}


// ********************************

// Support functions


OFCondition nextUp(DcmStack &stack)
{
    DcmObject *oldContainer = stack.pop();
    if (oldContainer->isLeaf())
        return EC_IllegalCall;
    else if (!stack.empty())
    {
        DcmObject *container = stack.top();
        DcmObject *result = container->nextInContainer(oldContainer);
        if (result)
        {
            stack.push(result);
            return EC_Normal;
        }
        else
            return nextUp(stack);
    }
    return EC_TagNotFound;
}


/*
** Simple tests for existence
*/

OFBool DcmItem::tagExists(const DcmTagKey &key,
                          OFBool searchIntoSub)
{
    DcmStack stack;

    OFCondition ec = search(key, stack, ESM_fromHere, searchIntoSub);
    return (ec.good());
}


OFBool DcmItem::tagExistsWithValue(const DcmTagKey &key,
                                   OFBool searchIntoSub)
{
    DcmStack stack;
    OFBool result = OFFalse;

    if (search(key, stack, ESM_fromHere, searchIntoSub).good() && stack.top()->isElement())
    {
        DcmElement *elem = OFstatic_cast(DcmElement *, stack.top());
        if (elem != NULL)
            result = !(elem->isEmpty());
    }

    return result;
}


// ********************************

/* --- findAndGet functions: find an element and get it or the value, respectively --- */

OFCondition DcmItem::findAndGetElement(const DcmTagKey &tagKey,
                                       DcmElement *&element,
                                       const OFBool searchIntoSub,
                                       const OFBool createCopy)
{
    DcmStack stack;
    /* find the element */
    OFCondition status = search(tagKey, stack, ESM_fromHere, searchIntoSub);
    if (status.good() && stack.top()->isElement())
    {
        element = OFstatic_cast(DcmElement *, stack.top());
        /* should never happen but ... */
        if (element == NULL)
            status = EC_CorruptedData;
        else if (createCopy)
        {
            /* create a copy of the element */
            element = OFstatic_cast(DcmElement *, element->clone());
            if (element == NULL)
                status = EC_MemoryExhausted;
        }
    } else {
        /* reset element pointer */
        element = NULL;
    }
    return status;
}


OFCondition DcmItem::findAndGetElements(const DcmTagKey &tagKey,
                                        DcmStack &resultStack)
{
    OFCondition status = EC_TagNotFound;
    DcmStack stack;
    DcmObject *object = NULL;
    /* iterate over all elements */
    while (nextObject(stack, OFTrue).good())
    {
        /* get element */
        object = stack.top();
        if (object->getTag() == tagKey)
        {
            /* add it to the result stack */
            resultStack.push(object);
            status = EC_Normal;
        }
    }
    return status;
}


OFCondition DcmItem::findAndGetString(const DcmTagKey& tagKey,
                                      const char *&value,
                                      const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getString(OFconst_cast(char *&, value));
    }
    /* reset value */
    if (status.bad())
        value = NULL;
    return status;
}


OFCondition DcmItem::findAndGetString(const DcmTagKey& tagKey,
                                      const char *&value,
                                      Uint32 &length,
                                      const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getString(OFconst_cast(char *&, value), length);
    }
    /* reset values */
    if (status.bad())
    {
        value = NULL;
        length = 0;
    }
    return status;
}


OFCondition DcmItem::findAndGetOFString(const DcmTagKey& tagKey,
                                        OFString &value,
                                        const unsigned long pos,
                                        const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getOFString(value, pos);
    }
    /* reset value */
    if (status.bad())
        value.clear();
    return status;
}


OFCondition DcmItem::findAndGetOFStringArray(const DcmTagKey& tagKey,
                                             OFString &value,
                                             const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getOFStringArray(value);
    }
    /* reset value */
    if (status.bad())
        value.clear();
    return status;
}


OFCondition DcmItem::findAndGetUint8(const DcmTagKey& tagKey,
                                     Uint8 &value,
                                     const unsigned long pos,
                                     const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getUint8(value, pos);
    }
    /* reset value */
    if (status.bad())
        value = 0;
    return status;
}


OFCondition DcmItem::findAndGetUint8Array(const DcmTagKey& tagKey,
                                          const Uint8 *&value,
                                          unsigned long *count,
                                          const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        Uint8 *array = NULL;
        status = elem->getUint8Array(array);
        value = array;
    }
    /* set optional count parameter */
    if (count != NULL)
    {
        if (status.good())
            *count = elem->getLength() / sizeof(Uint8);
        else
            *count = 0;
    }
    /* reset value */
    if (status.bad())
        value = NULL;
    return status;
}


OFCondition DcmItem::findAndGetUint16(const DcmTagKey& tagKey,
                                      Uint16 &value,
                                      const unsigned long pos,
                                      const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getUint16(value, pos);
    }
    /* reset value */
    if (status.bad())
        value = 0;
    return status;
}


OFCondition DcmItem::findAndGetUint16Array(const DcmTagKey& tagKey,
                                           const Uint16 *&value,
                                           unsigned long *count,
                                           const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        Uint16 *array = NULL;
        status = elem->getUint16Array(array);
        value = array;
    }
    /* set optional count parameter */
    if (count != NULL)
    {
        if (status.good())
        {
            /* don't use getNumberOfValues() because of OB/OW for pixel data
             * and since AT uses two 16-bit integers per value */
            *count = elem->getLength() / sizeof(Uint16);
        } else
            *count = 0;
    }
    /* reset value */
    if (status.bad())
        value = NULL;
    return status;
}


OFCondition DcmItem::findAndGetSint16(const DcmTagKey& tagKey,
                                      Sint16 &value,
                                      const unsigned long pos,
                                      const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getSint16(value, pos);
    }
    /* reset value */
    if (status.bad())
        value = 0;
    return status;
}


OFCondition DcmItem::findAndGetSint16Array(const DcmTagKey& tagKey,
                                           const Sint16 *&value,
                                           unsigned long *count,
                                           const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        Sint16 *array = NULL;
        status = elem->getSint16Array(array);
        value = array;
    }
    /* set optional count parameter */
    if (count != NULL)
    {
        if (status.good())
            *count = elem->getLength() / sizeof(Sint16);
        else
            *count = 0;
    }
    /* reset value */
    if (status.bad())
        value = NULL;
    return status;
}


OFCondition DcmItem::findAndGetUint32(const DcmTagKey& tagKey,
                                      Uint32 &value,
                                      const unsigned long pos,
                                      const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getUint32(value, pos);
    }
    /* reset value */
    if (status.bad())
        value = 0;
    return status;
}


OFCondition DcmItem::findAndGetUint32Array(const DcmTagKey& tagKey,
                                           const Uint32 *&value,
                                           unsigned long *count,
                                           const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        Uint32 *array = NULL;
        status = elem->getUint32Array(array);
        value = array;
    }
    /* set optional count parameter */
    if (count != NULL)
    {
        if (status.good())
            *count = elem->getLength() / sizeof(Uint32);
        else
            *count = 0;
    }
    /* reset value */
    if (status.bad())
        value = NULL;
    return status;
}


OFCondition DcmItem::findAndGetSint32(const DcmTagKey& tagKey,
                                      Sint32 &value,
                                      const unsigned long pos,
                                      const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getSint32(value, pos);
    }
    /* reset value */
    if (status.bad())
        value = 0;
    return status;
}


OFCondition DcmItem::findAndGetSint32Array(const DcmTagKey& tagKey,
                                           const Sint32 *&value,
                                           unsigned long *count,
                                           const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        Sint32 *array = NULL;
        status = elem->getSint32Array(array);
        value = array;
    }
    /* set optional count parameter */
    if (count != NULL)
    {
        if (status.good())
            *count = elem->getLength() / sizeof(Sint32);
        else
            *count = 0;
    }
    /* reset value */
    if (status.bad())
        value = NULL;
    return status;
}


OFCondition DcmItem::findAndGetUint64(const DcmTagKey& tagKey,
                                      Uint64 &value,
                                      const unsigned long pos,
                                      const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getUint64(value, pos);
    }
    /* reset value */
    if (status.bad())
        value = 0;
    return status;
}


OFCondition DcmItem::findAndGetUint64Array(const DcmTagKey& tagKey,
                                           const Uint64 *&value,
                                           unsigned long *count,
                                           const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        Uint64 *array = NULL;
        status = elem->getUint64Array(array);
        value = array;
    }
    /* set optional count parameter */
    if (count != NULL)
    {
        if (status.good())
            *count = elem->getLength() / sizeof(Uint64);
        else
            *count = 0;
    }
    /* reset value */
    if (status.bad())
        value = NULL;
    return status;
}


OFCondition DcmItem::findAndGetSint64(const DcmTagKey& tagKey,
                                      Sint64 &value,
                                      const unsigned long pos,
                                      const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getSint64(value, pos);
    }
    /* reset value */
    if (status.bad())
        value = 0;
    return status;
}


OFCondition DcmItem::findAndGetSint64Array(const DcmTagKey& tagKey,
                                           const Sint64 *&value,
                                           unsigned long *count,
                                           const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        Sint64 *array = NULL;
        status = elem->getSint64Array(array);
        value = array;
    }
    /* set optional count parameter */
    if (count != NULL)
    {
        if (status.good())
            *count = elem->getLength() / sizeof(Sint64);
        else
            *count = 0;
    }
    /* reset value */
    if (status.bad())
        value = NULL;
    return status;
}


OFCondition DcmItem::findAndGetLongInt(const DcmTagKey& tagKey,
                                       long int &value,
                                       const unsigned long pos,
                                       const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* distinguish supported VRs */
        switch (elem->ident())
        {
            case EVR_UL:
            case EVR_OL:
            case EVR_up:
                Uint32 ul;
                status = elem->getUint32(ul, pos);
                value = OFstatic_cast(long int, ul);
                break;
            case EVR_SL:
            case EVR_IS:
                Sint32 sl;
                status = elem->getSint32(sl, pos);
                value = OFstatic_cast(long int, sl);
                break;
            case EVR_US:
            case EVR_xs:
            case EVR_lt:
                Uint16 us;
                status = elem->getUint16(us, pos);
                value = OFstatic_cast(long int, us);
                break;
            case EVR_SS:
                Sint16 ss;
                status = elem->getSint16(ss, pos);
                value = OFstatic_cast(long int, ss);
                break;
            default:
                status = EC_IllegalCall;
                break;
        }
    }
    /* reset value */
    if (status.bad())
        value = 0;
    return status;
}


OFCondition DcmItem::findAndGetFloat32(const DcmTagKey& tagKey,
                                       Float32 &value,
                                       const unsigned long pos,
                                       const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getFloat32(value, pos);
    }
    /* reset value */
    if (status.bad())
        value = 0;
    return status;
}


OFCondition DcmItem::findAndGetFloat32Array(const DcmTagKey& tagKey,
                                            const Float32 *&value,
                                            unsigned long *count,
                                            const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        Float32 *array = NULL;
        status = elem->getFloat32Array(array);
        value = array;
    }
    /* set optional count parameter */
    if (count != NULL)
    {
        if (status.good())
            *count = elem->getLength() / sizeof(Float32);
        else
            *count = 0;
    }
    /* reset value */
    if (status.bad())
        value = NULL;
    return status;
}


OFCondition DcmItem::findAndGetFloat64(const DcmTagKey& tagKey,
                                       Float64 &value,
                                       const unsigned long pos,
                                       const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        status = elem->getFloat64(value, pos);
    }
    /* reset value */
    if (status.bad())
        value = 0;
    return status;
}


OFCondition DcmItem::findAndGetFloat64Array(const DcmTagKey& tagKey,
                                            const Float64 *&value,
                                            unsigned long *count,
                                            const OFBool searchIntoSub)
{
    DcmElement *elem;
    /* find the element */
    OFCondition status = findAndGetElement(tagKey, elem, searchIntoSub);
    if (status.good())
    {
        /* get the value */
        Float64 *array = NULL;
        status = elem->getFloat64Array(array);
        value = array;
    }
    /* set optional count parameter */
    if (count != NULL)
    {
        if (status.good())
            *count = elem->getLength() / sizeof(Float64);
        else
            *count = 0;
    }
    /* reset value */
    if (status.bad())
        value = NULL;
    return status;
}


OFCondition DcmItem::findAndGetSequence(const DcmTagKey &seqTagKey,
                                        DcmSequenceOfItems *&sequence,
                                        const OFBool searchIntoSub,
                                        const OFBool createCopy)
{
    DcmStack stack;
    /* find the element */
    OFCondition status = search(seqTagKey, stack, ESM_fromHere, searchIntoSub);
    if (status.good() && stack.top()->isElement())
    {
        DcmElement *delem = OFstatic_cast(DcmElement *, stack.top());
        /* should never happen but ... */
        if (delem == NULL)
            status = EC_CorruptedData;
        /* check for correct VR */
        else if ((delem->ident() == EVR_SQ) || (delem->ident() == EVR_pixelSQ))
        {
            sequence = OFstatic_cast(DcmSequenceOfItems *, delem);
            /* create a copy of the sequence? */
            if (createCopy)
            {
                sequence = OFstatic_cast(DcmSequenceOfItems *, sequence->clone());
                if (sequence == NULL)
                    status = EC_MemoryExhausted;
            }
        } else
            status = EC_InvalidVR;
    }
    if (status.bad())
    {
        /* reset sequence pointer */
        sequence = NULL;
    }
    return status;
}


OFCondition DcmItem::findAndGetSequenceItem(const DcmTagKey &seqTagKey,
                                            DcmItem *&item,
                                            const signed long itemNum,
                                            const OFBool createCopy)
{
    DcmStack stack;
    /* find sequence */
    OFCondition status = search(seqTagKey, stack, ESM_fromHere, OFFalse /*searchIntoSub*/);
    if (status.good() && stack.top()->isElement())
    {
        /* get element */
        DcmElement *delem = OFstatic_cast(DcmElement *, stack.top());
        if (delem != NULL)
        {
            /* check VR */
            if ((delem->ident() == EVR_SQ) || (delem->ident() == EVR_pixelSQ))
            {
                DcmSequenceOfItems *sequence = OFstatic_cast(DcmSequenceOfItems *, delem);
                const unsigned long count = sequence->card();
                /* empty sequence? */
                if (count > 0)
                {
                    /* get last item */
                    if (itemNum == -1)
                        item = sequence->getItem(count - 1);
                    /* get specified item */
                    else if ((itemNum >= 0) && (OFstatic_cast(unsigned long, itemNum) < count))
                        item = sequence->getItem(OFstatic_cast(unsigned long, itemNum));
                    /* invalid item number */
                    else
                        status = EC_IllegalParameter;
                    /* create a copy of the item? */
                    if (createCopy)
                    {
                        if (status.good() && (item != NULL))
                        {
                            item = OFstatic_cast(DcmItem *, item->clone());
                            if (item == NULL)
                                status = EC_MemoryExhausted;
                        }
                    }
                } else
                    status = EC_IllegalParameter;
            } else
                status = EC_InvalidVR;
        } else
            status = EC_CorruptedData;
    }
    /* reset item value */
    if (status.bad())
        item = NULL;
    else if (item == NULL)
        status = EC_IllegalCall;
    return status;
}


// ********************************

/* --- findOrCreate functions: find an element or create a new one --- */

OFCondition DcmItem::findOrCreateSequenceItem(const DcmTag& seqTag,
                                              DcmItem *&item,
                                              const signed long itemNum)
{
    DcmStack stack;
    /* find sequence */
    OFCondition status = search(seqTag, stack, ESM_fromHere, OFFalse /*searchIntoSub*/);
    DcmSequenceOfItems *sequence = NULL;
    /* sequence found? */
    if (status.good() && stack.top()->isElement())
    {
        /* get element */
        DcmElement *delem = OFstatic_cast(DcmElement *, stack.top());
        if (delem != NULL)
        {
            /* check VR */
            if ((delem->ident() == EVR_SQ) || (delem->ident() == EVR_pixelSQ))
                sequence = OFstatic_cast(DcmSequenceOfItems *, delem);
            else
                status = EC_InvalidVR;
        } else
            status = EC_CorruptedData;
    } else {
        /* create new sequence element */
        sequence = new DcmSequenceOfItems(seqTag);
        if (sequence != NULL)
        {
            /* insert into item/dataset */
            status = insert(sequence, OFTrue /*replaceOld*/);
            if (status.bad())
                delete sequence;
        } else
            status = EC_MemoryExhausted;
    }
    if (status.good())
    {
        if (sequence != NULL)
        {
            const unsigned long count = sequence->card();
            /* existing item? */
            if ((count > 0) && (itemNum >= -1) && (itemNum < OFstatic_cast(signed long, count)))
            {
                if (itemNum == -1)
                {
                    /* get last item */
                    item = sequence->getItem(count - 1);
                } else {
                    /* get specified item */
                    item = sequence->getItem(OFstatic_cast(unsigned long, itemNum));
                }
            /* create new item(s) */
            } else {
                unsigned long i = 0;
                /* create empty trailing items if required */
                const unsigned long itemCount = (itemNum > OFstatic_cast(signed long, count)) ? (itemNum - count + 1) : 1;
                while ((i < itemCount) && status.good())
                {
                    item = new DcmItem();
                    if (item != NULL)
                    {
                        /* append new item to end of sequence */
                        status = sequence->append(item);
                        if (status.bad())
                            delete item;
                    } else
                        status = EC_MemoryExhausted;
                    i++;
                }
            }
        } else
            status = EC_IllegalCall;
    }
    /* reset item value */
    if (status.bad())
        item = NULL;
    else if (item == NULL)
        status = EC_IllegalCall;
    return status;
}


// ********************************


/* --- findAndXXX functions: find an element and do something with it --- */

OFCondition DcmItem::findAndInsertCopyOfElement(const DcmTagKey &tagKey,
                                                DcmItem *destItem,
                                                const OFBool replaceOld)
{
    OFCondition status = EC_IllegalParameter;
    if (destItem != NULL)
    {
        DcmElement *delem = NULL;
        /* get copy of element from current dataset */
        status = findAndGetElement(tagKey, delem, OFFalse /*searchIntoSub*/, OFTrue /*createCopy*/);
        if (status.good())
        {
            /* ... and insert it into the destination dataset */
            status = destItem->insert(delem, replaceOld);
            if (status.bad())
                delete delem;
        }
    }
    return status;
}


OFCondition DcmItem::findAndDeleteElement(const DcmTagKey &tagKey,
                                          const OFBool allOccurrences,
                                          const OFBool searchIntoSub)
{
    OFCondition status = EC_TagNotFound;
    DcmStack stack;
    DcmObject *object = NULL;
    OFBool intoSub = OFTrue;
    /* iterate over all elements */
    while (nextObject(stack, intoSub).good())
    {
        /* get element */
        object = stack.top();
        if (object->getTag() == tagKey)
        {
            stack.pop();
            /* remove element from dataset and free memory */
            delete OFstatic_cast(DcmItem *, stack.top())->remove(object);
            status = EC_Normal;
            /* delete only the first element? */
            if (!allOccurrences)
                break;
        }
        intoSub = searchIntoSub || allOccurrences;
    }
    return status;
}


OFCondition DcmItem::findAndDeleteSequenceItem(const DcmTagKey &seqTagKey,
                                               const signed long itemNum)
{
    DcmStack stack;
    /* find sequence */
    OFCondition status = search(seqTagKey, stack, ESM_fromHere, OFFalse /*searchIntoSub*/);
    if (status.good() && stack.top()->isElement())
    {
        /* get element */
        DcmElement *delem = OFstatic_cast(DcmElement *, stack.top());
        if (delem != NULL)
        {
            /* check VR */
            if ((delem->ident() == EVR_SQ) || (delem->ident() == EVR_pixelSQ))
            {
                DcmSequenceOfItems *sequence = OFstatic_cast(DcmSequenceOfItems *, delem);
                const unsigned long count = sequence->card();
                /* last item? */
                if (itemNum == -1)
                    delete sequence->remove(count - 1);
                /* valid item? */
                else if ((itemNum >= 0) && (OFstatic_cast(unsigned long, itemNum) < count))
                    delete sequence->remove(OFstatic_cast(unsigned long, itemNum));
                else
                    status = EC_IllegalParameter;
            } else
                status = EC_InvalidVR;
        } else
            status = EC_CorruptedData;
    }
    return status;
}


// ********************************

/* --- putAndInsert functions: put value and insert new element --- */

OFCondition DcmItem::putAndInsertString(const DcmTag& tag,
                                        const char *value,
                                        const OFBool replaceOld)
{
    /* determine length of the string value */
    const Uint32 length = (value != NULL) ? OFstatic_cast(Uint32, strlen(value)) : 0;
    /* call the real function */
    return putAndInsertString(tag, value, length, replaceOld);
}


OFCondition DcmItem::putAndInsertString(const DcmTag& tag,
                                        const char *value,
                                        const Uint32 length,
                                        const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_AE:
            elem = new DcmApplicationEntity(tag);
            break;
        case EVR_AS:
            elem = new DcmAgeString(tag);
            break;
        case EVR_AT:
            elem = new DcmAttributeTag(tag);
            break;
        case EVR_CS:
            elem = new DcmCodeString(tag);
            break;
        case EVR_DA:
            elem = new DcmDate(tag);
            break;
        case EVR_DS:
            elem = new DcmDecimalString(tag);
            break;
        case EVR_DT:
            elem = new DcmDateTime(tag);
            break;
        case EVR_FL:
            elem = new DcmFloatingPointSingle(tag);
            break;
        case EVR_FD:
            elem = new DcmFloatingPointDouble(tag);
            break;
        case EVR_IS:
            elem = new DcmIntegerString(tag);
            break;
        case EVR_LO:
            elem = new DcmLongString(tag);
            break;
        case EVR_LT:
            elem = new DcmLongText(tag);
            break;
        case EVR_OB:
        case EVR_OW:
            elem = new DcmOtherByteOtherWord(tag);
            break;
        case EVR_OD:
            elem = new DcmOtherDouble(tag);
            break;
        case EVR_OF:
            elem = new DcmOtherFloat(tag);
            break;
        case EVR_OL:
            elem = new DcmOtherLong(tag);
            break;
        case EVR_OV:
            elem = new DcmOther64bitVeryLong(tag);
            break;
        case EVR_PN:
            elem = new DcmPersonName(tag);
            break;
        case EVR_SH:
            elem = new DcmShortString(tag);
            break;
        case EVR_SL:
            elem = new DcmSignedLong(tag);
            break;
        case EVR_SS:
            elem = new DcmSignedShort(tag);
            break;
        case EVR_ST:
            elem = new DcmShortText(tag);
            break;
        case EVR_SV:
            elem = new DcmSigned64bitVeryLong(tag);
            break;
        case EVR_TM:
            elem = new DcmTime(tag);
            break;
        case EVR_UC:
            elem = new DcmUnlimitedCharacters(tag);
            break;
        case EVR_UI:
            elem = new DcmUniqueIdentifier(tag);
            break;
        case EVR_UL:
            elem = new DcmUnsignedLong(tag);
            break;
        case EVR_UR:
            elem = new DcmUniversalResourceIdentifierOrLocator(tag);
            break;
        case EVR_US:
            elem = new DcmUnsignedShort(tag);
            break;
        case EVR_UT:
            elem = new DcmUnlimitedText(tag);
            break;
        case EVR_UV:
            elem = new DcmUnsigned64bitVeryLong(tag);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putString(value, length);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertOFStringArray(const DcmTag& tag,
                                               const OFString &value,
                                               const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_AE:
            elem = new DcmApplicationEntity(tag);
            break;
        case EVR_AS:
            elem = new DcmAgeString(tag);
            break;
        case EVR_CS:
            elem = new DcmCodeString(tag);
            break;
        case EVR_DA:
            elem = new DcmDate(tag);
            break;
        case EVR_DS:
            elem = new DcmDecimalString(tag);
            break;
        case EVR_DT:
            elem = new DcmDateTime(tag);
            break;
        case EVR_IS:
            elem = new DcmIntegerString(tag);
            break;
        case EVR_LO:
            elem = new DcmLongString(tag);
            break;
        case EVR_LT:
            elem = new DcmLongText(tag);
            break;
        case EVR_PN:
            elem = new DcmPersonName(tag);
            break;
        case EVR_SH:
            elem = new DcmShortString(tag);
            break;
        case EVR_ST:
            elem = new DcmShortText(tag);
            break;
        case EVR_TM:
            elem = new DcmTime(tag);
            break;
        case EVR_UC:
            elem = new DcmUnlimitedCharacters(tag);
            break;
        case EVR_UI:
            elem = new DcmUniqueIdentifier(tag);
            break;
        case EVR_UR:
            elem = new DcmUniversalResourceIdentifierOrLocator(tag);
            break;
        case EVR_UT:
            elem = new DcmUnlimitedText(tag);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putOFStringArray(value);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertUint8Array(const DcmTag& tag,
                                            const Uint8 *value,
                                            const unsigned long count,
                                            const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_OB:
            elem = new DcmOtherByteOtherWord(tag);
            break;
        case EVR_ox:
            /* special handling for Pixel Data */
            if (tag == DCM_PixelData)
            {
                elem = new DcmPixelData(tag);
                if (elem != NULL)
                    elem->setVR(EVR_OB);
            } else
                elem = new DcmPolymorphOBOW(tag);
            break;
        case EVR_px:
            elem = new DcmPixelData(tag);
            if (elem != NULL)
                elem->setVR(EVR_OB);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putUint8Array(value, count);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertUint16(const DcmTag& tag,
                                        const Uint16 value,
                                        const unsigned long pos,
                                        const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_US:
            elem = new DcmUnsignedShort(tag);
            break;
        case EVR_lt:
        case EVR_xs:
            /* special handling */
            elem = new DcmUnsignedShort(DcmTag(tag, EVR_US));
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putUint16(value, pos);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertUint16Array(const DcmTag& tag,
                                             const Uint16 *value,
                                             const unsigned long count,
                                             const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_AT:
            elem = new DcmAttributeTag(tag);
            break;
        case EVR_lt:
        case EVR_OW:
            elem = new DcmOtherByteOtherWord(tag);
            break;
        case EVR_US:
            elem = new DcmUnsignedShort(tag);
            break;
        case EVR_ox:
            /* special handling */
            if (tag == DCM_PixelData)
            {
                elem = new DcmPixelData(tag);
                if (elem != NULL)
                    elem->setVR(EVR_OW);
            } else
                elem = new DcmPolymorphOBOW(tag);
            break;
        case EVR_px:
            elem = new DcmPixelData(tag);
            if (elem != NULL)
                elem->setVR(EVR_OW);
            break;
        case EVR_xs:
            /* special handling */
            elem = new DcmUnsignedShort(DcmTag(tag, EVR_US));
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putUint16Array(value, count);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertSint16(const DcmTag& tag,
                                        const Sint16 value,
                                        const unsigned long pos,
                                        const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_SS:
            elem = new DcmSignedShort(tag);
            break;
        case EVR_lt:
        case EVR_xs:
            /* special handling */
            elem = new DcmSignedShort(DcmTag(tag, EVR_SS));
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putSint16(value, pos);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertSint16Array(const DcmTag& tag,
                                             const Sint16 *value,
                                             const unsigned long count,
                                             const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_SS:
            elem = new DcmSignedShort(tag);
            break;
        case EVR_lt:
        case EVR_xs:
            /* special handling */
            elem = new DcmSignedShort(DcmTag(tag, EVR_SS));
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putSint16Array(value, count);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertUint32(const DcmTag& tag,
                                        const Uint32 value,
                                        const unsigned long pos,
                                        const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_UL:
            elem = new DcmUnsignedLong(tag);
            break;
        case EVR_OL:
            elem = new DcmOtherLong(tag);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putUint32(value, pos);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertUint32Array(const DcmTag& tag,
                                             const Uint32 *value,
                                             const unsigned long count,
                                             const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_OL:
            elem = new DcmOtherLong(tag);
            break;
        case EVR_UL:
            elem = new DcmUnsignedLong(tag);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putUint32Array(value, count);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertSint32(const DcmTag& tag,
                                        const Sint32 value,
                                        const unsigned long pos,
                                        const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_SL:
            elem = new DcmSignedLong(tag);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putSint32(value, pos);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertSint32Array(const DcmTag& tag,
                                             const Sint32 *value,
                                             const unsigned long count,
                                             const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_SL:
            elem = new DcmSignedLong(tag);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putSint32Array(value, count);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertFloat32(const DcmTag& tag,
                                         const Float32 value,
                                         const unsigned long pos,
                                         const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_FL:
            elem = new DcmFloatingPointSingle(tag);
            break;
        case EVR_OF:
            elem = new DcmOtherFloat(tag);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putFloat32(value, pos);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertFloat32Array(const DcmTag& tag,
                                              const Float32 *value,
                                              const unsigned long count,
                                              const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_FL:
            elem = new DcmFloatingPointSingle(tag);
            break;
        case EVR_OF:
            elem = new DcmOtherFloat(tag);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putFloat32Array(value, count);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertFloat64(const DcmTag& tag,
                                         const Float64 value,
                                         const unsigned long pos,
                                         const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_DS:
            elem = new DcmDecimalString(tag);
            break;
        case EVR_FD:
            elem = new DcmFloatingPointDouble(tag);
            break;
        case EVR_OD:
            elem = new DcmOtherDouble(tag);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putFloat64(value, pos);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertFloat64Array(const DcmTag& tag,
                                              const Float64 *value,
                                              const unsigned long count,
                                              const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_FD:
            elem = new DcmFloatingPointDouble(tag);
            break;
        case EVR_OD:
            elem = new DcmOtherDouble(tag);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putFloat64Array(value, count);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::putAndInsertTagKey(const DcmTag& tag,
                                        const DcmTagKey &value,
                                        const unsigned long pos,
                                        const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_AT:
            elem = new DcmAttributeTag(tag);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* put value */
        status = elem->putTagVal(value, pos);
        /* insert into dataset/item */
        if (status.good())
            status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


// ********************************


OFCondition DcmItem::insertEmptyElement(const DcmTag& tag,
                                        const OFBool replaceOld)
{
    OFCondition status = EC_Normal;
    /* create new element */
    DcmElement *elem = NULL;
    switch(tag.getEVR())
    {
        case EVR_AE:
            elem = new DcmApplicationEntity(tag);
            break;
        case EVR_AS:
            elem = new DcmAgeString(tag);
            break;
        case EVR_AT:
            elem = new DcmAttributeTag(tag);
            break;
        case EVR_CS:
            elem = new DcmCodeString(tag);
            break;
        case EVR_DA:
            elem = new DcmDate(tag);
            break;
        case EVR_DS:
            elem = new DcmDecimalString(tag);
            break;
        case EVR_DT:
            elem = new DcmDateTime(tag);
            break;
        case EVR_FL:
            elem = new DcmFloatingPointSingle(tag);
            break;
        case EVR_FD:
            elem = new DcmFloatingPointDouble(tag);
            break;
        case EVR_IS:
            elem = new DcmIntegerString(tag);
            break;
        case EVR_LO:
            elem = new DcmLongString(tag);
            break;
        case EVR_LT:
            elem = new DcmLongText(tag);
            break;
        case EVR_OB:
        case EVR_OW:
            elem = new DcmOtherByteOtherWord(tag);
            break;
        case EVR_OD:
            elem = new DcmOtherDouble(tag);
            break;
        case EVR_OF:
            elem = new DcmOtherFloat(tag);
            break;
        case EVR_OL:
            elem = new DcmOtherLong(tag);
            break;
        case EVR_OV:
            elem = new DcmOther64bitVeryLong(tag);
            break;
        case EVR_PN:
            elem = new DcmPersonName(tag);
            break;
        case EVR_SH:
            elem = new DcmShortString(tag);
            break;
        case EVR_SL:
            elem = new DcmSignedLong(tag);
            break;
        case EVR_SQ:
            elem = new DcmSequenceOfItems(tag);
            break;
        case EVR_SS:
            elem = new DcmSignedShort(tag);
            break;
        case EVR_ST:
            elem = new DcmShortText(tag);
            break;
        case EVR_SV:
            elem = new DcmSigned64bitVeryLong(tag);
            break;
        case EVR_TM:
            elem = new DcmTime(tag);
            break;
        case EVR_UC:
            elem = new DcmUnlimitedCharacters(tag);
            break;
        case EVR_UI:
            elem = new DcmUniqueIdentifier(tag);
            break;
        case EVR_UL:
            elem = new DcmUnsignedLong(tag);
            break;
        case EVR_UR:
            elem = new DcmUniversalResourceIdentifierOrLocator(tag);
            break;
        case EVR_US:
            elem = new DcmUnsignedShort(tag);
            break;
        case EVR_UT:
            elem = new DcmUnlimitedText(tag);
            break;
        case EVR_UV:
            elem = new DcmUnsigned64bitVeryLong(tag);
            break;
        case EVR_PixelData:
            elem = new DcmPixelData(tag);
            // set VR to OW to make sure that we never write/send the internal VR
            if (elem) elem->setVR(EVR_OW);
            break;
        case EVR_OverlayData:
            elem = new DcmOverlayData(tag);
            // set VR to OW to make sure that we never write/send the internal VR
            if (elem) elem->setVR(EVR_OW);
            break;
        case EVR_UNKNOWN:
            /* Unknown VR, e.g. tag not found in data dictionary */
            status = EC_UnknownVR;
            break;
        default:
            status = EC_IllegalCall;
            break;
    }
    if (elem != NULL)
    {
        /* insert new element into dataset/item */
        status = insert(elem, replaceOld);
        /* could not be inserted, therefore, delete it immediately */
        if (status.bad())
            delete elem;
    } else if (status.good())
        status = EC_MemoryExhausted;
    return status;
}


OFCondition DcmItem::insertSequenceItem(const DcmTag &seqTag,
                                        DcmItem *item,
                                        const signed long itemNum)
{
    OFCondition status = EC_IllegalParameter;
    if (item != NULL)
    {
        DcmStack stack;
        /* find sequence */
        status = search(seqTag, stack, ESM_fromHere, OFFalse /*searchIntoSub*/);
        DcmSequenceOfItems *sequence = NULL;
        /* sequence found? */
        if (status.good() && stack.top()->isElement())
        {
            /* get element */
            DcmElement *delem = OFstatic_cast(DcmElement *, stack.top());
            if (delem != NULL)
            {
                /* check VR */
                if ((delem->ident() == EVR_SQ) || (delem->ident() == EVR_pixelSQ))
                    sequence = OFstatic_cast(DcmSequenceOfItems *, delem);
                else
                    status = EC_InvalidVR;
            } else
                status = EC_CorruptedData;
        } else {
            /* create new sequence element */
            sequence = new DcmSequenceOfItems(seqTag);
            if (sequence != NULL)
            {
                /* insert into item/dataset */
                status = insert(sequence, OFTrue /*replaceOld*/);
                if (status.bad())
                    delete sequence;
            } else
                status = EC_MemoryExhausted;
        }
        if (status.good())
        {
            if (sequence != NULL)
            {
                const unsigned long count = sequence->card();
                /* 'itemNum' specifies and existing item? */
                if ((count > 0) && (itemNum >= -1) && (itemNum < OFstatic_cast(signed long, count)))
                {
                    if (itemNum == -1)
                    {
                        /* insert given item before last entry */
                        status = sequence->insert(item, DCM_EndOfListIndex, OFTrue /*before*/);
                    } else {
                        /* insert given item before specified entry */
                        status = sequence->insert(item, OFstatic_cast(unsigned long, itemNum), OFTrue /*before*/);
                    }
                /* create empty item(s) and append */
                } else {
                    DcmItem *newItem = NULL;
                    unsigned long i = 0;
                    /* create empty trailing items if required */
                    const unsigned long itemCount = (itemNum > OFstatic_cast(signed long, count)) ? (itemNum - count) : 0;
                    while ((i < itemCount) && status.good())
                    {
                        newItem = new DcmItem();
                        if (newItem != NULL)
                        {
                            /* append new item to end of sequence */
                            status = sequence->append(newItem);
                            if (status.bad())
                                delete newItem;
                        } else
                            status = EC_MemoryExhausted;
                        i++;
                    }
                    /* append given item to end of sequence */
                    status = sequence->append(item);
                }
            } else
                status = EC_IllegalCall;
        }
    }
    return status;
}


// ********************************


OFBool DcmItem::containsUnknownVR() const
{
    if (!elementList->empty())
    {
        elementList->seek(ELP_first);
        do {
            if (elementList->get()->containsUnknownVR())
                return OFTrue;
        } while (elementList->seek(ELP_next));
    }
    return OFFalse;
}


OFBool DcmItem::containsExtendedCharacters(const OFBool checkAllStrings)
{
    if (!elementList->empty())
    {
        elementList->seek(ELP_first);
        do {
            if (elementList->get()->containsExtendedCharacters(checkAllStrings))
                return OFTrue;
        } while (elementList->seek(ELP_next));
    }
    return OFFalse;
}


OFBool DcmItem::isAffectedBySpecificCharacterSet() const
{
    if (!elementList->empty())
    {
        elementList->seek(ELP_first);
        do {
            if (elementList->get()->isAffectedBySpecificCharacterSet())
                return OFTrue;
        } while (elementList->seek(ELP_next));
    }
    return OFFalse;
}


// ********************************


void DcmItem::updateSpecificCharacterSet(OFCondition &status,
                                         const DcmSpecificCharacterSet &converter)
{
    const OFString encoding = converter.getDestinationEncoding();
    if (status.good())
    {
        // check whether the attribute Specific Character Set (0008,0005) should be present at all
        if (checkForSpecificCharacterSet())
        {
            const OFString toCharset = converter.getDestinationCharacterSet();
            // check for default character set (ASCII), also make sure that the value "ISO_IR 6" is never used
            // in a dataset; open question: should we also check for non-ASCII characters in the element value?
            if (toCharset.empty() || (toCharset == "ISO_IR 6"))
            {
                // delete Specific Character Set (0008,0005) data element (type 1C)
                if (findAndDeleteElement(DCM_SpecificCharacterSet, OFFalse /*allOccurrences*/, OFFalse /*searchIntoSub*/).good())
                {
                    DCMDATA_DEBUG("DcmItem::convertCharacterSet() deleted element SpecificCharacterSet "
                        << DCM_SpecificCharacterSet << " during the conversion to " << encoding << " encoding");
                }
            } else {
                DCMDATA_DEBUG("DcmItem::convertCharacterSet() updating value of element SpecificCharacterSet "
                    << DCM_SpecificCharacterSet << " to '" << toCharset << "'");
                // update/set value of Specific Character Set (0008,0005) if needed
                status = putAndInsertOFStringArray(DCM_SpecificCharacterSet, toCharset);
            }
        } else {
            // otherwise delete it (if present)
            if (findAndDeleteElement(DCM_SpecificCharacterSet, OFFalse /*allOccurrences*/, OFFalse /*searchIntoSub*/).good())
            {
                DCMDATA_WARN("DcmItem: Deleted element SpecificCharacterSet " << DCM_SpecificCharacterSet
                    << " during the conversion to " << encoding << " encoding");
            }
        }
    } else {
        // an error occurred in a previous processing step
        DCMDATA_WARN("DcmItem: An error occurred during the conversion to " << encoding << " encoding, "
            << "the value of SpecificCharacterSet " << DCM_SpecificCharacterSet << " is not updated");
    }
}


OFCondition DcmItem::convertCharacterSet(const OFString &fromCharset,
                                         const OFString &toCharset,
                                         const size_t flags,
                                         const OFBool updateCharset)
{
    OFCondition status = EC_Normal;
    // if the item is empty, there is nothing to do
    if (!elementList->empty())
    {
        DcmSpecificCharacterSet converter;
        // create a new character set converter
        DCMDATA_DEBUG("DcmItem::convertCharacterSet() creating a new character set converter for '"
            << fromCharset << "'" << (fromCharset.empty() ? " (ASCII)" : "") << " to '"
            << toCharset << "'" << (toCharset.empty() ? " (ASCII)" : ""));
        // select source and destination character set
        status = converter.selectCharacterSet(fromCharset, toCharset);
        if (status.good())
        {
            unsigned cflags = 0;
            /* pass flags to underlying implementation */
            if (flags & DCMTypes::CF_discardIllegal)
                cflags |= OFCharacterEncoding::DiscardIllegalSequences;
            if (flags & DCMTypes::CF_transliterate)
                cflags |= OFCharacterEncoding::TransliterateIllegalSequences;
            if (cflags > 0)
                status = converter.setConversionFlags(cflags);
            if (status.good())
            {
                // convert all affected element values in the item
                status = convertCharacterSet(converter);
                if (updateCharset)
                {
                    // update the Specific Character Set (0008,0005) element
                    updateSpecificCharacterSet(status, converter);
                }
            }
        }
    }
    return status;
}


OFCondition DcmItem::convertCharacterSet(const OFString &toCharset,
                                         const size_t flags,
                                         const OFBool ignoreCharset)
{
    OFString fromCharset;
    // check whether this item can contain the attribute SpecificCharacterSet (0008,0005)
    if (checkForSpecificCharacterSet() && !ignoreCharset)
    {
        // determine value of Specific Character Set (0008,0005) if present in this item
        findAndGetOFStringArray(DCM_SpecificCharacterSet, fromCharset, OFFalse /*searchIntoSub*/);
    }
    // do the real work, if Specific Character Set is missing or empty use the default (ASCII)
    return convertCharacterSet(fromCharset, toCharset, flags, !ignoreCharset /*updateCharset*/);
}


OFCondition DcmItem::convertCharacterSet(DcmSpecificCharacterSet &converter)
{
    OFCondition status = EC_Normal;
    // if the item is empty, there is nothing to do
    if (!elementList->empty())
    {
        // iterate over all data elements in this item and convert the strings
        elementList->seek(ELP_first);
        do {
            status = elementList->get()->convertCharacterSet(converter);
        } while (status.good() && elementList->seek(ELP_next));
    }
    return status;
}


OFCondition DcmItem::convertToUTF8()
{
    // the DICOM defined term "ISO_IR 192" is used for "UTF-8"
    return convertCharacterSet("ISO_IR 192", 0 /*flags*/);
}


// ********************************


DcmElement* DcmItem::newDicomElement(const DcmTagKey& tag,
                                     const char *privateCreator)
{
  DcmTag temp(tag, privateCreator);
  DcmElement* elem = NULL;
  OFBool readAsUN = OFFalse;
  newDicomElement(
      elem,
      temp,
      0,          // Length
      NULL,       // Private creator
      readAsUN);  // read as VR UN (result ignored)
  return elem;
}


OFCondition DcmItem::newDicomElementWithVR(DcmElement*& newElement, const DcmTag& tag)
{
  DcmTag temp(tag);
  OFBool readAsUN = OFFalse;
  return newDicomElement(
      newElement,
      temp,
      0,          // Length
      NULL,       // Private creator
      readAsUN);  // read as VR UN (result ignored)
}


OFCondition DcmItem::newDicomElement(DcmElement*& newElement,
                                     const DcmTagKey& tag,
                                     const char *privateCreator)
{
    DcmTag temp(tag, privateCreator);
    newElement = NULL;
    OFBool readAsUN = OFFalse;
    return newDicomElement(
        newElement,
        temp,
        0,          // Length
        NULL,       // Private creator
        readAsUN);  // read as VR UN (result ignored)
}


OFCondition DcmItem::newDicomElement(DcmElement *&newElement,
                                     DcmTag &tag,
                                     const Uint32 length,
                                     DcmPrivateTagCache *privateCreatorCache,
                                     OFBool& readAsUN)
{
    /* initialize variables */
    OFCondition l_error = EC_Normal;
    newElement = NULL;
    DcmEVR evr = tag.getEVR();
    readAsUN = OFFalse;

    /* revert UN elements with finite length back to known VR if possible */
    if ((evr == EVR_UN) && (length != DCM_UndefinedLength) && dcmEnableUnknownVRConversion.get())
    {
        /* look up VR in data dictionary */
        DcmTag newTag(tag.getGroup(), tag.getElement());

        /* special handling for private elements */
        if (privateCreatorCache && (newTag.getGroup() & 1) && (newTag.getElement() >= 0x1000))
        {
            const char *pc = privateCreatorCache->findPrivateCreator(newTag);
            if (pc != NULL)
            {
                // we have a private creator for this element
                newTag.setPrivateCreator(pc);
                newTag.lookupVRinDictionary();
            }
        }

        /* update VR for tag, set "readAsUN" flag that makes sure the element value
         * is read in Little Endian Implicit VR (i.e. the UN encoding)
         */
        if (newTag.getEVR() != EVR_UNKNOWN)
        {
            DCMDATA_DEBUG("DcmItem::newDicomElement() reverted VR of element " << tag
                << " from 'UN' to '" << newTag.getVRName() << "'");
            tag.setVR(newTag.getVR());
            evr = tag.getEVR();
            readAsUN = OFTrue;
        }
    }

    /* depending on the VR of the tag which was passed, create the new object */
    switch (evr)
    {
        // byte strings:
        case EVR_AE :
            newElement = new DcmApplicationEntity(tag, length);
            break;
        case EVR_AS :
            newElement = new DcmAgeString(tag, length);
            break;
        case EVR_CS :
            newElement = new DcmCodeString(tag, length);
            break;
        case EVR_DA :
            newElement = new DcmDate(tag, length);
            break;
        case EVR_DS :
            newElement = new DcmDecimalString(tag, length);
            break;
        case EVR_DT :
            newElement = new DcmDateTime(tag, length);
            break;
        case EVR_IS :
            newElement = new DcmIntegerString(tag, length);
            break;
        case EVR_TM :
            newElement = new DcmTime(tag, length);
            break;
        case EVR_UI :
            newElement = new DcmUniqueIdentifier(tag, length);
            break;
        case EVR_UR:
            newElement = new DcmUniversalResourceIdentifierOrLocator(tag, length);
            break;

        // character strings:
        case EVR_LO :
            newElement = new DcmLongString(tag, length);
            break;
        case EVR_LT :
            newElement = new DcmLongText(tag, length);
            break;
        case EVR_PN :
            newElement = new DcmPersonName(tag, length);
            break;
        case EVR_SH :
            newElement = new DcmShortString(tag, length);
            break;
        case EVR_ST :
            newElement = new DcmShortText(tag, length);
            break;
        case EVR_UC:
            newElement = new DcmUnlimitedCharacters(tag, length);
            break;
        case EVR_UT:
            newElement = new DcmUnlimitedText(tag, length);
            break;

        // dependent on byte order:
        case EVR_AT :
            newElement = new DcmAttributeTag(tag, length);
            break;
        case EVR_SS :
            newElement = new DcmSignedShort(tag, length);
            break;
        case EVR_xs : // according to DICOM standard
        case EVR_US :
            newElement = new DcmUnsignedShort(tag, length);
            break;
        case EVR_SL :
            newElement = new DcmSignedLong(tag, length);
            break;
        case EVR_up : // for (0004,eeee) according to DICOM standard
        case EVR_UL :
            {
                // generate tag with VR from dictionary!
                DcmTag ulupTag(tag.getTagKey());
                if (ulupTag.getEVR() == EVR_up)
                    newElement = new DcmUnsignedLongOffset(ulupTag, length);
                else
                    newElement = new DcmUnsignedLong(tag, length);
            }
            break;
        case EVR_OL :
            newElement = new DcmOtherLong(tag, length);
            break;
        case EVR_SV :
            newElement = new DcmSigned64bitVeryLong(tag, length);
            break;
        case EVR_UV :
            newElement = new DcmUnsigned64bitVeryLong(tag, length);
            break;
        case EVR_OV :
            newElement = new DcmOther64bitVeryLong(tag, length);
            break;
        case EVR_FL :
            newElement = new DcmFloatingPointSingle(tag, length);
            break;
        case EVR_FD :
            newElement = new DcmFloatingPointDouble(tag, length);
            break;
        case EVR_OF :
            newElement = new DcmOtherFloat(tag, length);
            break;
        case EVR_OD :
            newElement = new DcmOtherDouble(tag, length);
            break;

        // sequences and items:
        case EVR_SQ :
            newElement = new DcmSequenceOfItems(tag, length, readAsUN);
            break;
        case EVR_na :
            if (tag == DCM_Item)
                l_error = EC_InvalidTag;
            else if (tag == DCM_SequenceDelimitationItem)
                l_error = EC_SequEnd;
            else if (tag == DCM_ItemDelimitationItem)
                l_error = EC_ItemEnd;
            else
                l_error = EC_InvalidTag;
            break;

        // pixel sequences (EVR_pixelSQ) are handled through class DcmPixelData
        // and should never appear here.

        // unclear 8 or 16 bit:
        case EVR_ox :
            if (tag == DCM_PixelData)
                newElement = new DcmPixelData(tag, length);
            else if (tag.getBaseTag() == DCM_OverlayData)
                newElement = new DcmOverlayData(tag, length);
            else
                /* we don't know this element's real transfer syntax, so we just
                 * use the defaults of class DcmOtherByteOtherWord and let the
                 * application handle it.
                 */
                newElement = new DcmOtherByteOtherWord(tag, length);
            break;

        case EVR_px :
            newElement = new DcmPixelData(tag, length);
            break;

        // This case should only occur if we encounter an element with an invalid
        // "Pi" VR. Make sure this does not cause problems later on
        case EVR_PixelData :
            newElement = new DcmPixelData(tag, length);
            // set VR to OW to make sure that we never write/send the internal VR
            if (newElement) newElement->setVR(EVR_OW);
            break;

        // This case should only occur if we encounter an element with an invalid
        // "Ov" VR. Make sure this does not cause problems later on
        case EVR_OverlayData :
            newElement = new DcmOverlayData(tag, length);
            // set VR to OW to make sure that we never write/send the internal VR
            if (newElement) newElement->setVR(EVR_OW);
            break;

        case EVR_lt :
            newElement = new DcmOtherByteOtherWord(tag, length);
            break;

        case EVR_OB :
        case EVR_OW :
            if (tag == DCM_PixelData)
                newElement = new DcmPixelData(tag, length);
            else if (tag.getBaseTag() == DCM_OverlayData)
                newElement = new DcmOverlayData(tag, length);
            else if ((tag == DCM_VOILUTSequence) && (length != DCM_UndefinedLength))
            {
                // this is an incorrectly encoded VOI LUT Sequence.
                // Real-world examples of this issue have been reported in 2016.
                if (dcmConvertVOILUTSequenceOWtoSQ.get())
                {
                    // Silently fix the error by interpreting as a sequence.
                    DcmTag newTag(tag);
                    newTag.setVR(DcmVR(EVR_SQ)); // on writing we will handle this element as SQ, not OB/OW
                    newElement = new DcmSequenceOfItems(newTag, length);
                } else {

                    if (dcmIgnoreParsingErrors.get())
                    {
                        // ignore parse error, keep VR unchanged
                        DCMDATA_WARN("DcmItem: VOI LUT Sequence with VR=OW and explicit length encountered.");
                        newElement = new DcmOtherByteOtherWord(tag, length);
                    }
                    else
                    {
                        // bail out with an error
                        DCMDATA_ERROR("DcmItem: VOI LUT Sequence with VR=OW and explicit length encountered.");
                        l_error = EC_VOI_LUT_OBOW;
                    }
                }
            }
            else if (tag.isPrivate())
            {
                // look up VR in private data dictionary
                DcmTag newTag(tag.getTagKey(), tag.getPrivateCreator());
                // special handling for private pixel data (compressed or uncompressed)
                if (newTag.getEVR() == EVR_px)
                {
                    DCMDATA_WARN("Found private element " << tag << " with VR " << tag.getVRName()
                        << " and undefined length, reading a pixel sequence according to data dictionary");
                    newElement = new DcmPixelData(tag, length);
                }
            }
            // no element has been created yet and no error reported
            if ((newElement == NULL) && l_error.good())
            {
                if (length == DCM_UndefinedLength)
                {
                    // The attribute is OB or OW but is encoded with undefined
                    // length, and it is not Pixel Data. This is illegal.
                    if (dcmConvertUndefinedLengthOBOWtoSQ.get())
                    {
                        // Assume that this is in fact a sequence so that we can
                        // catch the sequence delimitation item.
                        DcmTag newTag(tag);
                        newTag.setVR(DcmVR(EVR_SQ)); // on writing we will handle this element as SQ, not OB/OW
                        newElement = new DcmSequenceOfItems(newTag, length);
                    } else {
                        if (dcmIgnoreParsingErrors.get())
                        {
                            // ignore parse error, keep VR unchanged
                            OFCondition tempcond = EC_UndefinedLengthOBOW;
                            DCMDATA_WARN("DcmItem: Parse error in " << tag << ": " << tempcond.text());
                            newElement = new DcmSequenceOfItems(tag, length);
                        } else {
                            // bail out with an error
                            l_error = EC_UndefinedLengthOBOW;
                            DCMDATA_ERROR("DcmItem: Parse error in " << tag << ": " << l_error.text());
                        }
                    }
                } else {
                    // default case
                    newElement = new DcmOtherByteOtherWord(tag, length);
                }
            }
            break;

        // read unknown types as byte string:
        case EVR_UNKNOWN :
        case EVR_UNKNOWN2B :
        case EVR_UN :
            if (length == DCM_UndefinedLength)
            {
                // The attribute VR is UN with undefined length. Assume it is really
                // a sequence so that we can catch the sequence delimitation item.
                DcmTag newTag(tag);
                newTag.setVR(DcmVR(EVR_SQ)); // on writing we will handle this element as SQ, not UN
                if (dcmEnableCP246Support.get())
                {
                    DCMDATA_WARN("Found element " << newTag << " with VR UN and undefined length, "
                        << "reading a sequence with transfer syntax LittleEndianImplicit (CP-246)");
                } else {
                    DCMDATA_WARN("Found element " << newTag << " with VR UN and undefined length");
                }
                newElement = new DcmSequenceOfItems(newTag, length, dcmEnableCP246Support.get());
            } else {
                // defined length UN element, treat like OB
                newElement = new DcmOtherByteOtherWord(tag, length);
            }
            break;

        // these types should never occur
        case EVR_item :
        case EVR_metainfo :
        case EVR_dataset :
        case EVR_fileFormat :
        case EVR_dicomDir :
        case EVR_dirRecord :
        case EVR_pixelSQ :
        case EVR_pixelItem :
        case EVR_invalid :
            l_error = EC_IllegalCall;
            break;

        // we deliberately have no default clause to make sure a warning is raised
        // when an DcmEVR enum is not explicitly handled here
    }

    /* check for valid element pointer */
    if (l_error.good() && (newElement == NULL))
        l_error = EC_MemoryExhausted;

    /* return result value */
    return l_error;
}