File: dsrdoctn.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 (1422 lines) | stat: -rw-r--r-- 60,819 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
/*
 *
 *  Copyright (C) 2000-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: dcmsr
 *
 *  Author: Joerg Riesmeier
 *
 *  Purpose:
 *    classes: DSRDocumentTreeNode
 *
 */


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

#include "dcmtk/dcmsr/dsrdoctn.h"
#include "dcmtk/dcmsr/dsrdncsr.h"
#include "dcmtk/dcmsr/dsrdtitn.h"
#include "dcmtk/dcmsr/dsrxmld.h"
#include "dcmtk/dcmsr/dsriodcc.h"

#include "dcmtk/dcmdata/dcdeftag.h"
#include "dcmtk/dcmdata/dcuid.h"
#include "dcmtk/dcmdata/dcvrcs.h"
#include "dcmtk/dcmdata/dcvrdt.h"
#include "dcmtk/dcmdata/dcvrui.h"
#include "dcmtk/dcmdata/dcvrul.h"


DSRDocumentTreeNode::DSRDocumentTreeNode(const E_RelationshipType relationshipType,
                                         const E_ValueType valueType)
  : DSRTreeNode(),
    MarkFlag(OFFalse),
    ReferenceTarget(OFFalse),
    RelationshipType(relationshipType),
    ValueType(valueType),
    ConceptName(),
    ObservationDateTime(),
    ObservationUID(),
    TemplateIdentifier(),
    MappingResource(),
    MappingResourceUID(),
    MACParameters(DCM_MACParametersSequence),
    DigitalSignatures(DCM_DigitalSignaturesSequence)
{
}


DSRDocumentTreeNode::DSRDocumentTreeNode(const DSRDocumentTreeNode &node)
  : DSRTreeNode(node.Annotation),
    MarkFlag(node.MarkFlag),
    ReferenceTarget(OFFalse),
    RelationshipType(node.RelationshipType),
    ValueType(node.ValueType),
    ConceptName(node.ConceptName),
    ObservationDateTime(node.ObservationDateTime),
    ObservationUID(node.ObservationUID),
    TemplateIdentifier(node.TemplateIdentifier),
    MappingResource(node.MappingResource),
    MappingResourceUID(node.MappingResourceUID),
    MACParameters(DCM_MACParametersSequence),
    DigitalSignatures(DCM_DigitalSignaturesSequence)
{
}


DSRDocumentTreeNode::~DSRDocumentTreeNode()
{
}


void DSRDocumentTreeNode::clear()
{
    MarkFlag = OFFalse;
    ReferenceTarget = OFFalse;
    ConceptName.clear();
    ObservationDateTime.clear();
    ObservationUID.clear();
    TemplateIdentifier.clear();
    MappingResource.clear();
    MappingResourceUID.clear();
    MACParameters.clear();
    DigitalSignatures.clear();
}


OFBool DSRDocumentTreeNode::isEqual(const DSRDocumentTreeNode &node) const
{
    /* only very basic information is used for comparing the two nodes */
    return (RelationshipType == node.RelationshipType) &&
           (ValueType == node.ValueType) &&
           (ConceptName == node.ConceptName);
}


OFBool DSRDocumentTreeNode::isNotEqual(const DSRDocumentTreeNode &node) const
{
    /* only very basic information is used for comparing the two nodes */
    return (RelationshipType != node.RelationshipType) ||
           (ValueType != node.ValueType) ||
           (ConceptName != node.ConceptName);
}


OFBool DSRDocumentTreeNode::isValid() const
{
    return (RelationshipType != RT_invalid) && (ValueType != VT_invalid);
}


OFBool DSRDocumentTreeNode::hasValidValue() const
{
    return OFTrue;
}


OFBool DSRDocumentTreeNode::isShort(const size_t /*flags*/) const
{
    return OFTrue;
}


OFBool DSRDocumentTreeNode::hasTemplateIdentification() const
{
    /* mapping resource UID is optional, so do not check it */
    return !TemplateIdentifier.empty() && !MappingResource.empty();
}


OFCondition DSRDocumentTreeNode::print(STD_NAMESPACE ostream &stream,
                                       const size_t flags) const
{
    if (RelationshipType != RT_isRoot)
    {
        DCMSR_PRINT_ANSI_ESCAPE_CODE(DCMSR_ANSI_ESCAPE_CODE_RELATIONSHIP_TYPE)
        stream << relationshipTypeToReadableName(RelationshipType) << " ";
    }
    DCMSR_PRINT_ANSI_ESCAPE_CODE(DCMSR_ANSI_ESCAPE_CODE_VALUE_TYPE)
    stream << valueTypeToDefinedTerm(ValueType);
    DCMSR_PRINT_ANSI_ESCAPE_CODE(DCMSR_ANSI_ESCAPE_CODE_DELIMITER)
    stream << ":";
    /* only print valid concept name codes (unless explicitly requested otherwise) */
    if (ConceptName.isValid() || (flags & PF_printInvalidCodes))
    {
        DCMSR_PRINT_ANSI_ESCAPE_CODE(DCMSR_ANSI_ESCAPE_CODE_CONCEPT_NAME)
        ConceptName.print(stream, (flags & PF_printConceptNameCodes) > 0 /*printCodeValue*/, flags);
    }
    return EC_Normal;
}


OFCondition DSRDocumentTreeNode::printExtended(STD_NAMESPACE ostream &stream,
                                               const size_t flags) const
{
    /* print observation date/time (optional) */
    if (!ObservationDateTime.empty())
    {
        OFString tmpString;
        DCMSR_PRINT_ANSI_ESCAPE_CODE(DCMSR_ANSI_ESCAPE_CODE_DELIMITER)
        stream << " {" << dicomToReadableDateTime(ObservationDateTime, tmpString) << "}";
    }
    /* print annotation (optional) */
    if (hasAnnotation() && (flags & PF_printAnnotation))
    {
        DCMSR_PRINT_ANSI_ESCAPE_CODE(DCMSR_ANSI_ESCAPE_CODE_ANNOTATION)
        stream << "  \"" << getAnnotation().getText() << "\"";
    }
    /* print template identification (conditional) */
    if (hasTemplateIdentification() && (flags & PF_printTemplateIdentification))
    {
        DCMSR_PRINT_ANSI_ESCAPE_CODE(DCMSR_ANSI_ESCAPE_CODE_DELIMITER)
        stream << "  # ";
        DCMSR_PRINT_ANSI_ESCAPE_CODE(DCMSR_ANSI_ESCAPE_CODE_TEMPLATE_ID)
        stream << "TID " << TemplateIdentifier;
        stream << " (" << MappingResource;
        if (!MappingResourceUID.empty())
            stream << ", " << MappingResourceUID;
        stream << ")";
    }
    return EC_Normal;
}


OFCondition DSRDocumentTreeNode::read(DcmItem &dataset,
                                      const DSRIODConstraintChecker *constraintChecker,
                                      const size_t flags)
{
    return readSRDocumentContentModule(dataset, constraintChecker, flags);
}


OFCondition DSRDocumentTreeNode::write(DcmItem &dataset,
                                       DcmStack *markedItems)
{
    return writeSRDocumentContentModule(dataset, markedItems);
}


OFCondition DSRDocumentTreeNode::readXML(const DSRXMLDocument &doc,
                                         DSRXMLCursor cursor,
                                         const E_DocumentType documentType,
                                         const size_t flags)
{
    OFCondition result = SR_EC_InvalidDocument;
    if (cursor.valid())
    {
        OFString idAttr;
        OFString mappingResource;
        OFString mappingResourceUID;
        OFString templateIdentifier;
        /* important: NULL indicates first child node */
        DSRDocumentTreeNode *node = NULL;
        /* read "id" attribute (optional) and compare with expected value */
        if (!doc.getStringFromAttribute(cursor, idAttr, "id", OFFalse /*encoding*/, OFFalse /*required*/).empty() &&
            (stringToNumber(idAttr.c_str()) != getNodeID()))
        {
            /* create warning message */
            DCMSR_WARN("XML attribute 'id' (" << idAttr << ") deviates from current node number (" << getNodeID() << ")");
        }
        /* template identification information expected "inside" content item */
        if (!(flags & XF_templateElementEnclosesItems))
        {
            /* check for optional template identification */
            const DSRXMLCursor childCursor = doc.getNamedChildNode(cursor, "template", OFFalse /*required*/);
            if (childCursor.valid())
            {
                /* check whether information is stored as XML attributes */
                if (doc.hasAttribute(childCursor, "tid"))
                {
                    doc.getStringFromAttribute(childCursor, mappingResource, "resource");
                    doc.getStringFromAttribute(childCursor, mappingResourceUID, "uid", OFFalse /*encoding*/, OFFalse /*required*/);
                    doc.getStringFromAttribute(childCursor, templateIdentifier, "tid");
                } else {
                    const DSRXMLCursor resourceCursor = doc.getNamedChildNode(childCursor, "resource");
                    if (resourceCursor.valid())
                    {
                        doc.getStringFromAttribute(resourceCursor, mappingResourceUID, "uid", OFFalse /*encoding*/, OFFalse /*required*/);
                        doc.getStringFromNodeContent(resourceCursor, mappingResource);
                    }
                    doc.getStringFromNodeContent(doc.getNamedChildNode(childCursor, "id"), templateIdentifier);
                }
                if (setTemplateIdentification(templateIdentifier, mappingResource, mappingResourceUID).bad())
                    DCMSR_WARN("Content item has invalid/incomplete template identification");
            }
        }
        /* read concept name (not required in some cases) */
        ConceptName.readXML(doc, doc.getNamedChildNode(cursor, "concept", OFFalse /*required*/), flags);
        /* read observation UID and date/time (optional) */
        const DSRXMLCursor childCursor = doc.getNamedChildNode(cursor, "observation", OFFalse /*required*/);
        if (childCursor.valid())
        {
            doc.getStringFromAttribute(childCursor, ObservationUID, "uid", OFFalse /*encoding*/, OFFalse /*required*/);
            DSRDateTimeTreeNode::getValueFromXMLNodeContent(doc, doc.getNamedChildNode(childCursor, "datetime", OFFalse /*required*/), ObservationDateTime);
        }
        /* read node content (depends on value type) */
        result = readXMLContentItem(doc, cursor, flags);
        /* goto first child node */
        cursor.gotoChild();
        /* iterate over all child content items */
        while (cursor.valid() && result.good())
        {
            /* template identification information expected "outside" content item */
            if (flags & XF_templateElementEnclosesItems)
            {
                /* check for optional template identification */
                if (doc.matchNode(cursor, "template"))
                {
                    doc.getStringFromAttribute(cursor, mappingResource, "resource");
                    doc.getStringFromAttribute(cursor, mappingResourceUID, "uid", OFFalse /*encoding*/, OFFalse /*required*/);
                    doc.getStringFromAttribute(cursor, templateIdentifier, "tid");
                    /* goto first child of the "template" element */
                    cursor.gotoChild();
                }
            }
            /* get SR value type from current XML node, also supports "by-reference" detection */
            E_ValueType valueType = doc.getValueTypeFromNode(cursor);
            /* invalid types are silently ignored */
            if (valueType != VT_invalid)
            {
                /* get SR relationship type */
                E_RelationshipType relationshipType = doc.getRelationshipTypeFromNode(cursor);
                /* create new node (by-value or by-reference), do not check constraints */
                result = createAndAppendNewNode(node, relationshipType, valueType);
                if (result.good())
                {
                    if ((flags & XF_templateElementEnclosesItems) && (valueType != VT_byReference))
                    {
                        /* set template identification (if any) */
                        if (node->setTemplateIdentification(templateIdentifier, mappingResource, mappingResourceUID).bad())
                            DCMSR_WARN("Content item has invalid/incomplete template identification");
                    }
                    /* proceed with reading child nodes */
                    result = node->readXML(doc, cursor, documentType, flags);
                    /* print node error message (if any) */
                    doc.printGeneralNodeError(cursor, result);
                } else {
                    /* create new node failed */
                    DCMSR_ERROR("Cannot add \"" << relationshipTypeToReadableName(relationshipType) << " "
                        << valueTypeToDefinedTerm(valueType /*target item*/) << "\" to "
                        << valueTypeToDefinedTerm(ValueType /*source item*/) << " in "
                        << documentTypeToReadableName(documentType));
                }
            }
            /* proceed with next node */
            cursor.gotoNext();
        }
    }
    return result;
}


OFCondition DSRDocumentTreeNode::readXMLContentItem(const DSRXMLDocument & /*doc*/,
                                                    DSRXMLCursor /*cursor*/,
                                                    const size_t /*flags*/)
{
    return EC_IllegalCall;
}


OFCondition DSRDocumentTreeNode::writeXML(STD_NAMESPACE ostream &stream,
                                          const size_t flags) const
{
    OFCondition result = EC_Normal;
    /* check for validity */
    if (!isValid())
        printInvalidContentItemMessage("Writing to XML", this);
    /* write optional template identification */
    if ((flags & XF_writeTemplateIdentification) && !(flags & XF_templateElementEnclosesItems))
    {
        if (hasTemplateIdentification())
        {
            if (flags & XF_templateIdentifierAsAttribute)
            {
                stream << "<template resource=\"" << MappingResource << "\"";
                if (!MappingResourceUID.empty())
                    stream << " uid=\"" << MappingResourceUID << "\"";
                stream << " tid=\"" << TemplateIdentifier << "\"/>" << OFendl;
            } else {
                stream << "<template>" << OFendl;
                stream << "<resource";
                if (!MappingResourceUID.empty())
                    stream << " uid=\"" << MappingResourceUID << "\"";
                stream << ">" << MappingResource << "</resource>" << OFendl;
                writeStringValueToXML(stream, TemplateIdentifier, "id");
                stream << "</template>" << OFendl;
            }
        }
    }
    /* relationship type */
    if ((RelationshipType != RT_isRoot) && !(flags & XF_relationshipTypeAsAttribute))
        writeStringValueToXML(stream, relationshipTypeToDefinedTerm(RelationshipType), "relationship", (flags & XF_writeEmptyTags) > 0);
    /* concept name */
    if (ConceptName.isValid())
    {
        if (flags & XF_codeComponentsAsAttribute)
            stream << "<concept";     // bracket ">" is closed in the next writeXML() routine
        else
            stream << "<concept>" << OFendl;
        ConceptName.writeXML(stream, flags);
        stream << "</concept>" << OFendl;
    }
    if (!(ObservationDateTime.empty() && ObservationUID.empty()))
    {
        /* observation UID (optional) */
        OFString tmpString;
        stream << "<observation";
        if (!ObservationUID.empty())
            stream << " uid=\"" << ObservationUID << "\"";
        stream << ">" << OFendl;
        /* observation date/time (optional) */
        if (!ObservationDateTime.empty())
        {
            /* output time in ISO 8601 format */
            DcmDateTime::getISOFormattedDateTimeFromString(ObservationDateTime, tmpString, OFTrue /*seconds*/, OFFalse /*fraction*/,
                OFTrue /*timeZone*/, OFFalse /*createMissingPart*/, "T" /*dateTimeSeparator*/, "" /*timeZoneSeparator*/);
            writeStringValueToXML(stream, tmpString, "datetime");
        }
        stream << "</observation>" << OFendl;
    }
    /* write child nodes (if any) */
    DSRDocumentTreeNodeCursor cursor(getDown());
    if (cursor.isValid())
    {
        /* for all child nodes */
        do {
            result = cursor.getNode()->writeXML(stream, flags);
        } while (result.good() && cursor.gotoNext());
    }
    return result;
}


void DSRDocumentTreeNode::writeXMLItemStart(STD_NAMESPACE ostream &stream,
                                            const size_t flags,
                                            const OFBool closingBracket) const
{
    /* write optional template identification */
    if ((flags & XF_writeTemplateIdentification) && (flags & XF_templateElementEnclosesItems))
    {
        if (hasTemplateIdentification())
        {
            stream << "<template resource=\"" << MappingResource << "\"";
            if (!MappingResourceUID.empty())
                stream << " uid=\"" << MappingResourceUID << "\"";
            stream << " tid=\"" << TemplateIdentifier << "\">" << OFendl;
        }
    }
    /* write content item */
    if (flags & XF_valueTypeAsAttribute)
    {
        stream << "<item";
        if (ValueType != VT_byReference)
            stream << " valType=\"" << valueTypeToDefinedTerm(ValueType) << "\"";
    } else
        stream << "<" << valueTypeToXMLTagName(ValueType);
    if ((RelationshipType != RT_isRoot) && (flags & XF_relationshipTypeAsAttribute))
        stream << " relType=\"" << relationshipTypeToDefinedTerm(RelationshipType) << "\"";
    if (ReferenceTarget || (flags & XF_alwaysWriteItemIdentifier))
        stream << " id=\"" << getNodeID() << "\"";
    if (closingBracket)
        stream << ">" << OFendl;
}


void DSRDocumentTreeNode::writeXMLItemEnd(STD_NAMESPACE ostream &stream,
                                          const size_t flags) const
{
    /* close content item */
    if (flags & XF_valueTypeAsAttribute)
        stream << "</item>" << OFendl;
    else
        stream << "</" << valueTypeToXMLTagName(ValueType) << ">" << OFendl;
    /* close optional template identification */
    if ((flags & XF_writeTemplateIdentification) && (flags & XF_templateElementEnclosesItems))
    {
        if (hasTemplateIdentification())
            stream << "</template>" << OFendl;
    }
}


OFCondition DSRDocumentTreeNode::renderHTML(STD_NAMESPACE ostream &docStream,
                                            STD_NAMESPACE ostream &annexStream,
                                            const size_t nestingLevel,
                                            size_t &annexNumber,
                                            const size_t flags,
                                            const char *urlPrefix) const
{
    /* check for validity */
    if (!isValid())
        printInvalidContentItemMessage("Rendering", this);
    /* declare hyperlink target */
    if (ReferenceTarget)
    {
        const char *attrName = (flags & DSRTypes::HF_XHTML11Compatibility) ? "id" : "name";
        const char *closeElm = (flags & DSRTypes::HF_XHTML11Compatibility) ? " /" : "></a";
        docStream << "<a " << attrName << "=\"content_item_" << getNodeID() << "\"" << closeElm << ">" << OFendl;
    }
    /* render content item */
    OFCondition result = renderHTMLContentItem(docStream, annexStream, nestingLevel, annexNumber, flags, urlPrefix);
    /* render child nodes */
    if (result.good())
        result = renderHTMLChildNodes(docStream, annexStream, nestingLevel, annexNumber, flags | HF_renderItemsSeparately, urlPrefix);
    else
        printContentItemErrorMessage("Rendering", result, this);
    return result;
}


OFCondition DSRDocumentTreeNode::setRelationshipType(const E_RelationshipType relationshipType)
{
    OFCondition result = EC_Normal;
    /* check parameter before setting the value, "RT_isRoot" is allowed! */
    if ((relationshipType != RT_invalid) && (relationshipType != RT_unknown))
    {
        /* only "unknown" relationship types can be replaced */
        if (RelationshipType == RT_unknown)
            RelationshipType = relationshipType;
        else
            result = SR_EC_CannotChangeRelationshipType;
    } else
        result = EC_IllegalParameter;
    return result;
}


OFCondition DSRDocumentTreeNode::getConceptName(DSRCodedEntryValue &conceptName) const
{
    conceptName = ConceptName;
    return EC_Normal;
}


OFCondition DSRDocumentTreeNode::setConceptName(const DSRCodedEntryValue &conceptName,
                                                const OFBool check)
{
    OFCondition result = EC_Normal;
    /* check for valid code (if not disabled) */
    if (check && !conceptName.isEmpty())
        result = conceptName.checkCurrentValue();
    if (result.good())
        ConceptName = conceptName;
    return result;
}


OFCondition DSRDocumentTreeNode::setObservationDateTime(const OFString &observationDateTime,
                                                        const OFBool check)
{
    OFCondition result = (check) ? DcmDateTime::checkStringValue(observationDateTime, "1") : EC_Normal;
    if (result.good())
        ObservationDateTime = observationDateTime;
    return result;
}


OFCondition DSRDocumentTreeNode::setObservationDateTime(const DcmElement &delem,
                                                        const unsigned long pos,
                                                        const OFBool check)
{
    OFString observationDateTime;
    /* first, get the value from the element (need to cast away "const") */
    OFCondition result = OFconst_cast(DcmElement &, delem).getOFString(observationDateTime, pos);
    if (result.good())
    {
        /* then, check and set the value */
        result = setObservationDateTime(observationDateTime, check);
    }
    return result;
}


OFCondition DSRDocumentTreeNode::setObservationDateTime(DcmItem &dataset,
                                                        const DcmTagKey &tagKey,
                                                        const unsigned long pos,
                                                        const OFBool check)
{
    OFString observationDateTime;
    /* first, get the element value from the dataset */
    OFCondition result = getStringValueFromDataset(dataset, tagKey, observationDateTime, pos);
    if (result.good())
    {
        /* then, check and set the value */
        result = setObservationDateTime(observationDateTime, check);
    }
    return result;
}


OFCondition DSRDocumentTreeNode::setObservationUID(const OFString &observationUID,
                                                   const OFBool check)
{
    OFCondition result = (check) ? DcmUniqueIdentifier::checkStringValue(observationUID, "1") : EC_Normal;
    if (result.good())
        ObservationUID = observationUID;
    return result;
}


OFBool DSRDocumentTreeNode::compareTemplateIdentification(const OFString &templateIdentifier,
                                                          const OFString &mappingResource,
                                                          const OFString &mappingResourceUID) const
{
    OFBool result = (TemplateIdentifier == templateIdentifier) && (MappingResource == mappingResource);
    /* mapping resource UID is optional, so only check it if present */
    if (result && !MappingResourceUID.empty() && !mappingResourceUID.empty())
        result = (MappingResourceUID == mappingResourceUID);
    return result;
}


OFCondition DSRDocumentTreeNode::getTemplateIdentification(OFString &templateIdentifier,
                                                           OFString &mappingResource) const
{
    OFCondition result = SR_EC_InvalidValue;
    /* check for valid value pair */
    if (checkTemplateIdentification(TemplateIdentifier, MappingResource, "" /*mappingResourceUID*/))
    {
        templateIdentifier = TemplateIdentifier;
        mappingResource = MappingResource;
        result = EC_Normal;
    }
    return result;
}


OFCondition DSRDocumentTreeNode::getTemplateIdentification(OFString &templateIdentifier,
                                                           OFString &mappingResource,
                                                           OFString &mappingResourceUID) const
{
    OFCondition result = SR_EC_InvalidValue;
    /* check for valid pair/triple */
    if (checkTemplateIdentification(TemplateIdentifier, MappingResource, MappingResourceUID))
    {
        templateIdentifier = TemplateIdentifier;
        mappingResource = MappingResource;
        mappingResourceUID = MappingResourceUID;
        result = EC_Normal;
    }
    return result;
}


OFCondition DSRDocumentTreeNode::setTemplateIdentification(const OFString &templateIdentifier,
                                                           const OFString &mappingResource,
                                                           const OFString &mappingResourceUID,
                                                           const OFBool check)
{
    OFCondition result = EC_Normal;
    /* basic check for validity (empty or non-empty) */
    if (!checkTemplateIdentification(templateIdentifier, mappingResource, mappingResourceUID))
        result = EC_IllegalParameter;
    /* check more thoroughly whether the passed values are valid */
    else if (check)
    {
        result = DcmCodeString::checkStringValue(templateIdentifier, "1");
        if (result.good())
            result = DcmCodeString::checkStringValue(mappingResource, "1");
        if (result.good())
            result = DcmUniqueIdentifier::checkStringValue(mappingResourceUID, "1");
    }
    if (result.good())
    {
        if ((ValueType != VT_Container) && (ValueType != VT_includedTemplate) && !templateIdentifier.empty())
            DCMSR_WARN("Template identification should only be specified for CONTAINER content items");
        /* set current values, might be empty */
        TemplateIdentifier = templateIdentifier;
        MappingResource = mappingResource;
        MappingResourceUID = mappingResourceUID;
    }
    return result;
}


void DSRDocumentTreeNode::removeSignatures()
{
    MACParameters.clear();
    DigitalSignatures.clear();
}


OFCondition DSRDocumentTreeNode::readContentItem(DcmItem & /*dataset*/,
                                                 const size_t /*flags*/)
{
    /* no content to read */
    return EC_Normal;
}


OFCondition DSRDocumentTreeNode::writeContentItem(DcmItem & /*dataset*/) const
{
    /* no content to write */
    return EC_Normal;
}


OFCondition DSRDocumentTreeNode::renderHTMLContentItem(STD_NAMESPACE ostream & /*docStream*/,
                                                       STD_NAMESPACE ostream & /*annexStream*/,
                                                       const size_t /*nestingLevel*/,
                                                       size_t & /*annexNumber*/,
                                                       const size_t /*flags*/) const
{
    /* no content to render */
    return EC_Normal;
}


OFCondition DSRDocumentTreeNode::renderHTMLContentItem(STD_NAMESPACE ostream &docStream,
                                                       STD_NAMESPACE ostream &annexStream,
                                                       const size_t nestingLevel,
                                                       size_t &annexNumber,
                                                       const size_t flags,
                                                       const char * /*urlPrefix*/) const
{
    /* call the real method (without "urlPrefix" parameter) */
    return renderHTMLContentItem(docStream, annexStream, nestingLevel, annexNumber, flags);
}


OFCondition DSRDocumentTreeNode::readSRDocumentContentModule(DcmItem &dataset,
                                                             const DSRIODConstraintChecker *constraintChecker,
                                                             const size_t flags)
{
    OFCondition result = EC_Normal;
    /* read DocumentRelationshipMacro */
    result = readDocumentRelationshipMacro(dataset, constraintChecker, "1" /*posString*/, flags);
    /* read DocumentContentMacro */
    if (result.good())
        result = readDocumentContentMacro(dataset, "1" /*posString*/, flags);
    return result;
}


OFCondition DSRDocumentTreeNode::writeSRDocumentContentModule(DcmItem &dataset,
                                                              DcmStack *markedItems)
{
    OFCondition result = EC_Normal;
    /* write DocumentRelationshipMacro */
    result = writeDocumentRelationshipMacro(dataset, markedItems);
    /* write DocumentContentMacro */
    if (result.good())
        result = writeDocumentContentMacro(dataset);
    return result;
}


OFCondition DSRDocumentTreeNode::readDocumentRelationshipMacro(DcmItem &dataset,
                                                               const DSRIODConstraintChecker *constraintChecker,
                                                               const OFString &posString,
                                                               const size_t flags)
{
    OFCondition result = EC_Normal;
    /* read digital signatures sequences (optional) */
    if (flags & RF_readDigitalSignatures)
    {
        getElementFromDataset(dataset, MACParameters);
        getElementFromDataset(dataset, DigitalSignatures);
    }
    /* read ObservationDateTime (conditional) */
    getAndCheckStringValueFromDataset(dataset, DCM_ObservationDateTime, ObservationDateTime, "1", "1C");
    /* read ObservationUID (optional) */
    getAndCheckStringValueFromDataset(dataset, DCM_ObservationUID, ObservationUID, "1", "3");
    /* determine template identifier expected for this document */
    OFString expectedTemplateIdentifier;
    OFString expectedMappingResource;
    if (constraintChecker != NULL)
        constraintChecker->getRootTemplateIdentification(expectedTemplateIdentifier, expectedMappingResource);
    /* read ContentTemplateSequence (conditional) */
    DcmItem *ditem = NULL;
    if (dataset.findAndGetSequenceItem(DCM_ContentTemplateSequence, ditem, 0 /*itemNum*/).good())
    {
        if (ValueType != VT_Container)
            DCMSR_WARN("Found Content Template Sequence for content item \"" << posString << "\" which is not a CONTAINER");
        getAndCheckStringValueFromDataset(*ditem, DCM_MappingResource, MappingResource, "1", "1", "ContentTemplateSequence");
        getAndCheckStringValueFromDataset(*ditem, DCM_MappingResourceUID, MappingResourceUID, "1", "3", "ContentTemplateSequence");
        getAndCheckStringValueFromDataset(*ditem, DCM_TemplateIdentifier, TemplateIdentifier, "1", "1", "ContentTemplateSequence");
        /* in case the DICOM Content Mapping Resource (DCMR) is used */
        if (MappingResource == "DCMR")
        {
            /* check whether the correct Mapping Resource UID is used (if present) */
            if (!MappingResourceUID.empty() && (MappingResourceUID != UID_DICOMContentMappingResource))
            {
                DCMSR_WARN("Incorrect value for Mapping Resource UID (" << MappingResourceUID << "), "
                    << UID_DICOMContentMappingResource << " expected");
            }
            /* check for a common error: Template Identifier includes "TID" prefix */
            if (!TemplateIdentifier.empty())
            {
                if ((TemplateIdentifier.find_first_not_of("0123456789") != OFString_npos) || (TemplateIdentifier.at(0) == '0'))
                {
                    DCMSR_DEBUG("Reading invalid Template Identifier (" << TemplateIdentifier << ")");
                    DCMSR_WARN("Template Identifier shall be a string of digits without leading zeros");
                }
            }
        }
        /* check whether the expected template (if known) has been used */
        if (!expectedTemplateIdentifier.empty())
        {
            /* compare with expected mapping resource */
            if (MappingResource != expectedMappingResource)
            {
                DCMSR_WARN("Incorrect value for Mapping Resource ("
                    << ((MappingResource.empty()) ? "<empty>" : MappingResource) << "), "
                    << expectedMappingResource << " expected");
            }
            /* compare with expected template identifier */
            if (TemplateIdentifier != expectedTemplateIdentifier)
            {
                DCMSR_WARN("Incorrect value for Template Identifier ("
                    << ((TemplateIdentifier.empty()) ? "<empty>" : TemplateIdentifier) << "), "
                    << expectedTemplateIdentifier << " expected");
            }
        }
    }
    /* only check template identifier on dataset level (root node) */
    else if ((dataset.ident() == EVR_dataset) && !expectedTemplateIdentifier.empty())
    {
        DCMSR_WARN("Content Template Sequence missing or empty, Template Identifier "
            << expectedTemplateIdentifier << " (" << expectedMappingResource << ") expected");
    }
    /* read ContentSequence */
    if (result.good())
        result = readContentSequence(dataset, constraintChecker, posString, flags);
    return result;
}


OFCondition DSRDocumentTreeNode::writeDocumentRelationshipMacro(DcmItem &dataset,
                                                                DcmStack *markedItems)
{
    OFCondition result = EC_Normal;
    /* write digital signatures sequences (optional) */
    if (!MACParameters.isEmpty())
        addElementToDataset(result, dataset, new DcmSequenceOfItems(MACParameters), "1-n", "3", "SOPCommonModule");
    if (!DigitalSignatures.isEmpty())
    {
        addElementToDataset(result, dataset, new DcmSequenceOfItems(DigitalSignatures), "1-n", "3", "SOPCommonModule");
        DCMSR_WARN("Writing possibly incorrect digital signature - same as read from dataset");
    }
    /* add to marked items stack */
    if (MarkFlag && (markedItems != NULL))
        markedItems->push(&dataset);
    /* write ObservationDateTime (conditional) */
    result = putStringValueToDataset(dataset, DCM_ObservationDateTime, ObservationDateTime, OFFalse /*allowEmpty*/);
    /* write ObservationUID (optional) */
    if (result.good())
        result = putStringValueToDataset(dataset, DCM_ObservationUID, ObservationUID, OFFalse /*allowEmpty*/);
    /* write ContentTemplateSequence (conditional) */
    if (result.good())
    {
        if (hasTemplateIdentification())
        {
            DcmItem *ditem = NULL;
            /* create sequence with a single item */
            result = dataset.findOrCreateSequenceItem(DCM_ContentTemplateSequence, ditem, 0 /*position*/);
            if (result.good())
            {
                if (ValueType != VT_Container)
                    DCMSR_WARN("Writing Content Template Sequence for content item that is not a CONTAINER");
                /* write item data */
                putStringValueToDataset(*ditem, DCM_MappingResource, MappingResource);
                putStringValueToDataset(*ditem, DCM_MappingResourceUID, MappingResourceUID, OFFalse /*allowEmpty*/);
                putStringValueToDataset(*ditem, DCM_TemplateIdentifier, TemplateIdentifier);
            }
        }
    }
    /* write ContentSequence */
    if (result.good())
        result = writeContentSequence(dataset, markedItems);
    return result;
}


OFCondition DSRDocumentTreeNode::readDocumentContentMacro(DcmItem &dataset,
                                                          const OFString &posString,
                                                          const size_t flags)
{
    OFCondition result = EC_Normal;
    /* skip reading ValueType, already done somewhere else */

    /* read ConceptNameCodeSequence */
    if (RelationshipType == RT_isRoot)
    {
        /* the concept name is required for the root container */
        result = ConceptName.readSequence(dataset, DCM_ConceptNameCodeSequence, "1" /*type*/, flags);
    } else {
        /* the concept name might be empty for all other content items */
        ConceptName.readSequence(dataset, DCM_ConceptNameCodeSequence, "1C" /*type*/, flags);
    }
    if (result.good() || (flags & RF_ignoreContentItemErrors))
    {
        if (result.bad())
            DCMSR_DEBUG("Ignoring content item error because of read flag");
        /* read ContentItem (depending on ValueType) */
        result = readContentItem(dataset, flags);
    }
    /* check for validity, after reading */
    if (result.bad() || !isValid())
    {
        printInvalidContentItemMessage("Reading", this, posString.c_str());
        /* ignore content item reading/parsing error if flag is set */
        if (flags & RF_ignoreContentItemErrors)
        {
            DCMSR_DEBUG("Ignoring content item error because of read flag");
            result = EC_Normal;
        }
        /* content item is not valid (see above) */
        else if (result.good())
        {
            /* check whether only the value or the entire content item is invalid */
            result = (!hasValidValue()) ? SR_EC_InvalidValue : SR_EC_InvalidContentItem;
        }
        /* accept invalid content item value if flag is set */
        if ((result == SR_EC_InvalidValue) && (flags & RF_acceptInvalidContentItemValue))
        {
            DCMSR_DEBUG("Ignoring invalid content item value because of read flag");
            result = EC_Normal;
        }
    }
    return result;
}


OFCondition DSRDocumentTreeNode::writeDocumentContentMacro(DcmItem &dataset) const
{
    OFCondition result = EC_Normal;
    /* write ValueType */
    result = putStringValueToDataset(dataset, DCM_ValueType, valueTypeToDefinedTerm(ValueType));
    /* write ConceptNameCodeSequence */
    if (result.good())
    {
        if (ConceptName.isValid())
            result = ConceptName.writeSequence(dataset, DCM_ConceptNameCodeSequence);
    }
    if (result.good())
    {
        /* check for validity, before writing */
        if (!isValid())
            printInvalidContentItemMessage("Writing", this);
        /* write ContentItem (depending on ValueType) */
        result = writeContentItem(dataset);
    }
    return result;
}


OFCondition DSRDocumentTreeNode::createAndAppendNewNode(DSRDocumentTreeNode *&previousNode,
                                                        const E_RelationshipType relationshipType,
                                                        const E_ValueType valueType,
                                                        const DSRIODConstraintChecker *constraintChecker)
{
    OFCondition result = EC_Normal;
    /* do not check by-reference relationships here, will be done later (after complete reading) */
    if ((relationshipType == RT_unknown) || ((relationshipType != RT_invalid) && ((valueType == VT_byReference) ||
        (constraintChecker == NULL) || constraintChecker->checkContentRelationship(ValueType, relationshipType, valueType))))
    {
        DSRDocumentTreeNode *node = createDocumentTreeNode(relationshipType, valueType);
        if (node != NULL)
        {
            /* first child node */
            if (previousNode == NULL)
                Down = node;
            else
            {
                /* new sibling */
                previousNode->Next = node;
                node->Prev = previousNode;
            }
            /* store new node for the next time */
            previousNode = node;
        } else {
            if (valueType == VT_invalid)
                result = SR_EC_UnknownValueType;
            else
                result = EC_MemoryExhausted;
        }
    } else {
        /* summarize what went wrong */
        if (valueType == VT_invalid)
            result = SR_EC_UnknownValueType;
        else if (relationshipType == RT_invalid)
            result = SR_EC_UnknownRelationshipType;
        else
            result = SR_EC_InvalidByValueRelationship;
    }
    return result;
}


OFCondition DSRDocumentTreeNode::readContentSequence(DcmItem &dataset,
                                                     const DSRIODConstraintChecker *constraintChecker,
                                                     const OFString &posString,
                                                     const size_t flags)
{
    OFCondition result = EC_Normal;
    DcmSequenceOfItems *dseq = NULL;
    /* read ContentSequence (might be absent or empty) */
    if (dataset.findAndGetSequence(DCM_ContentSequence, dseq).good())
    {
        OFString tmpString;
        E_ValueType valueType = VT_invalid;
        E_RelationshipType relationshipType = RT_invalid;
        /* important: NULL indicates first child node */
        DSRDocumentTreeNode *node = NULL;
        /* for all items in the sequence */
        unsigned long i = 0;
        DcmObject *dobj = NULL;
        while (((dobj = dseq->nextInContainer(dobj)) != NULL) && result.good())
        {
            DcmItem *ditem = OFstatic_cast(DcmItem *, dobj);
            DSRDocumentTreeNode *newNode = NULL;
            /* create current location string */
            char buffer[20];
            OFString location = posString;
            if (!location.empty())
                location += ".";
            location += numberToString(OFstatic_cast(size_t, i + 1), buffer, sizeof(buffer));
            if (flags & RF_showCurrentlyProcessedItem)
                DCMSR_INFO("Processing content item " << location);
            /* read RelationshipType */
            result = getAndCheckStringValueFromDataset(*ditem, DCM_RelationshipType, tmpString, "1", "1", "content item");
            if (result.good() || (flags & RF_acceptUnknownRelationshipType))
            {
                relationshipType = definedTermToRelationshipType(tmpString);
                /* check relationship type */
                if (relationshipType == RT_invalid)
                {
                    printUnknownValueWarningMessage("RelationshipType", tmpString.c_str());
                    if (flags & RF_acceptUnknownRelationshipType)
                        relationshipType = RT_unknown;
                }
                /* check for by-reference relationship */
                DcmUnsignedLong referencedContentItemIdentifier(DCM_ReferencedContentItemIdentifier);
                if (getAndCheckElementFromDataset(*ditem, referencedContentItemIdentifier, "1-n", "1C", "content item").good())
                {
                    /* create new node (by-reference, no constraint checker required) */
                    result = createAndAppendNewNode(node, relationshipType, VT_byReference);
                    /* read ReferencedContentItemIdentifier (again) */
                    if (result.good())
                    {
                        newNode = node;
                        result = node->readContentItem(*ditem, flags);
                    }
                } else {
                    /* read ValueType (from DocumentContentMacro) - required to create new node */
                    result = getAndCheckStringValueFromDataset(*ditem, DCM_ValueType, tmpString, "1", "1", "content item");
                    if (result.good())
                    {
                        /* read by-value relationship */
                        valueType = definedTermToValueType(tmpString);
                        /* check value type */
                        if (valueType != VT_invalid)
                        {
                            /* create new node (by-value) */
                            result = createAndAppendNewNode(node, relationshipType, valueType, (flags & RF_ignoreRelationshipConstraints) ? NULL : constraintChecker);
                            /* read RelationshipMacro */
                            if (result.good())
                            {
                                newNode = node;
                                result = node->readDocumentRelationshipMacro(*ditem, constraintChecker, location, flags);
                                /* read DocumentContentMacro */
                                if (result.good())
                                    result = node->readDocumentContentMacro(*ditem, location.c_str(), flags);
                            } else {
                                /* create new node failed */

                                /* determine document type */
                                const E_DocumentType documentType = (constraintChecker != NULL) ? constraintChecker->getDocumentType() : DT_invalid;
                                DCMSR_ERROR("Cannot add \"" << relationshipTypeToReadableName(relationshipType) << " "
                                    << valueTypeToDefinedTerm(valueType /*target item*/) << "\" to "
                                    << valueTypeToDefinedTerm(ValueType /*source item*/) << " in "
                                    << documentTypeToReadableName(documentType));
                            }
                        } else {
                            /* unknown/unsupported value type */
                            printUnknownValueWarningMessage("ValueType", tmpString.c_str());
                            result = SR_EC_UnknownValueType;
                        }
                    }
                }
            }
            /* check for any errors */
            if (result.bad())
            {
                printContentItemErrorMessage("Reading", result, newNode, location.c_str());
                /* print current data set (item) that caused the error */
                DCMSR_DEBUG(OFString(31, '-') << " DICOM DATA SET " << OFString(31, '-') << OFendl
                    << DcmObject::PrintHelper(*ditem, DCMTypes::PF_convertToOctalNumbers, 1) << OFString(78, '-'));
            }
            /* increment the counter (needed for generating the location string) */
            i++;
        }
        /* skipping complete subtree if flag is set */
        if (result.bad() && (flags & RF_skipInvalidContentItems))
        {
            printInvalidContentItemMessage("Skipping", node);
            result = EC_Normal;
        }
    }
    return result;
}


OFCondition DSRDocumentTreeNode::writeContentSequence(DcmItem &dataset,
                                                      DcmStack *markedItems) const
{
    OFCondition result = EC_Normal;
    /* goto first child of current node */
    DSRDocumentTreeNodeCursor cursor(getDown());
    if (cursor.isValid())
    {
        /* write ContentSequence */
        DcmSequenceOfItems *dseq = new DcmSequenceOfItems(DCM_ContentSequence);
        if (dseq != NULL)
        {
            DcmItem *ditem = NULL;
            DSRDocumentTreeNode *node = NULL;
            /* for all child nodes */
            do {
                node = cursor.getNode();
                ditem = new DcmItem();
                if (ditem != NULL)
                {
                    /* write RelationshipType */
                    result = putStringValueToDataset(*ditem, DCM_RelationshipType, relationshipTypeToDefinedTerm(node->getRelationshipType()));
                    /* check for by-reference relationship */
                    if (node->getValueType() == VT_byReference)
                    {
                        /* write ReferencedContentItemIdentifier */
                        if (result.good())
                            result = node->writeContentItem(*ditem);
                    } else {    // by-value
                        /* write RelationshipMacro */
                        if (result.good())
                            result = node->writeDocumentRelationshipMacro(*ditem, markedItems);
                        /* write DocumentContentMacro */
                        if (result.good())
                            node->writeDocumentContentMacro(*ditem);
                    }
                    /* check for any errors */
                    if (result.bad())
                        printContentItemErrorMessage("Writing", result, node);
                    /* insert item into sequence */
                    if (result.good())
                        dseq->insert(ditem);
                    else
                        delete ditem;
                } else
                    result = EC_MemoryExhausted;
            } while (result.good() && cursor.gotoNext());
            if (result.good())
                result = dataset.insert(dseq, OFTrue /*replaceOld*/);
            if (result.bad())
                delete dseq;
        } else
            result = EC_MemoryExhausted;
    }
    return result;
}


OFCondition DSRDocumentTreeNode::renderHTMLConceptName(STD_NAMESPACE ostream &docStream,
                                                       const size_t flags) const
{
    if (!(flags & HF_renderItemInline) && (flags & HF_renderItemsSeparately))
    {
        const char *lineBreak = (flags & DSRTypes::HF_renderSectionTitlesInline) ? " " :
                                (flags & DSRTypes::HF_XHTML11Compatibility) ? "<br />" : "<br>";
        /* flag indicating whether line is empty or not */
        OFBool writeLine = OFFalse;
        if (!ConceptName.getCodeMeaning().empty())
        {
            docStream << "<b>";
            /* render ConceptName & Code (if valid) */
            ConceptName.renderHTML(docStream, flags, (flags & HF_renderConceptNameCodes) && ConceptName.isValid() /*fullCode*/);
            docStream << ":</b>";
            writeLine = OFTrue;
        }
        else if (flags & HF_currentlyInsideAnnex)
        {
            docStream << "<b>";
            /* render ValueType only */
            docStream << valueTypeToReadableName(ValueType);
            docStream << ":</b>";
            writeLine = OFTrue;
        }
        /* render optional observation date/time */
        if (!ObservationDateTime.empty())
        {
            if (writeLine)
                docStream << " ";
            OFString tmpString;
            if (flags & HF_XHTML11Compatibility)
                docStream << "<span class=\"observe\">";
            else
                docStream << "<small>";
            docStream << "(observed: " << dicomToReadableDateTime(ObservationDateTime, tmpString) << ")";
            if (flags & HF_XHTML11Compatibility)
                docStream << "</span>";
            else
                docStream << "</small>";
            writeLine = OFTrue;
        }
        if (writeLine)
            docStream << lineBreak << OFendl;
    }
    return EC_Normal;
}


OFCondition DSRDocumentTreeNode::renderHTMLChildNodes(STD_NAMESPACE ostream &docStream,
                                                      STD_NAMESPACE ostream &annexStream,
                                                      const size_t nestingLevel,
                                                      size_t &annexNumber,
                                                      const size_t flags,
                                                      const char *urlPrefix) const
{
    OFCondition result = EC_Normal;
    /* goto first child of current node */
    DSRDocumentTreeNodeCursor cursor(getDown());
    if (cursor.isValid())
    {
        /* flag used to format the relationship reference texts */
        OFBool paragraphFlag = (flags & HF_createFootnoteReferences) > 0;
        /* local version of flags */
        size_t newFlags = flags;
        /* footnote counter */
        size_t footnoteNumber = 1;
        /* create memory output stream for the temporal document */
        OFOStringStream tempDocStream;
        const DSRDocumentTreeNode *node = NULL;
        /* for all child nodes */
        do {
            node = cursor.getNode();
            /* set/reset flag for footnote creation*/
            newFlags &= ~HF_createFootnoteReferences;
            if (!(flags & HF_renderItemsSeparately) && node->hasChildNodes() && (node->getValueType() != VT_Container))
                newFlags |= HF_createFootnoteReferences;
            /* render (optional) reference to annex */
            OFString relationshipText;
            if (!getRelationshipText(node->getRelationshipType(), relationshipText, flags).empty())
            {
                if (paragraphFlag)
                {
                    /* inside paragraph: line break */
                    if (flags & HF_XHTML11Compatibility)
                        docStream << "<br />" << OFendl;
                    else
                        docStream << "<br>" << OFendl;
                } else {
                    /* open paragraph */
                    if (flags & HF_XHTML11Compatibility)
                    {
                        docStream << "<div class=\"small\">" << OFendl;
                        docStream << "<p>" << OFendl;
                    } else {
                        docStream << "<p>" << OFendl;
                        docStream << "<small>" << OFendl;
                    }
                    paragraphFlag = OFTrue;
                }
                if (newFlags & HF_XHTML11Compatibility)
                    docStream << "<span class=\"relation\">" << relationshipText << "</span>: ";
                else if (flags & DSRTypes::HF_HTML32Compatibility)
                    docStream << "<u>" << relationshipText << "</u>: ";
                else /* HTML 4.01 */
                    docStream << "<span class=\"under\">" << relationshipText << "</span>: ";
                /* expand short nodes with no children inline (or depending on 'flags' all nodes) */
                if ((flags & HF_alwaysExpandChildrenInline) ||
                    (!(flags & HF_neverExpandChildrenInline) && !node->hasChildNodes() && node->isShort(flags)))
                {
                    if (node->getValueType() != VT_byReference)
                    {
                        /* render concept name/code or value type */
                        if (node->getConceptName().getCodeMeaning().empty())
                            docStream << valueTypeToReadableName(node->getValueType());
                        else
                            node->getConceptName().renderHTML(docStream, flags, (flags & HF_renderConceptNameCodes) && ConceptName.isValid() /*fullCode*/);
                        docStream << " = ";
                    }
                    /* render HTML code (directly to the reference text) */
                    result = node->renderHTML(docStream, annexStream, 0 /*nesting level*/, annexNumber, newFlags | HF_renderItemInline, urlPrefix);
                } else {
                    /* render concept name or value type */
                    if (node->getConceptName().getCodeMeaning().empty())
                        docStream << valueTypeToReadableName(node->getValueType()) << " ";
                    else
                        docStream << node->getConceptName().getCodeMeaning() << " ";
                    /* render annex heading and reference */
                    createHTMLAnnexEntry(docStream, annexStream, "" /*referenceText*/, annexNumber, newFlags);
                    if (flags & HF_XHTML11Compatibility)
                        annexStream << "<div class=\"para\">" << OFendl;
                    else
                        annexStream << "<div>" << OFendl;
                    /* create memory output stream for the temporal annex */
                    OFOStringStream tempAnnexStream;
                    /* render HTML code (directly to the annex) */
                    result = node->renderHTML(annexStream, tempAnnexStream, 0 /*nesting level*/, annexNumber, newFlags | HF_currentlyInsideAnnex, urlPrefix);
                    annexStream << "</div>" << OFendl;
                    /* use empty paragraph for bottom margin */
                    if (!(flags & HF_XHTML11Compatibility))
                        annexStream << "<p>" << OFendl;
                    /* append temporary stream to main stream */
                    if (result.good())
                        result = appendStream(annexStream, tempAnnexStream);
                }
            } else {
                /* close paragraph */
                if (paragraphFlag)
                {
                    if (flags & HF_XHTML11Compatibility)
                    {
                        docStream << "</p>" << OFendl;
                        docStream << "</div>" << OFendl;
                    } else {
                        docStream << "</small>" << OFendl;
                        docStream << "</p>" << OFendl;
                    }
                    paragraphFlag = OFFalse;
                }
                /* begin new paragraph */
                if (flags & HF_renderItemsSeparately)
                {
                    if (flags & HF_XHTML11Compatibility)
                        docStream << "<div class=\"para\">" << OFendl;
                    else
                        docStream << "<div>" << OFendl;
                }
                /* write footnote text to temporary stream */
                if (newFlags & HF_createFootnoteReferences)
                {
                    /* render HTML code (without child nodes) */
                    result = node->renderHTMLContentItem(docStream, annexStream, 0 /*nestingLevel*/, annexNumber, newFlags, urlPrefix);
                    /* create footnote numbers (individually for each child?) */
                    if (result.good())
                    {
                        /* tags are closed automatically in 'node->renderHTMLChildNodes()' */
                        if (flags & HF_XHTML11Compatibility)
                        {
                            tempDocStream << "<div class=\"small\">" << OFendl;
                            tempDocStream << "<p>" << OFendl;
                        } else {
                            tempDocStream << "<p>" << OFendl;
                            tempDocStream << "<small>" << OFendl;
                        }
                        /* render footnote text and reference */
                        createHTMLFootnote(docStream, tempDocStream, footnoteNumber, node->getNodeID(), flags);
                        /* render child nodes to temporary stream */
                        result = node->renderHTMLChildNodes(tempDocStream, annexStream, 0 /*nestingLevel*/, annexNumber, newFlags, urlPrefix);
                    }
                } else {
                    /* render HTML code (incl. child nodes)*/
                    result = node->renderHTML(docStream, annexStream, nestingLevel + 1, annexNumber, newFlags, urlPrefix);
                }
                /* end paragraph */
                if (flags & HF_renderItemsSeparately)
                {
                    docStream << "</div>" << OFendl;
                    /* use empty paragraph for bottom margin */
                    if (!(flags & HF_XHTML11Compatibility))
                        docStream << "<p>" << OFendl;
                }
            }
        } while (result.good() && cursor.gotoNext());
        /* close last open paragraph (if any) */
        if (paragraphFlag)
        {
            if (flags & HF_XHTML11Compatibility)
            {
                docStream << "</p>" << OFendl;
                docStream << "</div>" << OFendl;
            } else {
                docStream << "</small>" << OFendl;
                docStream << "</p>" << OFendl;
            }
        }
        /* append temporary stream to main stream */
        if (result.good())
            result = appendStream(docStream, tempDocStream);
    }
    return result;
}


// static functions

const OFString &DSRDocumentTreeNode::getRelationshipText(const E_RelationshipType relationshipType,
                                                         OFString &relationshipText,
                                                         const size_t flags)
{
    switch (relationshipType)
    {
        case RT_contains:
            if (flags & HF_createFootnoteReferences)
                relationshipText = "Contains";
            else
                relationshipText.clear();
            break;
        case RT_hasObsContext:
            relationshipText = "Observation Context";
            break;
        case RT_hasAcqContext:
            relationshipText = "Acquisition Context";
            break;
        case RT_hasConceptMod:
            relationshipText = "Concept Modifier";
            break;
        case RT_hasProperties:
            relationshipText = "Properties";
            break;
        case RT_inferredFrom:
            relationshipText = "Inferred from";
            break;
        case RT_selectedFrom:
            relationshipText = "Selected from";
            break;
        default:
            relationshipText.clear();
            break;
    }
    return relationshipText;
}


OFBool DSRDocumentTreeNode::checkTemplateIdentification(const OFString &templateIdentifier,
                                                        const OFString &mappingResource,
                                                        const OFString &mappingResourceUID)
{
    OFBool result = OFFalse;
    /* either all three values are empty or the first two are both non-empty */
    if (templateIdentifier.empty() && mappingResource.empty() && mappingResourceUID.empty())
        result = OFTrue;
    else if (!templateIdentifier.empty() && !mappingResource.empty())
        result = OFTrue;
    return result;
}


// comparison operators

OFBool operator==(const DSRDocumentTreeNode &lhs,
                  const DSRDocumentTreeNode &rhs)
{
    return lhs.isEqual(rhs);
}


OFBool operator!=(const DSRDocumentTreeNode &lhs,
                  const DSRDocumentTreeNode &rhs)
{
    return lhs.isNotEqual(rhs);
}