File: scu.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 (2746 lines) | stat: -rw-r--r-- 104,669 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
/*
 *
 *  Copyright (C) 2008-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:  dcmnet
 *
 *  Author:  Michael Onken
 *
 *  Purpose: Base class for Service Class Users (SCUs)
 *
 */

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

#include "dcmtk/dcmdata/dcostrmf.h" /* for class DcmOutputFileStream */
#include "dcmtk/dcmdata/dcuid.h"    /* for dcmFindUIDName() */
#include "dcmtk/dcmnet/diutil.h"    /* for dcmnet logger */
#include "dcmtk/dcmnet/scu.h"
#include "dcmtk/ofstd/ofmem.h" /* for OFunique_ptr */
#include "dcmtk/ofstd/ofstd.h"


#ifdef WITH_ZLIB
#include <zlib.h> /* for zlibVersion() */
#endif

DcmSCU::DcmSCU()
    : m_assoc(NULL)
    , m_net(NULL)
    , m_params(NULL)
    , m_assocConfigFilename()
    , m_assocConfigProfile()
    , m_presContexts()
    , m_assocConfigFile()
    , m_openDIMSERequest(NULL)
    , m_maxReceivePDULength(ASC_DEFAULTMAXPDU)
    , m_blockMode(DIMSE_BLOCKING)
    , m_ourAETitle("ANY-SCU")
    , m_peer()
    , m_peerAETitle("ANY-SCP")
    , m_peerPort(104)
    , m_dimseTimeout(0)
    , m_acseTimeout(30)
    , m_tcpConnectTimeout(dcmConnectionTimeout.get())
    , m_storageDir()
    , m_storageMode(DCMSCU_STORAGE_DISK)
    , m_verbosePCMode(OFFalse)
    , m_datasetConversionMode(OFFalse)
    , m_progressNotificationMode(OFTrue)
    , m_secureConnectionEnabled(OFFalse)
    , m_protocolVersion(ASC_AF_Default)
{
    OFStandard::initializeNetwork();
}

void DcmSCU::freeNetwork()
{
    if ((m_assoc != NULL) || (m_net != NULL) || (m_params != NULL))
        DCMNET_DEBUG("Cleaning up internal association and network structures");
    /* destroy association parameters, i.e. free memory of T_ASC_Parameters.
       Usually this is done in ASC_destroyAssociation; however, if we already
       have association parameters but not yet an association (e.g. after calling
       initNetwork() and negotiateAssociation()), the latter approach may fail.
    */
    if (m_params)
    {
        ASC_destroyAssociationParameters(&m_params);
        m_params = NULL;
        // make sure destroyAssociation does not try to free params a second time
        // (happens in case we have already have an association structure)
        if (m_assoc)
            m_assoc->params = NULL;
    }
    // destroy the association, i.e. free memory of T_ASC_Association* structure.
    ASC_destroyAssociation(&m_assoc);
    // drop the network, i.e. free memory of T_ASC_Network* structure.
    ASC_dropNetwork(&m_net);
    // Cleanup old DIMSE request if any
    delete m_openDIMSERequest;
    m_openDIMSERequest = NULL;
}

DcmSCU::~DcmSCU()
{
    // abort association (if any) and destroy dcmnet data structures
    if (isConnected())
    {
        closeAssociation(DCMSCU_ABORT_ASSOCIATION); // also frees network
    }
    else
    {
        freeNetwork();
    }

    OFStandard::shutdownNetwork();
}

OFCondition DcmSCU::initNetwork()
{
    /* Return if SCU is already connected */
    if (isConnected())
        return NET_EC_AlreadyConnected;

    /* Be sure internal network structures are clean (delete old) */
    freeNetwork();

    OFString tempStr;
    /* initialize network, i.e. create an instance of T_ASC_Network*. */
    OFCondition cond = ASC_initializeNetwork(NET_REQUESTOR, 0, m_acseTimeout, &m_net);
    if (cond.bad())
    {
        DimseCondition::dump(tempStr, cond);
        DCMNET_ERROR(tempStr);
        return cond;
    }

    /* initialize association parameters, i.e. create an instance of T_ASC_Parameters*. */
    cond = ASC_createAssociationParameters(&m_params, m_maxReceivePDULength, m_tcpConnectTimeout);
    if (cond.bad())
    {
        DCMNET_ERROR(DimseCondition::dump(tempStr, cond));
        return cond;
    }

    /* sets this application's title and the called application's title in the params */
    /* structure. The default values are "ANY-SCU" and "ANY-SCP". */
    ASC_setAPTitles(m_params, m_ourAETitle.c_str(), m_peerAETitle.c_str(), NULL);

    /* sets the IP protocol version */
    ASC_setProtocolFamily(m_params, m_protocolVersion);

    /* Figure out the presentation addresses and copy the */
    /* corresponding values into the association parameters.*/
    DIC_NODENAME peerHost;
    const OFString localHost = OFStandard::getHostName();
    /* Since the underlying dcmnet structures reserve only 64 bytes for peer
       as well as local host name, we check here for buffer overflow.
     */
    if ((m_peer.length() + 5 /* max 65535 */) + 1 /* for ":" */ > 63)
    {
        DCMNET_ERROR("Maximum length of peer host name '" << m_peer << "' is longer than maximum of 57 characters");
        return EC_IllegalCall; // TODO: need to find better error code
    }
    if (localHost.size() + 1 > 63)
    {
        DCMNET_ERROR("Maximum length of local host name '" << localHost << "' is longer than maximum of 62 characters");
        return EC_IllegalCall; // TODO: need to find better error code
    }
    OFStandard::snprintf(peerHost, sizeof(peerHost), "%s:%d", m_peer.c_str(), OFstatic_cast(int, m_peerPort));
    ASC_setPresentationAddresses(m_params, localHost.c_str(), peerHost);

    /* Add presentation contexts */

    // First, import from config file, if specified
    OFCondition result;
    if (!m_assocConfigFilename.empty())
    {
        DcmAssociationConfiguration assocConfig;
        result = DcmAssociationConfigurationFile::initialize(assocConfig, m_assocConfigFilename.c_str(), OFTrue);
        if (result.bad())
        {
            DCMNET_WARN("Unable to parse association configuration file " << m_assocConfigFilename
                                                                          << " (ignored): " << result.text());
            return result;
        }
        else
        {
            /* perform name mangling for config file key */
            OFString profileName;
            const unsigned char* c = OFreinterpret_cast(const unsigned char*, m_assocConfigProfile.c_str());
            while (*c)
            {
                if (!OFStandard::isspace(*c))
                    profileName += OFstatic_cast(char, toupper(*c));
                ++c;
            }

            result = assocConfig.setAssociationParameters(profileName.c_str(), *m_params);
            if (result.bad())
            {
                DCMNET_WARN("Unable to apply association configuration file " << m_assocConfigFilename
                                                                              << " (ignored): " << result.text());
                return result;
            }
        }
    }

    // Adapt presentation context ID to existing presentation contexts.
    // It's important that presentation context IDs are numerated 1,3,5,7...!
    Uint32 nextFreePresID = 257;
    Uint32 numContexts    = ASC_countPresentationContexts(m_params);
    if (numContexts <= 127)
    {
        // Need Uint16 to avoid overflow in currPresID (unsigned char)
        nextFreePresID = 2 * numContexts + 1; /* add 1 to point to the next free ID*/
    }
    // Print warning if number of overall presentation contexts exceeds 128
    if ((numContexts + m_presContexts.size()) > 128)
    {
        DCMNET_WARN("Number of presentation contexts exceeds 128 (" << numContexts + m_presContexts.size()
                                                                    << "). Some contexts will not be negotiated");
    }
    else
    {
        DCMNET_TRACE("Configured " << numContexts << " presentation contexts from config file");
        if (m_presContexts.size() > 0)
            DCMNET_TRACE("Adding another " << m_presContexts.size() << " presentation contexts configured for SCU");
    }

    // Add presentation contexts not originating from config file
    OFListIterator(DcmSCUPresContext) contIt             = m_presContexts.begin();
    OFListConstIterator(DcmSCUPresContext) endOfContList = m_presContexts.end();
    while ((contIt != endOfContList) && (nextFreePresID <= 255))
    {
        const Uint16 numTransferSyntaxes = OFstatic_cast(Uint16, (*contIt).transferSyntaxes.size());
        const char** transferSyntaxes    = new const char*[numTransferSyntaxes];

        // Iterate over transfer syntaxes within one presentation context
        OFListIterator(OFString) syntaxIt        = (*contIt).transferSyntaxes.begin();
        OFListIterator(OFString) endOfSyntaxList = (*contIt).transferSyntaxes.end();
        Uint16 sNum                              = 0;
        // copy all transfer syntaxes to array
        while (syntaxIt != endOfSyntaxList)
        {
            transferSyntaxes[sNum] = (*syntaxIt).c_str();
            ++syntaxIt;
            ++sNum;
        }

        // add the presentation context
        cond = ASC_addPresentationContext(m_params,
                                          OFstatic_cast(Uint8, nextFreePresID),
                                          (*contIt).abstractSyntaxName.c_str(),
                                          transferSyntaxes,
                                          numTransferSyntaxes,
                                          (*contIt).roleSelect);
        // if adding was successful, prepare presentation context ID for next addition
        delete[] transferSyntaxes;
        transferSyntaxes = NULL;
        if (cond.bad())
            return cond;
        contIt++;
        // goto next free number, only odd presentation context IDs permitted
        nextFreePresID += 2;
    }

    numContexts = ASC_countPresentationContexts(m_params);
    if (numContexts == 0)
    {
        DCMNET_ERROR("Cannot initialize network: No presentation contexts defined");
        return NET_EC_NoPresentationContextsDefined;
    }
    DCMNET_DEBUG("Configured a total of " << numContexts << " presentation contexts for SCU");

    return cond;
}

OFCondition DcmSCU::negotiateAssociation()
{
    /* Return error if SCU is already connected */
    if (isConnected())
        return NET_EC_AlreadyConnected;

    /* dump presentation contexts if required */
    OFString tempStr;
    if (m_verbosePCMode)
        DCMNET_INFO("Request Parameters:" << OFendl << ASC_dumpParameters(tempStr, m_params, ASC_ASSOC_RQ));
    else
        DCMNET_DEBUG("Request Parameters:" << OFendl << ASC_dumpParameters(tempStr, m_params, ASC_ASSOC_RQ));

    /* create association, i.e. try to establish a network connection to another */
    /* DICOM application. This call creates an instance of T_ASC_Association*. */
    DCMNET_INFO("Requesting Association");
    OFCondition cond = ASC_requestAssociation(m_net, m_params, &m_assoc);
    if (cond.bad())
    {
        if (cond == DUL_ASSOCIATIONREJECTED)
        {
            T_ASC_RejectParameters rej;
            ASC_getRejectParameters(m_params, &rej);
            DCMNET_DEBUG("Association Rejected:" << OFendl << ASC_printRejectParameters(tempStr, &rej));
            return cond;
        }
        else
        {
            DCMNET_DEBUG("Association Request Failed: " << DimseCondition::dump(tempStr, cond));
            return cond;
        }
    }

    /* dump the presentation contexts which have been accepted/refused */
    if (m_verbosePCMode)
        DCMNET_INFO("Association Parameters Negotiated:" << OFendl
                                                         << ASC_dumpParameters(tempStr, m_params, ASC_ASSOC_AC));
    else
        DCMNET_DEBUG("Association Parameters Negotiated:" << OFendl
                                                          << ASC_dumpParameters(tempStr, m_params, ASC_ASSOC_AC));

    /* count the presentation contexts which have been accepted by the SCP */
    /* If there are none, finish the execution */
    if (ASC_countAcceptedPresentationContexts(m_params) == 0)
    {
        DCMNET_ERROR("No Acceptable Presentation Contexts");
        return NET_EC_NoAcceptablePresentationContexts;
    }

    /* dump general information concerning the establishment of the network connection if required */
    DCMNET_INFO("Association Accepted (Max Send PDV: " << OFstatic_cast(unsigned long, m_assoc->sendPDVLength) << ")");
    return EC_Normal;
}

OFCondition DcmSCU::addPresentationContext(const OFString& abstractSyntax,
                                           const OFList<OFString>& xferSyntaxes,
                                           const T_ASC_SC_ROLE role)

{

    DcmSCUPresContext presContext;
    presContext.abstractSyntaxName          = abstractSyntax;
    OFListConstIterator(OFString) it        = xferSyntaxes.begin();
    OFListConstIterator(OFString) endOfList = xferSyntaxes.end();
    while (it != endOfList)
    {
        presContext.transferSyntaxes.push_back(*it);
        it++;
    }
    presContext.roleSelect = role;
    m_presContexts.push_back(presContext);
    return EC_Normal;
}

OFCondition DcmSCU::useSecureConnection(DcmTransportLayer* tlayer)
{
    OFCondition cond = ASC_setTransportLayer(m_net, tlayer, OFFalse /* do not take over ownership */);
    if (cond.good())
        cond = ASC_setTransportLayerType(m_params, OFTrue /* use TLS */);

    if (cond.good()) m_secureConnectionEnabled = OFTrue;
    return cond;
}

void DcmSCU::clearPresentationContexts()
{
    m_presContexts.clear();
    m_assocConfigFilename.clear();
    m_assocConfigProfile.clear();
}

// Returns usable presentation context ID for a given abstract syntax UID and
// transfer syntax UID. 0 if none matches.
T_ASC_PresentationContextID DcmSCU::findPresentationContextID(const OFString& abstractSyntax,
                                                              const OFString& transferSyntax,
                                                              const T_ASC_SC_ROLE requestorRole)
{
    if (!isConnected())
        return 0;

    DUL_PRESENTATIONCONTEXT* pc;
    LST_HEAD** l;
    OFBool found = OFFalse;

    if (abstractSyntax.empty())
        return 0;

    /* first of all we look for a presentation context
     * matching both abstract and transfer syntax
     */
    l  = &m_assoc->params->DULparams.acceptedPresentationContext;
    pc = (DUL_PRESENTATIONCONTEXT*)LST_Head(l);
    (void)LST_Position(l, (LST_NODE*)pc);
    while (pc && !found)
    {
        found = (strcmp(pc->abstractSyntax, abstractSyntax.c_str()) == 0);
        found &= (pc->result == ASC_P_ACCEPTANCE);
        if (!transferSyntax.empty()) // ignore transfer syntax if not specified
            found &= (strcmp(pc->acceptedTransferSyntax, transferSyntax.c_str()) == 0);
        if (found)
            found &= pc->acceptedSCRole == ascRole2dulRole(requestorRole);
        if (!found)
            pc = (DUL_PRESENTATIONCONTEXT*)LST_Next(l);
    }
    if (found)
        return pc->presentationContextID;

    return 0; /* not found */
}

// Returns the presentation context ID that best matches the given abstract syntax UID and
// transfer syntax UID.
T_ASC_PresentationContextID DcmSCU::findAnyPresentationContextID(const OFString& abstractSyntax,
                                                                 const OFString& transferSyntax)
{
    if (m_assoc == NULL)
        return 0;

    DUL_PRESENTATIONCONTEXT* pc;
    LST_HEAD** l;
    OFBool found = OFFalse;

    if (abstractSyntax.empty())
        return 0;

    /* first of all we look for a presentation context
     * matching both abstract and transfer syntax
     */
    l  = &m_assoc->params->DULparams.acceptedPresentationContext;
    pc = (DUL_PRESENTATIONCONTEXT*)LST_Head(l);
    (void)LST_Position(l, (LST_NODE*)pc);
    while (pc && !found)
    {
        found = (strcmp(pc->abstractSyntax, abstractSyntax.c_str()) == 0);
        found &= (pc->result == ASC_P_ACCEPTANCE);
        if (!transferSyntax.empty()) // ignore transfer syntax if not specified
            found &= (strcmp(pc->acceptedTransferSyntax, transferSyntax.c_str()) == 0);
        if (!found)
            pc = (DUL_PRESENTATIONCONTEXT*)LST_Next(l);
    }
    if (found)
        return pc->presentationContextID;

    /* now we look for an explicit VR uncompressed PC. */
    l  = &m_assoc->params->DULparams.acceptedPresentationContext;
    pc = (DUL_PRESENTATIONCONTEXT*)LST_Head(l);
    (void)LST_Position(l, (LST_NODE*)pc);
    while (pc && !found)
    {
        found = (strcmp(pc->abstractSyntax, abstractSyntax.c_str()) == 0) && (pc->result == ASC_P_ACCEPTANCE)
            && ((strcmp(pc->acceptedTransferSyntax, UID_LittleEndianExplicitTransferSyntax) == 0)
                || (strcmp(pc->acceptedTransferSyntax, UID_BigEndianExplicitTransferSyntax) == 0));
        if (!found)
            pc = (DUL_PRESENTATIONCONTEXT*)LST_Next(l);
    }
    if (found)
        return pc->presentationContextID;

    /* now we look for an implicit VR uncompressed PC. */
    l  = &m_assoc->params->DULparams.acceptedPresentationContext;
    pc = (DUL_PRESENTATIONCONTEXT*)LST_Head(l);
    (void)LST_Position(l, (LST_NODE*)pc);
    while (pc && !found)
    {
        found = (strcmp(pc->abstractSyntax, abstractSyntax.c_str()) == 0) && (pc->result == ASC_P_ACCEPTANCE)
            && (strcmp(pc->acceptedTransferSyntax, UID_LittleEndianImplicitTransferSyntax) == 0);
        if (!found)
            pc = (DUL_PRESENTATIONCONTEXT*)LST_Next(l);
    }
    if (found)
        return pc->presentationContextID;

    /* finally we accept everything we get.
       returns 0 if abstract syntax is not supported
    */
    return ASC_findAcceptedPresentationContextID(m_assoc, abstractSyntax.c_str());
}

void DcmSCU::findPresentationContext(const T_ASC_PresentationContextID presID,
                                     OFString& abstractSyntax,
                                     OFString& transferSyntax)
{
    transferSyntax.clear();
    abstractSyntax.clear();
    if (m_assoc == NULL)
        return;

    DUL_PRESENTATIONCONTEXT* pc;
    LST_HEAD** l;

    /* we look for a presentation context matching
     * both abstract and transfer syntax
     */
    l  = &m_assoc->params->DULparams.acceptedPresentationContext;
    pc = (DUL_PRESENTATIONCONTEXT*)LST_Head(l);
    (void)LST_Position(l, (LST_NODE*)pc);
    while (pc)
    {
        if (presID == pc->presentationContextID)
        {
            if (pc->result == ASC_P_ACCEPTANCE)
            {
                // found a match
                transferSyntax = pc->acceptedTransferSyntax;
                abstractSyntax = pc->abstractSyntax;
            }
            break;
        }
        pc = (DUL_PRESENTATIONCONTEXT*)LST_Next(l);
    }
}

Uint16 DcmSCU::nextMessageID()
{
    if (!isConnected())
        return 0;
    else
        return m_assoc->nextMsgID++;
}

void DcmSCU::closeAssociation(const DcmCloseAssociationType closeType)
{
    if (!isConnected())
    {
        DCMNET_WARN("Closing of association requested but no association active (ignored)");
        return;
    }

    OFCondition cond;
    OFString tempStr;

    /* tear down association, i.e. terminate network connection to SCP */
    switch (closeType)
    {
        case DCMSCU_RELEASE_ASSOCIATION:
            /* release association */
            DCMNET_INFO("Releasing Association");
            cond = ASC_releaseAssociation(m_assoc);
            if (cond.bad())
            {
                DCMNET_ERROR("Association Release Failed: " << DimseCondition::dump(tempStr, cond));
                return; // TODO: do we really need this?
            }
            break;
        case DCMSCU_ABORT_ASSOCIATION:
            /* abort association */
            DCMNET_INFO("Aborting Association");
            cond = ASC_abortAssociation(m_assoc);
            if (cond.bad())
            {
                DCMNET_ERROR("Association Abort Failed: " << DimseCondition::dump(tempStr, cond));
            }
            break;
        case DCMSCU_PEER_REQUESTED_RELEASE:
            /* peer requested release */
            DCMNET_ERROR("Protocol Error: Peer requested release (Aborting)");
            DCMNET_INFO("Aborting Association");
            cond = ASC_abortAssociation(m_assoc);
            if (cond.bad())
            {
                DCMNET_ERROR("Association Abort Failed: " << DimseCondition::dump(tempStr, cond));
            }
            break;
        case DCMSCU_PEER_ABORTED_ASSOCIATION:
            /* peer aborted association */
            DCMNET_INFO("Peer Aborted Association");
            break;
    }

    // destroy and free memory of internal association and network structures
    freeNetwork();
}

OFCondition DcmSCU::releaseAssociation()
{
    OFCondition status = DIMSE_ILLEGALASSOCIATION;
    // check whether there is an active association
    if (isConnected())
    {
        closeAssociation(DCMSCU_RELEASE_ASSOCIATION);
        status = EC_Normal;
    }
    return status;
}

OFCondition DcmSCU::abortAssociation()
{
    OFCondition status = DIMSE_ILLEGALASSOCIATION;
    // check whether there is an active association
    if (isConnected())
    {
        closeAssociation(DCMSCU_ABORT_ASSOCIATION);
        status = EC_Normal;
    }
    return status;
}

/* ************************************************************************* */
/*                            C-ECHO functionality                           */
/* ************************************************************************* */

// Sends C-ECHO request to another DICOM application
OFCondition DcmSCU::sendECHORequest(const T_ASC_PresentationContextID presID)
{
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;

    OFCondition cond;
    T_ASC_PresentationContextID pcid = presID;

    /* If necessary, find appropriate presentation context */
    if (pcid == 0)
        pcid = findPresentationContextID(UID_VerificationSOPClass, UID_LittleEndianExplicitTransferSyntax);
    if (pcid == 0)
        pcid = findPresentationContextID(UID_VerificationSOPClass, UID_BigEndianExplicitTransferSyntax);
    if (pcid == 0)
        pcid = findPresentationContextID(UID_VerificationSOPClass, UID_LittleEndianImplicitTransferSyntax);
    if (pcid == 0)
    {
        DCMNET_ERROR("No valid presentation context found for sending C-ECHO using SOP Class: "
                     << dcmFindNameOfUID(UID_VerificationSOPClass, ""));
        return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
    }

    /* Now, assemble DIMSE message */
    T_DIMSE_Message msg;
    // Make sure everything is zeroed (especially options)
    memset((char*)&msg, 0, sizeof(msg));
    T_DIMSE_C_EchoRQ* req = &(msg.msg.CEchoRQ);
    // Set type of message
    msg.CommandField = DIMSE_C_ECHO_RQ;
    // Set message ID
    req->MessageID = nextMessageID();
    // Announce no dataset
    req->DataSetType = DIMSE_DATASET_NULL;
    // Set affected SOP Class UID (always Verification SOP Class)
    OFStandard::strlcpy(req->AffectedSOPClassUID, UID_VerificationSOPClass, sizeof(req->AffectedSOPClassUID));

    /* Send request */
    OFString tempStr;
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending C-ECHO Request");
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, msg, DIMSE_OUTGOING, NULL, pcid));
    }
    else
    {
        DCMNET_INFO("Sending C-ECHO Request (MsgID " << req->MessageID << ")");
    }
    cond = sendDIMSEMessage(pcid, &msg, NULL /*dataObject*/);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed sending C-ECHO request: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }

    /* Receive response */
    T_DIMSE_Message rsp;
    // Make sure everything is zeroed (especially options)
    memset((char*)&rsp, 0, sizeof(rsp));

    DcmDataset* statusDetail = NULL;
    cond = receiveDIMSECommand(&pcid, &rsp, &statusDetail, NULL /* not interested in the command set */);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed receiving DIMSE response: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }
    /* Check whether we received C-ECHO response, otherwise print error */
    if (rsp.CommandField == DIMSE_C_ECHO_RSP)
    {
        if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
        {
            DCMNET_INFO("Received C-ECHO Response");
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
        }
        else
        {
            DCMNET_INFO("Received C-ECHO Response (" << DU_cechoStatusString(rsp.msg.CEchoRSP.DimseStatus) << ")");
        }
    }
    else
    {
        DCMNET_ERROR("Expected C-ECHO response but received DIMSE command 0x"
                     << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
                     << OFstatic_cast(unsigned int, rsp.CommandField));
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
        delete statusDetail;
        return DIMSE_BADCOMMANDTYPE;
    }
    /* Print status detail if it was received */
    if (statusDetail != NULL)
    {
        DCMNET_DEBUG("Response has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
        delete statusDetail;
    }
    return EC_Normal;
}

/* ************************************************************************* */
/*                            C-STORE functionality                          */
/* ************************************************************************* */

// Sends C-STORE request to another DICOM application
OFCondition DcmSCU::sendSTORERequest(const T_ASC_PresentationContextID presID,
                                     const OFFilename& dicomFile,
                                     DcmDataset* dataset,
                                     Uint16& rspStatusCode,
                                     const OFString& moveOriginatorAETitle,
                                     const Uint16 moveOriginatorMsgID)
{
    // Do some basic validity checks
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;

    OFCondition cond;
    OFString tempStr;
    T_ASC_PresentationContextID pcid = presID;
    DcmDataset* statusDetail         = NULL;
    T_DIMSE_Message msg;
    // Make sure everything is zeroed (especially options)
    memset((char*)&msg, 0, sizeof(msg));
    T_DIMSE_C_StoreRQ* req = &(msg.msg.CStoreRQ);

    // Set type of message
    msg.CommandField = DIMSE_C_STORE_RQ;
    /* Set message ID */
    req->MessageID = nextMessageID();
    /* Load file if necessary */
    DcmFileFormat* fileformat = NULL;
    if (!dicomFile.isEmpty())
    {
        fileformat = new DcmFileFormat();
        if (fileformat == NULL)
            return EC_MemoryExhausted;
        cond = fileformat->loadFile(dicomFile);
        if (cond.bad())
        {
            delete fileformat;
            return cond;
        }
        dataset = fileformat->getDataset();
    }

    /* Fill message according to dataset to be sent */
    OFString sopClassUID;
    OFString sopInstanceUID;
    E_TransferSyntax xferSyntax = EXS_Unknown;
    cond                        = getDatasetInfo(dataset, sopClassUID, sopInstanceUID, xferSyntax);
    DcmXfer xfer(xferSyntax);
    /* Check whether the information is sufficient */
    if (sopClassUID.empty() || sopInstanceUID.empty() || ((pcid == 0) && (xferSyntax == EXS_Unknown)))
    {
        DCMNET_ERROR("Cannot send SOP instance, missing information:");
        if (!dicomFile.isEmpty())
            DCMNET_ERROR("  DICOM Filename   : " << dicomFile);
        DCMNET_ERROR("  SOP Class UID    : " << sopClassUID);
        DCMNET_ERROR("  SOP Instance UID : " << sopInstanceUID);
        DCMNET_ERROR("  Transfer Syntax  : " << xfer.getXferName());
        if (pcid == 0)
            DCMNET_ERROR("  Pres. Context ID : 0 (find via SOP Class and Transfer Syntax)");
        else
            DCMNET_ERROR("  Pres. Context ID : " << OFstatic_cast(unsigned int, pcid));
        delete fileformat;
        return cond;
    }
    OFStandard::strlcpy(req->AffectedSOPClassUID, sopClassUID.c_str(), sizeof(req->AffectedSOPClassUID));
    OFStandard::strlcpy(req->AffectedSOPInstanceUID, sopInstanceUID.c_str(), sizeof(req->AffectedSOPInstanceUID));
    req->DataSetType = DIMSE_DATASET_PRESENT;
    req->Priority    = DIMSE_PRIORITY_MEDIUM;

    /* If desired (optional), insert MOVE originator information if this C-STORE
       was initiated through a C-MOVE request.
     */
    if (!moveOriginatorAETitle.empty())
    {
        OFStandard::strlcpy(req->MoveOriginatorApplicationEntityTitle,
                            moveOriginatorAETitle.c_str(),
                            sizeof(req->MoveOriginatorApplicationEntityTitle));
        req->opts |= O_STORE_MOVEORIGINATORAETITLE;
    }
    if (moveOriginatorMsgID != 0)
    {
        req->MoveOriginatorID = moveOriginatorMsgID;
        req->opts |= O_STORE_MOVEORIGINATORID;
    }

    /* If no presentation context is specified by the caller ... */
    if (pcid == 0)
    {
        /* ... try to find an appropriate presentation context automatically */
        pcid = findPresentationContextID(sopClassUID, xfer.getXferID());
    }
    else if (m_datasetConversionMode)
    {
        /* Convert dataset to network transfer syntax (if required) */
        OFString abstractSyntax, transferSyntax;
        findPresentationContext(pcid, abstractSyntax, transferSyntax);
        /* Check whether given presentation context was accepted by the peer */
        if (abstractSyntax.empty() || transferSyntax.empty())
        {
            /* Mark presentation context as invalid */
            pcid = 0;
        }
        else
        {
            if (abstractSyntax != sopClassUID)
            {
                DCMNET_WARN("Inappropriate presentation context with ID "
                            << OFstatic_cast(unsigned int, pcid) << ": abstract syntax does not match SOP class UID");
            }
            /* Try to convert to the negotiated transfer syntax */
            DcmXfer netXfer(transferSyntax.c_str());
            if (netXfer != xferSyntax)
            {
                DCMNET_INFO("Converting transfer syntax: " << xfer.getXferName() << " -> " << netXfer.getXferName());
                cond = dataset->chooseRepresentation(netXfer.getXfer(), NULL);
                if (cond.bad())
                {
                    DCMNET_ERROR("No conversion to transfer syntax " << netXfer.getXferName() << " possible!");
                    delete fileformat;
                    return cond;
                }
            }
        }
    }
    /* No appropriate presentation context for sending */
    if (pcid == 0)
    {
        OFString sopClassName = dcmFindNameOfUID(sopClassUID.c_str(), sopClassUID.c_str());
        OFString xferName     = xfer.getXferName();
        DCMNET_ERROR("No presentation context found for sending C-STORE with SOP Class / Transfer Syntax: "
                     << sopClassName << " / " << xferName);
        delete fileformat;
        return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
    }

    /* Send request */
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending C-STORE Request");
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, msg, DIMSE_OUTGOING, NULL, pcid));
    }
    else
    {
        DCMNET_INFO("Sending C-STORE Request (MsgID " << req->MessageID << ", "
                                                      << dcmSOPClassUIDToModality(sopClassUID.c_str(), "OT") << ")");
    }
    cond = sendDIMSEMessage(pcid, &msg, dataset);
    delete fileformat;
    fileformat = NULL;
    if (cond.bad())
    {
        DCMNET_ERROR("Failed sending C-STORE request: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }

    /* Receive response */
    T_DIMSE_Message rsp;
    // Make sure everything is zeroed (especially options)
    memset((char*)&rsp, 0, sizeof(rsp));
    cond = receiveDIMSECommand(&pcid, &rsp, &statusDetail, NULL /* not interested in the command set */);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed receiving DIMSE response: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }

    if (rsp.CommandField == DIMSE_C_STORE_RSP)
    {
        if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
        {
            DCMNET_INFO("Received C-STORE Response");
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
        }
        else
        {
            DCMNET_INFO("Received C-STORE Response (" << DU_cstoreStatusString(rsp.msg.CStoreRSP.DimseStatus) << ")");
        }
    }
    else
    {
        DCMNET_ERROR("Expected C-STORE response but received DIMSE command 0x"
                     << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
                     << OFstatic_cast(unsigned int, rsp.CommandField));
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
        delete statusDetail;
        return DIMSE_BADCOMMANDTYPE;
    }
    T_DIMSE_C_StoreRSP storeRsp = rsp.msg.CStoreRSP;
    rspStatusCode               = storeRsp.DimseStatus;
    if (statusDetail != NULL)
    {
        DCMNET_DEBUG("Response has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
        delete statusDetail;
    }

    return cond;
}

/* ************************************************************************* */
/*                            C-MOVE functionality                           */
/* ************************************************************************* */

// Sends a C-MOVE Request on given presentation context
OFCondition DcmSCU::sendMOVERequest(const T_ASC_PresentationContextID presID,
                                    const OFString& moveDestinationAETitle,
                                    DcmDataset* dataset,
                                    OFList<RetrieveResponse*>* responses)
{
    // Do some basic validity checks
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;
    if (dataset == NULL)
        return DIMSE_NULLKEY;

    /* Prepare DIMSE data structures for issuing request */
    OFCondition cond;
    OFString tempStr;
    T_ASC_PresentationContextID pcid = presID;
    T_DIMSE_Message msg;
    // make sure everything is zeroed (especially options)
    memset((char*)&msg, 0, sizeof(msg));
    DcmDataset* statusDetail = NULL;
    T_DIMSE_C_MoveRQ* req    = &(msg.msg.CMoveRQ);
    // Set type of message
    msg.CommandField = DIMSE_C_MOVE_RQ;
    // Set message ID
    req->MessageID = nextMessageID();
    // Announce dataset
    req->DataSetType = DIMSE_DATASET_PRESENT;
    // Set target for embedded C-Store's
    OFStandard::strlcpy(req->MoveDestination, moveDestinationAETitle.c_str(), sizeof(req->MoveDestination));
    // Set priority (mandatory)
    req->Priority = DIMSE_PRIORITY_MEDIUM;

    /* Determine SOP Class from presentation context */
    OFString abstractSyntax, transferSyntax;
    findPresentationContext(pcid, abstractSyntax, transferSyntax);
    if (abstractSyntax.empty() || transferSyntax.empty())
        return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
    OFStandard::strlcpy(req->AffectedSOPClassUID, abstractSyntax.c_str(), sizeof(req->AffectedSOPClassUID));

    /* Send request */
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending C-MOVE Request");
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, msg, DIMSE_OUTGOING, dataset, pcid));
    }
    else
    {
        DCMNET_INFO("Sending C-MOVE Request (MsgID " << req->MessageID << ")");
    }
    cond = sendDIMSEMessage(pcid, &msg, dataset);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed sending C-MOVE request: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }

    /* Receive and handle C-MOVE response messages */
    OFBool waitForNextResponse = OFTrue;
    while (waitForNextResponse)
    {
        T_DIMSE_Message rsp;
        // Make sure everything is zeroed, especially options
        memset((char*)&rsp, 0, sizeof(rsp));
        statusDetail = NULL;

        // Receive command set
        cond = receiveDIMSECommand(&pcid, &rsp, &statusDetail, NULL /* not interested in the command set */);
        if (cond.bad())
        {
            DCMNET_ERROR("Failed receiving DIMSE response: " << DimseCondition::dump(tempStr, cond));
            delete statusDetail;
            break;
        }

        if (rsp.CommandField == DIMSE_C_MOVE_RSP)
        {
            if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
            {
                DCMNET_INFO("Received C-MOVE Response");
                DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
            }
            else
            {
                DCMNET_INFO("Received C-MOVE Response (" << DU_cmoveStatusString(rsp.msg.CMoveRSP.DimseStatus) << ")");
            }
        }
        else
        {
            DCMNET_ERROR("Expected C-MOVE response but received DIMSE command 0x"
                         << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
                         << OFstatic_cast(unsigned int, rsp.CommandField));
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
            delete statusDetail;
            cond = DIMSE_BADCOMMANDTYPE;
            break;
        }

        // Prepare response package for response handler
        OFunique_ptr<RetrieveResponse> moveRSP(new RetrieveResponse);
        moveRSP->m_affectedSOPClassUID     = rsp.msg.CMoveRSP.AffectedSOPClassUID;
        moveRSP->m_messageIDRespondedTo    = rsp.msg.CMoveRSP.MessageIDBeingRespondedTo;
        moveRSP->m_status                  = rsp.msg.CMoveRSP.DimseStatus;
        moveRSP->m_numberOfRemainingSubops = rsp.msg.CMoveRSP.NumberOfRemainingSubOperations;
        moveRSP->m_numberOfCompletedSubops = rsp.msg.CMoveRSP.NumberOfCompletedSubOperations;
        moveRSP->m_numberOfFailedSubops    = rsp.msg.CMoveRSP.NumberOfFailedSubOperations;
        moveRSP->m_numberOfWarningSubops   = rsp.msg.CMoveRSP.NumberOfWarningSubOperations;
        moveRSP->m_statusDetail            = statusDetail;
        // DCMNET_DEBUG("C-MOVE response has status 0x"
        //  << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
        //  << moveRSP->m_status);
        if (statusDetail != NULL)
        {
            DCMNET_DEBUG("Response has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
        }

        // Receive dataset if there is one (status PENDING)
        DcmDataset* rspDataset = NULL;
        // Check if dataset is announced correctly
        if (rsp.msg.CMoveRSP.DataSetType != DIMSE_DATASET_NULL) // Some of the sub operations have failed, thus a
                                                                // dataset with a list of them is attached
        {
            // Receive dataset
            cond = receiveDIMSEDataset(&pcid, &rspDataset);
            if (cond.bad())
            {
                DCMNET_ERROR("Unable to receive C-MOVE dataset on presentation context "
                             << OFstatic_cast(unsigned int, pcid) << ": " << DimseCondition::dump(tempStr, cond));
                break;
            }
            moveRSP->m_dataset = rspDataset;
        }

        // Handle C-MOVE response (has to handle all possible status flags)
        cond = handleMOVEResponse(pcid, moveRSP.get(), waitForNextResponse);
        if (cond.bad())
        {
            DCMNET_WARN("Unable to handle C-MOVE response correctly: " << cond.text() << " (ignored)");
            // don't return here but trust the "waitForNextResponse" variable
        }
        // if response could be handled successfully, add it to response list
        else
        {
            if (responses != NULL) // only add if desired by caller
                responses->push_back(moveRSP.release());
        }
    }
    /* All responses received or break signal occurred */
    return cond;
}

// Standard handler for C-MOVE message responses
OFCondition DcmSCU::handleMOVEResponse(const T_ASC_PresentationContextID /* presID */,
                                       RetrieveResponse* response,
                                       OFBool& waitForNextResponse)
{
    waitForNextResponse = OFFalse;
    if (response == NULL)
        return DIMSE_NULLKEY;

    DCMNET_DEBUG("Handling C-MOVE Response");
    OFString s;
    s = DU_cmoveStatusString(response->m_status);
    return handleSessionResponseDefault(response->m_status, s, waitForNextResponse);
}

/* ************************************************************************* */
/*               C-GET and accompanying C-STORE functionality                */
/* ************************************************************************* */

// Sends a C-GET Request on given presentation context
OFCondition DcmSCU::sendCGETRequest(const T_ASC_PresentationContextID presID,
                                    DcmDataset* dataset,
                                    OFList<RetrieveResponse*>* responses)
{
    // Do some basic validity checks
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;
    if (dataset == NULL)
        return DIMSE_NULLKEY;

    /* Prepare DIMSE data structures for issuing request */
    OFCondition cond;
    OFString tempStr;
    T_ASC_PresentationContextID pcid = presID;
    T_DIMSE_Message msg;
    // Make sure everything is zeroed (especially options)
    memset((char*)&msg, 0, sizeof(msg));
    T_DIMSE_C_GetRQ* req = &(msg.msg.CGetRQ);
    // Set type of message
    msg.CommandField = DIMSE_C_GET_RQ;
    // Set message ID
    req->MessageID = nextMessageID();
    // Announce dataset
    req->DataSetType = DIMSE_DATASET_PRESENT;
    // Specify priority
    req->Priority = DIMSE_PRIORITY_MEDIUM;

    // Determine SOP Class from presentation context
    OFString abstractSyntax, transferSyntax;
    findPresentationContext(pcid, abstractSyntax, transferSyntax);
    if (abstractSyntax.empty() || transferSyntax.empty())
        return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
    OFStandard::strlcpy(req->AffectedSOPClassUID, abstractSyntax.c_str(), sizeof(req->AffectedSOPClassUID));

    /* Send request */
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending C-GET Request");
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, msg, DIMSE_OUTGOING, dataset, pcid));
    }
    else
    {
        DCMNET_INFO("Sending C-GET Request (MsgID " << req->MessageID << ")");
    }
    cond = sendDIMSEMessage(pcid, &msg, dataset);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed sending C-GET request: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }

    cond = handleCGETSession(pcid, dataset, responses);
    return cond;
}

// Does the logic for switching between C-GET Response and C-STORE Requests
OFCondition DcmSCU::handleCGETSession(const T_ASC_PresentationContextID /* presID */,
                                      DcmDataset* /* dataset */,
                                      OFList<RetrieveResponse*>* responses)
{
    OFCondition result;
    OFBool continueSession = OFTrue;
    OFString tempStr;

    // As long we want to continue (usually, as long as we receive more objects,
    // i.e. the final C-GET response has not arrived yet)
    while (continueSession)
    {
        T_DIMSE_Message rsp;
        // Make sure everything is zeroed (especially options)
        memset((char*)&rsp, 0, sizeof(rsp));

        DcmDataset* statusDetail         = NULL;
        T_ASC_PresentationContextID pcid = 0;

        // Receive command set
        result = receiveDIMSECommand(&pcid, &rsp, &statusDetail, NULL /* not interested in the command set */);
        if (result.bad())
        {
            DCMNET_ERROR("Failed receiving DIMSE command: " << DimseCondition::dump(tempStr, result));
            delete statusDetail;
            break;
        }
        // Handle C-GET Response
        if (rsp.CommandField == DIMSE_C_GET_RSP)
        {
            if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
            {
                DCMNET_INFO("Received C-GET Response");
                DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
            }
            else
            {
                DCMNET_INFO("Received C-GET Response (" << DU_cgetStatusString(rsp.msg.CGetRSP.DimseStatus) << ")");
            }
            // Prepare response package for response handler
            OFunique_ptr<RetrieveResponse> getRSP(new RetrieveResponse());
            getRSP->m_affectedSOPClassUID     = rsp.msg.CGetRSP.AffectedSOPClassUID;
            getRSP->m_messageIDRespondedTo    = rsp.msg.CGetRSP.MessageIDBeingRespondedTo;
            getRSP->m_status                  = rsp.msg.CGetRSP.DimseStatus;
            getRSP->m_numberOfRemainingSubops = rsp.msg.CGetRSP.NumberOfRemainingSubOperations;
            getRSP->m_numberOfCompletedSubops = rsp.msg.CGetRSP.NumberOfCompletedSubOperations;
            getRSP->m_numberOfFailedSubops    = rsp.msg.CGetRSP.NumberOfFailedSubOperations;
            getRSP->m_numberOfWarningSubops   = rsp.msg.CGetRSP.NumberOfWarningSubOperations;
            getRSP->m_statusDetail            = statusDetail;
            if (statusDetail != NULL)
            {
                DCMNET_DEBUG("Response has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
                statusDetail = NULL; // forget reference to status detail, will be deleted with getRSP
            }
            result = handleCGETResponse(pcid, getRSP.get(), continueSession);
            if (result.bad())
            {
                DCMNET_WARN("Unable to handle C-GET response correctly: " << result.text() << " (ignored)");
                // don't return here but trust the "continueSession" variable
            }
            // if response could be handled successfully, add it to response list
            else
            {
                if (responses != NULL) // only add if desired by caller
                    responses->push_back(getRSP.release());
            }
        }

        // Handle C-STORE Request
        else if (rsp.CommandField == DIMSE_C_STORE_RQ)
        {
            if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
            {
                DCMNET_INFO("Received C-STORE Request");
                DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
            }
            else
            {
                DCMNET_INFO("Received C-STORE Request (MsgID " << rsp.msg.CStoreRQ.MessageID << ")");
            }
            // Receive dataset if there is one (status PENDING)
            DcmDataset* rspDataset = NULL;
            // Check if dataset is announced correctly
            if (rsp.msg.CStoreRQ.DataSetType == DIMSE_DATASET_NULL)
            {
                DCMNET_WARN("Incoming C-STORE with no dataset, trying to receive one anyway");
            }
            Uint16 desiredCStoreReturnStatus = 0;
            // handle normal storage mode, i.e. receive in memory and store to disk
            if (m_storageMode == DCMSCU_STORAGE_DISK)
            {
                // Receive dataset
                result = receiveDIMSEDataset(&pcid, &rspDataset);
                if (result.bad())
                {
                    result                    = DIMSE_NULLKEY;
                    desiredCStoreReturnStatus = STATUS_STORE_Error_CannotUnderstand;
                }
                else
                {
                    result = handleSTORERequest(pcid, rspDataset, continueSession, desiredCStoreReturnStatus);
                }
            }
            // handle bit preserving storage mode, i.e. receive directly to disk
            else if (m_storageMode == DCMSCU_STORAGE_BIT_PRESERVING)
            {
                OFString storageFilename;
                OFStandard::combineDirAndFilename(
                    storageFilename, m_storageDir, rsp.msg.CStoreRQ.AffectedSOPInstanceUID, OFTrue);
                result = handleSTORERequestFile(&pcid, storageFilename, &(rsp.msg.CStoreRQ));
                if (result.good())
                {
                    notifyInstanceStored(
                        storageFilename, rsp.msg.CStoreRQ.AffectedSOPClassUID, rsp.msg.CStoreRQ.AffectedSOPInstanceUID);
                }
            }
            // handle ignore storage mode, i.e. ignore received dataset and do not store at all
            else
            {
                result = ignoreSTORERequest(pcid, rsp.msg.CStoreRQ);
            }

            // Evaluate result from C-STORE request handling and send response
            if (result.bad())
            {
                desiredCStoreReturnStatus = STATUS_STORE_Error_CannotUnderstand;
                continueSession           = OFFalse;
            }
            result = sendSTOREResponse(pcid, desiredCStoreReturnStatus, rsp.msg.CStoreRQ);
            if (result.bad())
            {
                continueSession = OFFalse;
            }
        }

        // Handle other DIMSE command (error since other command than GET/STORE not expected)
        else
        {
            DCMNET_ERROR("Expected C-GET response or C-STORE request but received DIMSE command 0x"
                         << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
                         << OFstatic_cast(unsigned int, rsp.CommandField));
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
            result          = DIMSE_BADCOMMANDTYPE;
            continueSession = OFFalse;
        }

        delete statusDetail; // should be NULL if not existing or added to response list
        statusDetail = NULL;
    }
    /* All responses received or break signal occurred */

    return result;
}

// Handles single C-GET Response
OFCondition DcmSCU::handleCGETResponse(const T_ASC_PresentationContextID /* presID */,
                                       RetrieveResponse* response,
                                       OFBool& continueCGETSession)
{
    continueCGETSession = OFFalse;
    if (response == NULL)
        return DIMSE_NULLKEY;

    DCMNET_DEBUG("Handling C-GET Response");
    OFString s;
    s = DU_cgetStatusString(response->m_status);
    return handleSessionResponseDefault(response->m_status, s, continueCGETSession);
}

// Handles single C-STORE Request received during C-GET session
OFCondition DcmSCU::handleSTORERequest(const T_ASC_PresentationContextID /* presID */,
                                       DcmDataset* incomingObject,
                                       OFBool& /* continueCGETSession */,
                                       Uint16& cStoreReturnStatus)
{
    if (incomingObject == NULL)
        return DIMSE_NULLKEY;

    OFString sopClassUID;
    OFString sopInstanceUID;
    OFCondition result = incomingObject->findAndGetOFString(DCM_SOPClassUID, sopClassUID);
    if (result.good())
        result = incomingObject->findAndGetOFString(DCM_SOPInstanceUID, sopInstanceUID);
    if (result.bad())
    {
        DCMNET_ERROR("Cannot store received object: either SOP Instance or SOP Class UID not present");
        cStoreReturnStatus = STATUS_STORE_Error_DataSetDoesNotMatchSOPClass;
        delete incomingObject;
        return EC_TagNotFound;
    }

    OFString filename = createStorageFilename(incomingObject);
    if (OFStandard::fileExists(filename))
    {
        DCMNET_WARN("DICOM file already exists, overwriting: " << filename);
    }
    DcmFileFormat dcmff(incomingObject, OFFalse /* do not copy but take ownership */);
    result = dcmff.saveFile(filename);
    if (result.good())
    {
        E_TransferSyntax xferSyntax;
        getDatasetInfo(incomingObject, sopClassUID, sopInstanceUID, xferSyntax);
        notifyInstanceStored(filename, sopClassUID, sopInstanceUID);
        cStoreReturnStatus = STATUS_Success;
    }
    else
    {
        DCMNET_ERROR("cannot write DICOM file: " << filename);
        cStoreReturnStatus = STATUS_STORE_Refused_OutOfResources;

        // delete incomplete file
        OFStandard::deleteFile(filename);
    }

    return result;
}

OFCondition DcmSCU::handleSTORERequestFile(T_ASC_PresentationContextID* presID,
                                           const OFString& filename,
                                           T_DIMSE_C_StoreRQ* request)
{
    if (filename.empty())
        return EC_IllegalParameter;

    /* in the following, we want to receive data over the network and write it to a file */
    /* exactly the way it was received over the network. Hence, a filestream will be created and the data */
    /* set will be received and written to the file through the call to DIMSE_receiveDataSetInFile(...).*/
    /* create filestream */
    DcmOutputFileStream* filestream = NULL;
    OFCondition cond                = DIMSE_createFilestream(filename, request, m_assoc, *presID, OFTrue, &filestream);
    if (cond.good())
    {
        if (m_progressNotificationMode)
        {
            cond = DIMSE_receiveDataSetInFile(m_assoc,
                                              m_blockMode,
                                              m_dimseTimeout,
                                              presID,
                                              filestream,
                                              callbackRECEIVEProgress,
                                              this /*callbackData*/);
        }
        else
        {
            cond = DIMSE_receiveDataSetInFile(
                m_assoc, m_blockMode, m_dimseTimeout, presID, filestream, NULL /*callback*/, NULL /*callbackData*/);
        }
        if (cond.good()) cond = filestream->fclose();
        delete filestream;
        if (cond != EC_Normal)
        {
            OFStandard::deleteFile(filename);
        }
        DCMNET_DEBUG("Received dataset on presentation context " << OFstatic_cast(unsigned int, *presID));
    }
    else
    {
        OFString tempStr;
        DCMNET_ERROR("Unable to receive and store dataset on presentation context "
                     << OFstatic_cast(unsigned int, *presID) << ": " << DimseCondition::dump(tempStr, cond));
    }
    return cond;
}

OFCondition
DcmSCU::sendSTOREResponse(T_ASC_PresentationContextID presID, Uint16 status, const T_DIMSE_C_StoreRQ& request)
{
    // Send back response
    T_DIMSE_Message response;
    // Make sure everything is zeroed (especially options)
    memset((char*)&response, 0, sizeof(response));
    T_DIMSE_C_StoreRSP& storeRsp       = response.msg.CStoreRSP;
    response.CommandField              = DIMSE_C_STORE_RSP;
    storeRsp.MessageIDBeingRespondedTo = request.MessageID;
    storeRsp.DimseStatus               = status;
    storeRsp.DataSetType               = DIMSE_DATASET_NULL;
    /* Following information is optional and normally not sent by the underlying
     * dcmnet routines. However, maybe this could be changed later, so insert it.
     */
    OFStandard::strlcpy(
        storeRsp.AffectedSOPClassUID, request.AffectedSOPClassUID, sizeof(storeRsp.AffectedSOPClassUID));
    OFStandard::strlcpy(
        storeRsp.AffectedSOPInstanceUID, request.AffectedSOPInstanceUID, sizeof(storeRsp.AffectedSOPInstanceUID));
    storeRsp.opts = O_STORE_AFFECTEDSOPCLASSUID | O_STORE_AFFECTEDSOPINSTANCEUID;

    OFString tempStr;
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending C-STORE Response");
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_OUTGOING, NULL, presID));
    }
    else
    {
        DCMNET_INFO("Sending C-STORE Response (" << DU_cstoreStatusString(status) << ")");
    }
    OFCondition cond = sendDIMSEMessage(presID, &response, NULL /*dataObject*/);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed sending C-STORE response: " << DimseCondition::dump(tempStr, cond));
    }
    return cond;
}

OFString DcmSCU::createStorageFilename(DcmDataset* dataset)
{
    OFString sopClassUID, sopInstanceUID;
    E_TransferSyntax dummy;
    getDatasetInfo(dataset, sopClassUID, sopInstanceUID, dummy);
    // Create unique filename
    if (sopClassUID.empty() || sopInstanceUID.empty())
        return "";
    OFString name = dcmSOPClassUIDToModality(sopClassUID.c_str(), "UNKNOWN");
    name += ".";
    name += sopInstanceUID;
    OFStandard::sanitizeFilename(name);
    OFString returnStr;
    OFStandard::combineDirAndFilename(returnStr, m_storageDir, name, OFTrue);
    return returnStr;
}

OFCondition DcmSCU::ignoreSTORERequest(T_ASC_PresentationContextID presID, const T_DIMSE_C_StoreRQ& request)
{

    /* We cannot create the filestream, so ignore the incoming dataset and return an out-of-resources error to the SCU
     */
    DIC_UL bytesRead = 0;
    DIC_UL pdvCount  = 0;
    DCMNET_DEBUG("Ignoring incoming C-STORE dataset on presentation context "
                 << OFstatic_cast(unsigned int, presID)
                 << " with Affected SOP Instance UID: " << request.AffectedSOPInstanceUID);
    OFCondition result = DIMSE_ignoreDataSet(m_assoc, m_blockMode, m_dimseTimeout, &bytesRead, &pdvCount);
    if (result.good())
    {
        DCMNET_TRACE("Successfully skipped " << bytesRead << " bytes in " << pdvCount << " PDVs");
    }
    return result;
}

void DcmSCU::notifyInstanceStored(const OFString& filename,
                                  const OFString& sopClassUID,
                                  const OFString& sopInstanceUID) const
{
    DCMNET_DEBUG("Stored instance to disk:");
    DCMNET_DEBUG("  Filename: " << filename);
    DCMNET_DEBUG("  SOP Class UID: " << sopClassUID);
    DCMNET_DEBUG("  SOP Instance UID: " << sopInstanceUID);
}

/* ************************************************************************* */
/*                            C-FIND functionality                           */
/* ************************************************************************* */

// Sends a C-FIND Request on given presentation context
OFCondition
DcmSCU::sendFINDRequest(const T_ASC_PresentationContextID presID, DcmDataset* queryKeys, OFList<QRResponse*>* responses)
{
    // Do some basic validity checks
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;
    if (queryKeys == NULL)
        return DIMSE_NULLKEY;

    /* Prepare DIMSE data structures for issuing request */
    OFCondition cond;
    OFString tempStr;
    T_ASC_PresentationContextID pcid = presID;
    T_DIMSE_Message msg;
    // Make sure everything is zeroed (especially options)
    memset((char*)&msg, 0, sizeof(msg));

    DcmDataset* statusDetail = NULL;
    T_DIMSE_C_FindRQ* req    = &(msg.msg.CFindRQ);
    // Set type of message
    msg.CommandField = DIMSE_C_FIND_RQ;
    // Set message ID
    req->MessageID = nextMessageID();
    // Announce dataset
    req->DataSetType = DIMSE_DATASET_PRESENT;
    // Specify priority
    req->Priority = DIMSE_PRIORITY_MEDIUM;

    // Determine SOP Class from presentation context
    OFString abstractSyntax, transferSyntax;
    findPresentationContext(pcid, abstractSyntax, transferSyntax);
    if (abstractSyntax.empty() || transferSyntax.empty())
        return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
    OFStandard::strlcpy(req->AffectedSOPClassUID, abstractSyntax.c_str(), sizeof(req->AffectedSOPClassUID));

    /* Send request */
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending C-FIND Request");
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, msg, DIMSE_OUTGOING, queryKeys, pcid));
    }
    else
    {
        DCMNET_INFO("Sending C-FIND Request (MsgID " << req->MessageID << ")");
    }
    cond = sendDIMSEMessage(pcid, &msg, queryKeys);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed sending C-FIND request: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }

    /* Receive and handle response */
    OFBool waitForNextResponse = OFTrue;
    while (waitForNextResponse)
    {
        T_DIMSE_Message rsp;
        // Make sure everything is zeroed (especially options)
        memset((char*)&rsp, 0, sizeof(rsp));

        statusDetail = NULL;

        // Receive command set
        cond = receiveDIMSECommand(&pcid, &rsp, &statusDetail, NULL /* not interested in the command set */);
        if (cond.bad())
        {
            DCMNET_ERROR("Failed receiving DIMSE response: " << DimseCondition::dump(tempStr, cond));
            return cond;
        }

        if (rsp.CommandField == DIMSE_C_FIND_RSP)
        {
            if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
            {
                DCMNET_INFO("Received C-FIND Response");
                DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
            }
            else
            {
                DCMNET_INFO("Received C-FIND Response (" << DU_cfindStatusString(rsp.msg.CFindRSP.DimseStatus) << ")");
            }
        }
        else
        {
            DCMNET_ERROR("Expected C-FIND response but received DIMSE command 0x"
                         << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
                         << OFstatic_cast(unsigned int, rsp.CommandField));
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
            delete statusDetail;
            return DIMSE_BADCOMMANDTYPE;
        }

        // Prepare response package for response handler
        OFunique_ptr<QRResponse> findRSP(new QRResponse);
        findRSP->m_affectedSOPClassUID  = rsp.msg.CFindRSP.AffectedSOPClassUID;
        findRSP->m_messageIDRespondedTo = rsp.msg.CFindRSP.MessageIDBeingRespondedTo;
        findRSP->m_status               = rsp.msg.CFindRSP.DimseStatus;
        findRSP->m_statusDetail         = statusDetail;

        // Receive dataset if there is one (status PENDING)
        DcmDataset* rspDataset = NULL;
        if (DICOM_PENDING_STATUS(findRSP->m_status))
        {
            // Check if dataset is announced correctly
            if (rsp.msg.CFindRSP.DataSetType == DIMSE_DATASET_NULL)
            {
                DCMNET_ERROR("Received C-FIND response with PENDING status but no dataset announced, aborting");
                return DIMSE_BADMESSAGE;
            }

            // Receive dataset
            cond = receiveDIMSEDataset(&pcid, &rspDataset);
            if (cond.bad())
                return DIMSE_BADDATA;
            findRSP->m_dataset = rspDataset;
        }

        // Handle C-FIND response (has to handle all possible status flags)
        cond = handleFINDResponse(pcid, findRSP.get(), waitForNextResponse);
        if (cond.bad())
        {
            DCMNET_WARN("Unable to handle C-FIND response correctly: " << cond.text() << " (ignored)");
            // don't return here but trust the "waitForNextResponse" variable
        }
        // if response could be handled successfully, add it to response list
        else
        {
            if (responses != NULL) // only add if desired by caller
                responses->push_back(findRSP.release());
        }
    }
    /* All responses received or break signal occurred */
    return EC_Normal;
}

// Standard handler for C-FIND message responses
OFCondition DcmSCU::handleFINDResponse(const T_ASC_PresentationContextID /* presID */,
                                       QRResponse* response,
                                       OFBool& waitForNextResponse)
{
    waitForNextResponse = OFFalse;
    if (response == NULL)
        return DIMSE_NULLKEY;

    DCMNET_DEBUG("Handling C-FIND Response");
    OFString s;
    s = DU_cfindStatusString(response->m_status);
    return handleSessionResponseDefault(response->m_status, s, waitForNextResponse);
}

/* ************************************************************************* */
/*                            C-CANCEL functionality                         */
/* ************************************************************************* */

// Send C-CANCEL-REQ and, therefore, ends current C-FIND, -MOVE or -GET session
OFCondition DcmSCU::sendCANCELRequest(const T_ASC_PresentationContextID presID,
                                      const Sint32 msgIDBeingRespondedTo)
{
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;

    if (msgIDBeingRespondedTo > 65535 || msgIDBeingRespondedTo < -1)
        return EC_IllegalParameter;

    /* Prepare DIMSE data structures for issuing request */
    OFCondition cond;
    OFString tempStr;
    T_ASC_PresentationContextID pcid = presID;
    T_DIMSE_Message msg;
    // Make sure everything is zeroed (especially options)
    memset((char*)&msg, 0, sizeof(msg));
    T_DIMSE_C_CancelRQ* req = &(msg.msg.CCancelRQ);
    // Set type of message
    msg.CommandField = DIMSE_C_CANCEL_RQ;

    if (msgIDBeingRespondedTo != -1)
    {
        req->MessageIDBeingRespondedTo = OFstatic_cast(Uint16, msgIDBeingRespondedTo);
    }
    else
    {
        /* Set message ID responded to. A new message ID is _not_ needed so
           we do not increment the message ID here but instead have to give the
           message ID that was used last.
           Note that that it is required to actually use the message ID of the last
           C-FIND/GET/MOVE that was issued on this presentation context channel.
           However, since we only support synchronous association mode so far,
           it is enough to take the last message ID used at all.
           For asynchronous operation, we would have to lookup the message ID
           of the last C-FIND/GET/MOVE request issued and thus, store this
           information after sending it.
         */
        req->MessageIDBeingRespondedTo = m_assoc->nextMsgID - 1;
    }

    // Announce dataset
    req->DataSetType = DIMSE_DATASET_NULL;

    /* We do not care about the transfer syntax since no
       dataset is transported at all, i.e. we trust that the user provided
       the correct presentation context ID (could be private one).
     */
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending C-CANCEL Request");
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, msg, DIMSE_OUTGOING, NULL, pcid));
    }
    else
    {
        DCMNET_INFO("Sending C-CANCEL Request (MsgID " << req->MessageIDBeingRespondedTo << ", PresID "
                                                       << OFstatic_cast(unsigned int, pcid) << ")");
    }
    cond = sendDIMSEMessage(pcid, &msg, NULL /*dataObject*/);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed sending C-CANCEL request: " << DimseCondition::dump(tempStr, cond));
    }

    DCMNET_TRACE("There is no C-CANCEL response in DICOM, so none expected");
    return cond;
}

/* ************************************************************************* */
/*                            N-ACTION functionality                         */
/* ************************************************************************* */

// Sends N-ACTION request to another DICOM application
OFCondition DcmSCU::sendACTIONRequest(const T_ASC_PresentationContextID presID,
                                      const OFString& sopInstanceUID,
                                      const Uint16 actionTypeID,
                                      DcmDataset* reqDataset,
                                      Uint16& rspStatusCode)
{
    // Do some basic validity checks
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;
    if (sopInstanceUID.empty() || (reqDataset == NULL))
        return DIMSE_NULLKEY;

    // Prepare DIMSE data structures for issuing request
    OFCondition cond;
    OFString tempStr;
    T_ASC_PresentationContextID pcid = presID;
    T_DIMSE_Message request;
    // Make sure everything is zeroed (especially options)
    memset((char*)&request, 0, sizeof(request));
    T_DIMSE_N_ActionRQ& actionReq = request.msg.NActionRQ;
    DcmDataset* statusDetail      = NULL;

    request.CommandField   = DIMSE_N_ACTION_RQ;
    actionReq.MessageID    = nextMessageID();
    actionReq.DataSetType  = DIMSE_DATASET_PRESENT;
    actionReq.ActionTypeID = actionTypeID;

    // Determine SOP Class from presentation context
    OFString abstractSyntax, transferSyntax;
    findPresentationContext(pcid, abstractSyntax, transferSyntax);
    if (abstractSyntax.empty() || transferSyntax.empty())
        return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
    OFStandard::strlcpy(actionReq.RequestedSOPClassUID, abstractSyntax.c_str(), sizeof(actionReq.RequestedSOPClassUID));
    OFStandard::strlcpy(
        actionReq.RequestedSOPInstanceUID, sopInstanceUID.c_str(), sizeof(actionReq.RequestedSOPInstanceUID));

    // Send request
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending N-ACTION Request");
        // Output dataset only if trace level is enabled
        if (DCM_dcmnetLogger.isEnabledFor(OFLogger::TRACE_LOG_LEVEL))
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_OUTGOING, reqDataset, pcid));
        else
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_OUTGOING, NULL, pcid));
    }
    else
    {
        DCMNET_INFO("Sending N-ACTION Request (MsgID " << actionReq.MessageID << ")");
    }
    cond = sendDIMSEMessage(pcid, &request, reqDataset);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed sending N-ACTION request: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }

    // Receive response
    T_DIMSE_Message response;
    memset((char*)&response, 0, sizeof(response));
    cond = receiveDIMSECommand(&pcid, &response, &statusDetail, NULL /* commandSet */);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed receiving DIMSE response: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }

    // Check command set
    if (response.CommandField == DIMSE_N_ACTION_RSP)
    {
        if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
        {
            DCMNET_INFO("Received N-ACTION Response");
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_INCOMING, NULL, pcid));
        }
        else
        {
            DCMNET_INFO("Received N-ACTION Response (" << DU_nactionStatusString(response.msg.NActionRSP.DimseStatus)
                                                       << ")");
        }
    }
    else
    {
        DCMNET_ERROR("Expected N-ACTION response but received DIMSE command 0x"
                     << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
                     << OFstatic_cast(unsigned int, response.CommandField));
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_INCOMING, NULL, pcid));
        delete statusDetail;
        return DIMSE_BADCOMMANDTYPE;
    }
    if (statusDetail != NULL)
    {
        DCMNET_DEBUG("Response has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
        delete statusDetail;
    }

    // Set return value
    T_DIMSE_N_ActionRSP& actionRsp = response.msg.NActionRSP;
    rspStatusCode                  = actionRsp.DimseStatus;

    // Check whether there is a dataset to be received
    if (actionRsp.DataSetType != DIMSE_DATASET_NULL)
    {
        // this should never happen
        DcmDataset* tempDataset = NULL;
        T_ASC_PresentationContextID tempID;
        DCMNET_WARN("Trying to retrieve unexpected dataset in N-ACTION response");
        cond = receiveDIMSEDataset(&tempID, &tempDataset);
        if (cond.good())
        {
            DCMNET_WARN("Received unexpected dataset after N-ACTION response, ignoring");
            delete tempDataset;
        }
        else
        {
            return DIMSE_BADDATA;
        }
    }
    if (actionRsp.MessageIDBeingRespondedTo != actionReq.MessageID)
    {
        // since we only support synchronous communication, the message ID in the response
        // should be identical to the one in the request
        DCMNET_ERROR("Received response with wrong message ID (" << actionRsp.MessageIDBeingRespondedTo
                                                                 << " instead of " << actionReq.MessageID << ")");
        return DIMSE_BADMESSAGE;
    }

    return cond;
}

/* ************************************************************************* */
/*                         N-EVENT REPORT functionality                      */
/* ************************************************************************* */

// Sends N-EVENT-REPORT request and receives N-EVENT-REPORT response
OFCondition DcmSCU::sendEVENTREPORTRequest(const T_ASC_PresentationContextID presID,
                                           const OFString& sopInstanceUID,
                                           const Uint16 eventTypeID,
                                           DcmDataset* reqDataset,
                                           Uint16& rspStatusCode)
{
    // Do some basic validity checks
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;
    if (sopInstanceUID.empty() || (reqDataset == NULL))
        return DIMSE_NULLKEY;

    // Prepare DIMSE data structures for issuing request
    OFCondition cond;
    OFString tempStr;
    T_ASC_PresentationContextID pcid = presID;
    T_DIMSE_Message request;
    // Make sure everything is zeroed (especially options)
    memset((char*)&request, 0, sizeof(request));

    T_DIMSE_N_EventReportRQ& eventReportReq = request.msg.NEventReportRQ;
    DcmDataset* statusDetail                = NULL;

    request.CommandField = DIMSE_N_EVENT_REPORT_RQ;

    // Generate a new message ID
    eventReportReq.MessageID   = nextMessageID();
    eventReportReq.DataSetType = DIMSE_DATASET_PRESENT;
    eventReportReq.EventTypeID = eventTypeID;

    // Determine SOP Class from presentation context
    OFString abstractSyntax, transferSyntax;
    findPresentationContext(pcid, abstractSyntax, transferSyntax);
    if (abstractSyntax.empty() || transferSyntax.empty())
        return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
    OFStandard::strlcpy(
        eventReportReq.AffectedSOPClassUID, abstractSyntax.c_str(), sizeof(eventReportReq.AffectedSOPClassUID));
    OFStandard::strlcpy(
        eventReportReq.AffectedSOPInstanceUID, sopInstanceUID.c_str(), sizeof(eventReportReq.AffectedSOPInstanceUID));

    // Send request
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending N-EVENT-REPORT Request");
        // Output dataset only if trace level is enabled
        if (DCM_dcmnetLogger.isEnabledFor(OFLogger::TRACE_LOG_LEVEL))
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_OUTGOING, reqDataset, pcid));
        else
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_OUTGOING, NULL, pcid));
    }
    else
    {
        DCMNET_INFO("Sending N-EVENT-REPORT Request (MsgID " << eventReportReq.MessageID << ")");
    }
    cond = sendDIMSEMessage(pcid, &request, reqDataset);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed sending N-EVENT-REPORT request: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }
    // Receive response
    T_DIMSE_Message response;
    // Make sure everything is zeroed (especially options)
    memset((char*)&response, 0, sizeof(response));

    cond = receiveDIMSECommand(&pcid, &response, &statusDetail, NULL /* commandSet */);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed receiving DIMSE response: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }

    // Check command set
    if (response.CommandField == DIMSE_N_EVENT_REPORT_RSP)
    {
        if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
        {
            DCMNET_INFO("Received N-EVENT-REPORT Response");
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_INCOMING, NULL, pcid));
        }
        else
        {
            DCMNET_INFO("Received N-EVENT-REPORT Response ("
                        << DU_neventReportStatusString(response.msg.NEventReportRSP.DimseStatus) << ")");
        }
    }
    else
    {
        DCMNET_ERROR("Expected N-EVENT-REPORT response but received DIMSE command 0x"
                     << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
                     << OFstatic_cast(unsigned int, response.CommandField));
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_INCOMING, NULL, pcid));
        delete statusDetail;
        return DIMSE_BADCOMMANDTYPE;
    }
    if (statusDetail != NULL)
    {
        DCMNET_DEBUG("Response has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
        delete statusDetail;
    }

    // Set return value
    T_DIMSE_N_EventReportRSP& eventReportRsp = response.msg.NEventReportRSP;
    rspStatusCode                            = eventReportRsp.DimseStatus;

    // Check whether there is a dataset to be received
    if (eventReportRsp.DataSetType != DIMSE_DATASET_NULL)
    {
        // this should never happen
        DcmDataset* tempDataset = NULL;
        T_ASC_PresentationContextID tempID;
        cond = receiveDIMSEDataset(&tempID, &tempDataset);
        if (cond.good())
        {
            DCMNET_WARN("Received unexpected dataset after N-EVENT-REPORT response, ignoring");
            delete tempDataset;
        }
        else
        {
            DCMNET_ERROR("Failed receiving unexpected dataset after N-EVENT-REPORT response: "
                         << DimseCondition::dump(tempStr, cond));
            return DIMSE_BADDATA;
        }
    }

    // Check whether the message ID being responded to is equal to the message ID of the request
    if (eventReportRsp.MessageIDBeingRespondedTo != eventReportReq.MessageID)
    {
        DCMNET_ERROR("Received response with wrong message ID (" << eventReportRsp.MessageIDBeingRespondedTo
                                                                 << " instead of " << eventReportReq.MessageID << ")");
        return DIMSE_BADMESSAGE;
    }
    return cond;
}

// Receives N-EVENT-REPORT request
OFCondition DcmSCU::handleEVENTREPORTRequest(DcmDataset*& reqDataset, Uint16& eventTypeID, const int timeout)
{
    // Do some basic validity checks
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;

    OFCondition cond;
    OFString tempStr;
    T_ASC_PresentationContextID presID;
    T_ASC_PresentationContextID presIDdset;
    T_DIMSE_Message request;
    // Make sure everything is zeroed (especially options)
    memset((char*)&request, 0, sizeof(request));
    T_DIMSE_N_EventReportRQ& eventReportReq = request.msg.NEventReportRQ;
    DcmDataset* dataset                     = NULL;
    DcmDataset* statusDetail                = NULL;
    Uint16 statusCode                       = 0;

    if (timeout > 0)
        DCMNET_DEBUG("Handle N-EVENT-REPORT request, waiting up to " << timeout
                                                                     << " seconds (only for N-EVENT-REPORT message)");
    else if ((m_dimseTimeout > 0) && (m_blockMode == DIMSE_NONBLOCKING))
        DCMNET_DEBUG("Handle N-EVENT-REPORT request, waiting up to " << m_dimseTimeout
                                                                     << " seconds (default for all DIMSE messages)");
    else
        DCMNET_DEBUG("Handle N-EVENT-REPORT request, waiting an unlimited period of time");

    // Receive request, use specific timeout (if defined)
    cond = receiveDIMSECommand(&presID, &request, &statusDetail, NULL /* commandSet */, timeout);
    if (cond.bad())
    {
        if (cond != DIMSE_NODATAAVAILABLE)
            DCMNET_ERROR("Failed receiving DIMSE request: " << DimseCondition::dump(tempStr, cond));
        return cond;
    }

    // Check command set
    if (request.CommandField == DIMSE_N_EVENT_REPORT_RQ)
    {
        if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
            DCMNET_INFO("Received N-EVENT-REPORT Request");
        else
            DCMNET_INFO("Received N-EVENT-REPORT Request (MsgID " << eventReportReq.MessageID << ")");
    }
    else
    {
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, NULL, presID));
        DCMNET_ERROR("Expected N-EVENT-REPORT request but received DIMSE command 0x"
                     << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
                     << OFstatic_cast(unsigned int, request.CommandField));
        delete statusDetail;
        return DIMSE_BADCOMMANDTYPE;
    }
    if (statusDetail != NULL)
    {
        DCMNET_DEBUG("Request has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
        delete statusDetail;
    }

    // Check if dataset is announced correctly
    if (eventReportReq.DataSetType == DIMSE_DATASET_NULL)
    {
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, NULL, presID));
        DCMNET_ERROR("Received N-EVENT-REPORT request but no dataset announced, aborting");
        return DIMSE_BADMESSAGE;
    }

    // Receive dataset
    cond = receiveDIMSEDataset(&presIDdset, &dataset);
    if (cond.bad())
    {
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, NULL, presID));
        return DIMSE_BADDATA;
    }

    // Output dataset only if trace level is enabled
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::TRACE_LOG_LEVEL))
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, dataset, presID));
    else
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, NULL, presID));

    // Compare presentation context ID of command and data set
    if (presIDdset != presID)
    {
        DCMNET_ERROR("Presentation Context ID of command (" << OFstatic_cast(unsigned int, presID) << ") and data set ("
                                                            << OFstatic_cast(unsigned int, presIDdset) << ") differ");
        delete dataset;
        return makeDcmnetCondition(DIMSEC_INVALIDPRESENTATIONCONTEXTID,
                                   OF_error,
                                   "DIMSE: Presentation Contexts of Command and Data Set differ");
    }

    // Check the request dataset and return the DIMSE status code to be used
    statusCode = checkEVENTREPORTRequest(eventReportReq, dataset);

    // Send back response
    T_DIMSE_Message response;
    // Make sure everything is zeroed (especially options)
    memset((char*)&response, 0, sizeof(response));

    T_DIMSE_N_EventReportRSP& eventReportRsp = response.msg.NEventReportRSP;
    response.CommandField                    = DIMSE_N_EVENT_REPORT_RSP;
    eventReportRsp.MessageIDBeingRespondedTo = eventReportReq.MessageID;
    eventReportRsp.DimseStatus               = statusCode;
    eventReportRsp.DataSetType               = DIMSE_DATASET_NULL;
    eventReportRsp.opts                      = 0;
    eventReportRsp.AffectedSOPClassUID[0]    = 0;
    eventReportRsp.AffectedSOPInstanceUID[0] = 0;

    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending N-EVENT-REPORT Response");
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_OUTGOING, NULL, presID));
    }
    else
    {
        DCMNET_INFO("Sending N-EVENT-REPORT Response (" << DU_neventReportStatusString(statusCode) << ")");
    }
    cond = sendDIMSEMessage(presID, &response, NULL /*dataObject*/);
    if (cond.bad())
    {
        DCMNET_ERROR("Failed sending N-EVENT-REPORT response: " << DimseCondition::dump(tempStr, cond));
        delete dataset;
        return cond;
    }

    // Set return values
    reqDataset  = dataset;
    eventTypeID = eventReportReq.EventTypeID;

    return cond;
}

Uint16 DcmSCU::checkEVENTREPORTRequest(T_DIMSE_N_EventReportRQ& /*eventReportReq*/, DcmDataset* /*reqDataset*/)
{
    // we default to success
    return STATUS_Success;
}

OFCondition DcmSCU::sendNCREATERequest(const T_ASC_PresentationContextID presID,
                                       const OFString& affectedSopInstanceUID,
                                       DcmDataset* reqDataset,
                                       DcmDataset*& createdInstance,
                                       Uint16& rspStatusCode)
{
    // Do some basic validity checks
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;

    if (affectedSopInstanceUID.empty() || (reqDataset == OFnullptr))
        return DIMSE_NULLKEY;

    // Determine SOP Class from presentation context
    OFString abstractSyntax, transferSyntax;
    findPresentationContext(presID, abstractSyntax, transferSyntax);
    if (abstractSyntax.empty() || transferSyntax.empty())
        return DIMSE_NOVALIDPRESENTATIONCONTEXTID;

    T_DIMSE_Message request;
    // Make sure everything is zeroed (especially options)
    memset((char*)&request, 0, sizeof(request));
    request.CommandField        = DIMSE_N_CREATE_RQ;
    T_DIMSE_N_CreateRQ& rqmsg   = request.msg.NCreateRQ;
    rqmsg.MessageID             = nextMessageID();
    rqmsg.DataSetType           = DIMSE_DATASET_PRESENT;
    rqmsg.opts                  = O_NCREATE_AFFECTEDSOPINSTANCEUID;

    OFStandard::strlcpy(rqmsg.AffectedSOPClassUID, abstractSyntax.c_str(), sizeof(rqmsg.AffectedSOPClassUID));
    OFStandard::strlcpy(rqmsg.AffectedSOPInstanceUID, affectedSopInstanceUID.c_str(), sizeof(rqmsg.AffectedSOPInstanceUID));

    OFString tempStr;

    /* Send request */
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending N-CREATE Request");
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_OUTGOING, reqDataset, presID));
    }
    else
    {
        DCMNET_INFO("Sending N-CREATE Request (MsgID " << rqmsg.MessageID << ")");
    }

    OFCondition result = sendDIMSEMessage(presID, &request, reqDataset);
    if (result.bad())
    {
        DCMNET_ERROR("Failed sending N-CREATE request: " << DimseCondition::dump(tempStr, result));
        return result;
    }

    T_DIMSE_Message response;
    // Make sure everything is zeroed (especially options)
    memset((char*)&response, 0, sizeof(response));
    DcmDataset* statusDetail = OFnullptr;

    T_ASC_PresentationContextID pcid = presID;
    result = receiveDIMSECommand(&pcid, &response, &statusDetail, OFnullptr /* commandSet */);

    rspStatusCode = response.msg.NCreateRSP.DimseStatus;

    if (result.bad())
    {
        delete statusDetail;
        DCMNET_ERROR("Failed receiving DIMSE response: " << DimseCondition::dump(tempStr, result));
        return result;
    }

    if (response.CommandField == DIMSE_N_CREATE_RSP)
    {
        if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
        {
            DCMNET_INFO("Received N-CREATE Response");
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_INCOMING, NULL, pcid));
        }
        else
        {
            DCMNET_INFO("Received N-CREATE Response (" << DU_ncreateStatusString(rspStatusCode) << ")");
        }
    }
    else
    {
        DCMNET_ERROR("Expected N-CREATE response but received DIMSE command 0x"
            << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
            << OFstatic_cast(unsigned int, response.CommandField));
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_INCOMING, NULL, pcid));
        delete statusDetail;
        return DIMSE_BADCOMMANDTYPE;
    }

    if (statusDetail != OFnullptr)
    {
        DCMNET_DEBUG("Response has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
        delete statusDetail;
    }

    if (pcid != presID)
    {
        DCMNET_ERROR("Presentation Context ID of command (" << OFstatic_cast(unsigned int, presID) << ") and data set ("
            << OFstatic_cast(unsigned int, pcid) << ") differ");
        return makeDcmnetCondition(DIMSEC_INVALIDPRESENTATIONCONTEXTID,
            OF_error,
            "DIMSE: Presentation Contexts of Command and Data Set differ");
    }

    // If requested, we need to receive the dataset containing the received instance
    if (response.msg.NCreateRSP.DataSetType != DIMSE_DATASET_NULL)
    {
        DcmDataset* respDataset = OFnullptr;
        result = receiveDIMSEDataset(&pcid, &respDataset);
        if (result.bad())
        {
            delete respDataset;
            DCMNET_ERROR(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, OFnullptr, pcid));
            return DIMSE_BADDATA;
        }

        if (presID != pcid)
        {
            delete respDataset;
            DCMNET_ERROR("Presentation Context ID of command (" << OFstatic_cast(unsigned int, presID) << ") and data set ("
                << OFstatic_cast(unsigned int, pcid) << ") differ");
            return makeDcmnetCondition(DIMSEC_INVALIDPRESENTATIONCONTEXTID,
                OF_error,
                "DIMSE: Presentation Contexts of Command and Data Set differ");
        }
        // Provide user with copy of result dataset
        createdInstance = respDataset;
    }

    return EC_Normal;
}

OFCondition DcmSCU::sendNSETRequest(const T_ASC_PresentationContextID presID,
    const OFString& requestedSopInstanceUID,
    DcmDataset* modificationList,
    DcmDataset*& attributeList,
    Uint16& rspStatusCode)
{

    // Do some basic validity checks
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;

    if (requestedSopInstanceUID.empty() || (modificationList == OFnullptr))
        return DIMSE_NULLKEY;

    // Determine SOP Class from presentation context
    OFString abstractSyntax, transferSyntax;
    findPresentationContext(presID, abstractSyntax, transferSyntax);
    if (abstractSyntax.empty() || transferSyntax.empty())
        return DIMSE_NOVALIDPRESENTATIONCONTEXTID;

    T_DIMSE_Message request;
    memset((char*)&request, 0, sizeof(request));
    request.CommandField = DIMSE_N_SET_RQ;
    T_DIMSE_N_SetRQ& rqmsg = request.msg.NSetRQ;
    rqmsg.MessageID = nextMessageID();
    rqmsg.DataSetType = DIMSE_DATASET_PRESENT;

    OFStandard::strlcpy(rqmsg.RequestedSOPClassUID, abstractSyntax.c_str(), sizeof(rqmsg.RequestedSOPClassUID));
    OFStandard::strlcpy(rqmsg.RequestedSOPInstanceUID, requestedSopInstanceUID.c_str(), sizeof(rqmsg.RequestedSOPInstanceUID));

    OFString tempStr;

    /* Send request */
    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
    {
        DCMNET_INFO("Sending N-SET Request");
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_OUTGOING, modificationList, presID));
    }
    else
    {
        DCMNET_INFO("Sending N-SET Request (MsgID " << rqmsg.MessageID << ")");
    }

    OFCondition result = sendDIMSEMessage(presID, &request, modificationList);
    if (result.bad())
    {
        DCMNET_ERROR("Failed sending N-SET request: " << DimseCondition::dump(tempStr, result));
        return result;
    }

    T_DIMSE_Message response;
    // Make sure everything is zeroed (especially options)
    memset((char*)&response, 0, sizeof(response));
    DcmDataset* statusDetail = OFnullptr;

    T_ASC_PresentationContextID pcid = presID;
    result = receiveDIMSECommand(&pcid, &response, &statusDetail, OFnullptr /* commandSet */);

    rspStatusCode = response.msg.NSetRSP.DimseStatus;

    if (result.bad())
    {
        delete statusDetail;
        DCMNET_ERROR("Failed receiving DIMSE response: " << DimseCondition::dump(tempStr, result));
        return result;
    }

    if (response.CommandField == DIMSE_N_SET_RSP)
    {
        if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
        {
            DCMNET_INFO("Received N-SET Response");
            DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_INCOMING, NULL, pcid));
        }
        else
        {
            DCMNET_INFO("Received N-SET Response (" << DU_cstoreStatusString(rspStatusCode) << ")");
        }
    }
    else
    {
        DCMNET_ERROR("Expected N-SET response but received DIMSE command 0x"
            << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
            << OFstatic_cast(unsigned int, response.CommandField));
        DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_INCOMING, NULL, pcid));
        delete statusDetail;
        return DIMSE_BADCOMMANDTYPE;
    }

    if (statusDetail != OFnullptr)
    {
        DCMNET_DEBUG("Response has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
        delete statusDetail;
    }

    if (pcid != presID)
    {
        DCMNET_ERROR("Presentation Context ID of command (" << OFstatic_cast(unsigned int, presID) << ") and data set ("
            << OFstatic_cast(unsigned int, pcid) << ") differ");
        return makeDcmnetCondition(DIMSEC_INVALIDPRESENTATIONCONTEXTID,
            OF_error,
            "DIMSE: Presentation Contexts of Command and Data Set differ");
    }

    // If requested, we need to receive the dataset containing the received instance
    if (response.msg.NSetRSP.DataSetType != DIMSE_DATASET_NULL)
    {
        DcmDataset* respDataset = OFnullptr;
        result = receiveDIMSEDataset(&pcid, &respDataset);
        if (result.bad())
        {
            delete respDataset;
            DCMNET_ERROR(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, OFnullptr, pcid));
            return DIMSE_BADDATA;
        }

        if (presID != pcid)
        {
            delete respDataset;
            DCMNET_ERROR("Presentation Context ID of command (" << OFstatic_cast(unsigned int, presID) << ") and data set ("
                << OFstatic_cast(unsigned int, pcid) << ") differ");
            return makeDcmnetCondition(DIMSEC_INVALIDPRESENTATIONCONTEXTID,
                OF_error,
                "DIMSE: Presentation Contexts of Command and Data Set differ");
        }

        // Provide user with copy of result dataset if desired
        attributeList = respDataset;
    }

    return EC_Normal;
}

OFCondition
DcmSCU::handleSessionResponseDefault(const Uint16 dimseStatus, const OFString& message, OFBool& waitForNextResponse)
{
    waitForNextResponse = OFFalse;

    // Do some basic validity checks
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;

    if (DICOM_WARNING_STATUS(dimseStatus))
    {
        DCMNET_WARN("DIMSE status is: " << message);
    }
    else if (DICOM_PENDING_STATUS(dimseStatus))
    {
        waitForNextResponse = OFTrue;
        DCMNET_DEBUG("DIMSE status is: " << message);
    }
    else if (dimseStatus == STATUS_Success)
    {
        DCMNET_DEBUG("DIMSE status is: " << message);
    }
    else
    {
        DCMNET_ERROR("DIMSE status is: " << message);
    }

    return EC_Normal;
}

/* ************************************************************************* */
/*                         General message handling                          */
/* ************************************************************************* */

void DcmSCU::notifySENDProgress(const unsigned long byteCount)
{
    DCMNET_TRACE("Bytes sent: " << byteCount);
}

void DcmSCU::notifyRECEIVEProgress(const unsigned long byteCount)
{
    DCMNET_TRACE("Bytes received: " << byteCount);
}

/* ************************************************************************* */
/*                            Various helpers                                */
/* ************************************************************************* */

// Sends a DIMSE command and possibly also instance data to the configured peer DICOM application
OFCondition DcmSCU::sendDIMSEMessage(const T_ASC_PresentationContextID presID,
                                     T_DIMSE_Message* msg,
                                     DcmDataset* dataObject,
                                     DcmDataset** commandSet)
{
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;
    if (msg == NULL)
        return DIMSE_NULLKEY;

    OFCondition cond;
    /* call the corresponding DIMSE function to send the message */
    if (m_progressNotificationMode)
    {
        cond = DIMSE_sendMessageUsingMemoryData(m_assoc,
                                                presID,
                                                msg,
                                                NULL /*statusDetail*/,
                                                dataObject,
                                                callbackSENDProgress,
                                                this /*callbackData*/,
                                                commandSet);
    }
    else
    {
        cond = DIMSE_sendMessageUsingMemoryData(m_assoc,
                                                presID,
                                                msg,
                                                NULL /*statusDetail*/,
                                                dataObject,
                                                NULL /*callback*/,
                                                NULL /*callbackData*/,
                                                commandSet);
    }

#if 0
  // currently disabled because it is not (yet) needed
  if (cond.good())
  {
    /* create a copy of the current DIMSE command message */
    delete m_openDIMSERequest;
    m_openDIMSERequest = new T_DIMSE_Message;
    // Make sure everyhting is zeroed (especially options)
    memset((char*)&m_openDIMSERequest, 0, sizeof(m_openDimseRequest));
    memcpy((char*)m_openDIMSERequest, msg, sizeof(*m_openDIMSERequest));
  }
#endif

    return cond;
}

// Receive DIMSE command (excluding dataset!) over the currently open association
OFCondition DcmSCU::receiveDIMSECommand(T_ASC_PresentationContextID* presID,
                                        T_DIMSE_Message* msg,
                                        DcmDataset** statusDetail,
                                        DcmDataset** commandSet,
                                        const Uint32 timeout)
{
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;

    OFCondition cond;
    if (timeout > 0)
    {
        /* call the corresponding DIMSE function to receive the command (use specified timeout)*/
        cond = DIMSE_receiveCommand(m_assoc, DIMSE_NONBLOCKING, timeout, presID, msg, statusDetail, commandSet);
    }
    else
    {
        /* call the corresponding DIMSE function to receive the command (use default timeout) */
        cond = DIMSE_receiveCommand(m_assoc, m_blockMode, m_dimseTimeout, presID, msg, statusDetail, commandSet);
    }
    return cond;
}

// Receives one dataset (of instance data) via network from another DICOM application
OFCondition DcmSCU::receiveDIMSEDataset(T_ASC_PresentationContextID* presID, DcmDataset** dataObject)
{
    if (!isConnected())
        return DIMSE_ILLEGALASSOCIATION;

    OFCondition cond;
    /* call the corresponding DIMSE function to receive the dataset */
    if (m_progressNotificationMode)
    {
        cond = DIMSE_receiveDataSetInMemory(
            m_assoc, m_blockMode, m_dimseTimeout, presID, dataObject, callbackRECEIVEProgress, this /*callbackData*/);
    }
    else
    {
        cond = DIMSE_receiveDataSetInMemory(
            m_assoc, m_blockMode, m_dimseTimeout, presID, dataObject, NULL /*callback*/, NULL /*callbackData*/);
    }

    if (cond.good())
    {
        DCMNET_DEBUG("Received dataset on presentation context " << OFstatic_cast(unsigned int, *presID));
    }
    else
    {
        OFString tempStr;
        DCMNET_ERROR("Unable to receive dataset on presentation context "
                     << OFstatic_cast(unsigned int, *presID) << ": " << DimseCondition::dump(tempStr, cond));
    }
    return cond;
}

void DcmSCU::setMaxReceivePDULength(const Uint32 maxRecPDU)
{
    m_maxReceivePDULength = maxRecPDU;
}

void DcmSCU::setDIMSEBlockingMode(const T_DIMSE_BlockingMode blockingMode)
{
    m_blockMode = blockingMode;
}

void DcmSCU::setAETitle(const OFString& myAETtitle)
{
    m_ourAETitle = myAETtitle;
}

void DcmSCU::setPeerHostName(const OFString& peerHostName)
{
    m_peer = peerHostName;
}

void DcmSCU::setPeerAETitle(const OFString& peerAETitle)
{
    m_peerAETitle = peerAETitle;
}

void DcmSCU::setPeerPort(const Uint16 peerPort)
{
    m_peerPort = peerPort;
}

void DcmSCU::setDIMSETimeout(const Uint32 dimseTimeout)
{
    m_dimseTimeout = dimseTimeout;
}

void DcmSCU::setACSETimeout(const Uint32 acseTimeout)
{
    m_acseTimeout = acseTimeout;
}

void DcmSCU::setConnectionTimeout(const Sint32 connectionTimeout)
{
    m_tcpConnectTimeout = connectionTimeout;
}

void DcmSCU::setAssocConfigFileAndProfile(const OFString& filename, const OFString& profile)
{
    m_assocConfigFilename = filename;
    m_assocConfigProfile  = profile;
}

void DcmSCU::setStorageDir(const OFString& storeDir)
{
    m_storageDir = storeDir;
}

void DcmSCU::setStorageMode(const DcmStorageMode storageMode)
{
    m_storageMode = storageMode;
}

void DcmSCU::setVerbosePCMode(const OFBool mode)
{
    m_verbosePCMode = mode;
}

void DcmSCU::setDatasetConversionMode(const OFBool mode)
{
    m_datasetConversionMode = mode;
}

void DcmSCU::setProgressNotificationMode(const OFBool mode)
{
    m_progressNotificationMode = mode;
}

void DcmSCU::setProtocolVersion(T_ASC_ProtocolFamily protocolVersion)
{
    m_protocolVersion = protocolVersion;
}

/* Get methods */

OFBool DcmSCU::isConnected() const
{
    return (m_assoc != NULL) && (m_assoc->DULassociation != NULL);
}

Uint32 DcmSCU::getMaxReceivePDULength() const
{
    return m_maxReceivePDULength;
}

OFBool DcmSCU::getTLSEnabled() const
{
    return m_secureConnectionEnabled;
}

T_DIMSE_BlockingMode DcmSCU::getDIMSEBlockingMode() const
{
    return m_blockMode;
}

const OFString& DcmSCU::getAETitle() const
{
    return m_ourAETitle;
}

const OFString& DcmSCU::getPeerHostName() const
{
    return m_peer;
}

const OFString& DcmSCU::getPeerAETitle() const
{
    return m_peerAETitle;
}

Uint16 DcmSCU::getPeerPort() const
{
    return m_peerPort;
}

Uint32 DcmSCU::getDIMSETimeout() const
{
    return m_dimseTimeout;
}

Uint32 DcmSCU::getACSETimeout() const
{
    return m_acseTimeout;
}

Sint32 DcmSCU::getConnectionTimeout() const
{
    return m_tcpConnectTimeout;
}

OFString DcmSCU::getStorageDir() const
{
    return m_storageDir;
}

DcmStorageMode DcmSCU::getStorageMode() const
{
    return m_storageMode;
}

OFBool DcmSCU::getVerbosePCMode() const
{
    return m_verbosePCMode;
}

OFBool DcmSCU::getDatasetConversionMode() const
{
    return m_datasetConversionMode;
}

OFBool DcmSCU::getProgressNotificationMode() const
{
    return m_progressNotificationMode;
}

OFCondition DcmSCU::getDatasetInfo(DcmDataset* dataset,
                                   OFString& sopClassUID,
                                   OFString& sopInstanceUID,
                                   E_TransferSyntax& transferSyntax)
{
    OFCondition status = EC_IllegalParameter;
    sopClassUID.clear();
    sopInstanceUID.clear();
    transferSyntax = EXS_Unknown;
    if (dataset != NULL)
    {
        // ignore returned condition codes (e.g. EC_TagNotFound)
        dataset->findAndGetOFString(DCM_SOPClassUID, sopClassUID);
        dataset->findAndGetOFString(DCM_SOPInstanceUID, sopInstanceUID);
        transferSyntax = dataset->getOriginalXfer();
        // check return values for validity
        if (sopClassUID.empty())
            status = NET_EC_InvalidSOPClassUID;
        else if (sopInstanceUID.empty())
            status = NET_EC_InvalidSOPInstanceUID;
        else if (transferSyntax == EXS_Unknown)
            status = NET_EC_UnknownTransferSyntax;
        else
            status = EC_Normal;
    }
    return status;
}

/* ************************************************************************* */
/*                            Callback functions                             */
/* ************************************************************************* */

void DcmSCU::callbackSENDProgress(void* callbackContext, const unsigned long byteCount)
{
    if (callbackContext != NULL)
        OFreinterpret_cast(DcmSCU*, callbackContext)->notifySENDProgress(byteCount);
}

void DcmSCU::callbackRECEIVEProgress(void* callbackContext, const unsigned long byteCount)
{
    if (callbackContext != NULL)
        OFreinterpret_cast(DcmSCU*, callbackContext)->notifyRECEIVEProgress(byteCount);
}

/* ************************************************************************* */
/*                          class RetrieveResponse                           */
/* ************************************************************************* */

void RetrieveResponse::print()
{
    DCMNET_INFO("  Number of Remaining Suboperations : " << m_numberOfRemainingSubops);
    DCMNET_INFO("  Number of Completed Suboperations : " << m_numberOfCompletedSubops);
    DCMNET_INFO("  Number of Failed Suboperations    : " << m_numberOfFailedSubops);
    DCMNET_INFO("  Number of Warning Suboperations   : " << m_numberOfWarningSubops);
}