2 //-----------------------------------------------------------------------------
4 #include "gdcmDocument.h"
5 #include "gdcmValEntry.h"
6 #include "gdcmBinEntry.h"
7 #include "gdcmSeqEntry.h"
9 #include "gdcmGlobal.h"
11 #include "gdcmDebug.h"
20 #include <netinet/in.h>
25 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
26 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
27 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
28 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
31 guint32 totalSQlength;
32 guint32 alreadyParsedlength;
35 //-----------------------------------------------------------------------------
36 // Refer to gdcmDocument::CheckSwap()
37 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
39 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
40 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
42 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
44 //-----------------------------------------------------------------------------
45 // Constructor / Destructor
49 * @param inFilename file to be opened for parsing
50 * @param exception_on_error whether we throw an exception or not
51 * @param enable_sequences = true to allow the header
52 * to be parsed *inside* the SeQuences,
53 * when they have an actual length
54 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
55 * @param ignore_shadow to allow skipping the shadow elements,
56 * to save memory space.
57 * \warning The TRUE value for this param has to be used
58 * with a FALSE value for the 'enable_sequence' param.
59 * ('public elements' may be embedded in 'shadow Sequences')
61 gdcmDocument::gdcmDocument(const char *inFilename,
62 bool exception_on_error,
63 bool enable_sequences,
65 enableSequences=enable_sequences;
66 ignoreShadow =ignore_shadow;
68 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
69 filename = inFilename;
72 if ( !OpenFile(exception_on_error))
77 // return false; // to go on compiling
79 fseek(fp,0L,SEEK_END);
87 //std::cout << "beg, lgt : " << beg << " " << lgt << std::endl;
89 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
92 /* TO DO : uncomment when everything else is OK
94 // --------------------------------------------------------------
95 // Special Patch to allow gdcm to read ACR-LibIDO formated images
97 // if recognition code tells us we deal with a LibIDO image
98 // we switch lineNumber and columnNumber
101 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
102 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
103 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
104 // with "little-endian strings"
106 filetype = ACR_LIBIDO;
107 std::string rows = GetEntryByNumber(0x0028, 0x0010);
108 std::string columns = GetEntryByNumber(0x0028, 0x0011);
109 SetEntryByNumber(columns, 0x0028, 0x0010);
110 SetEntryByNumber(rows , 0x0028, 0x0011);
112 // ----------------- End of Special Patch ----------------
116 printLevel = 1; // 'Medium' print level by default
121 * @param exception_on_error
123 gdcmDocument::gdcmDocument(bool exception_on_error) {
124 (void)exception_on_error;
127 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
130 printLevel = 1; // 'Medium' print level by default
134 * \brief Canonical destructor.
136 gdcmDocument::~gdcmDocument (void) {
141 //-----------------------------------------------------------------------------
147 * \brief Prints The Dict Entries of THE public Dicom Dictionary
150 void gdcmDocument::PrintPubDict(std::ostream & os) {
151 RefPubDict->Print(os);
155 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
158 void gdcmDocument::PrintShaDict(std::ostream & os) {
159 RefShaDict->Print(os);
162 //-----------------------------------------------------------------------------
165 * \brief Get the public dictionary used
167 gdcmDict *gdcmDocument::GetPubDict(void) {
172 * \brief Get the shadow dictionary used
174 gdcmDict *gdcmDocument::GetShaDict(void) {
179 * \brief Set the shadow dictionary used
180 * \param dict dictionary to use in shadow
182 bool gdcmDocument::SetShaDict(gdcmDict *dict){
188 * \brief Set the shadow dictionary used
189 * \param dictName name of the dictionary to use in shadow
191 bool gdcmDocument::SetShaDict(DictKey dictName){
192 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
197 * \brief This predicate, based on hopefully reasonable heuristics,
198 * decides whether or not the current gdcmDocument was properly parsed
199 * and contains the mandatory information for being considered as
200 * a well formed and usable Dicom/Acr File.
201 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
204 bool gdcmDocument::IsReadable(void) {
205 if(filetype==gdcmUnknown) {
208 if(listEntries.size()<=0) {
216 * \brief Determines if the Transfer Syntax was already encountered
217 * and if it corresponds to a ImplicitVRLittleEndian one.
218 * @return True when ImplicitVRLittleEndian found. False in all other cases.
220 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void) {
221 gdcmDocEntry *Element = GetDocEntryByNumber(0x0002, 0x0010);
224 LoadDocEntrySafe(Element);
226 std::string Transfer = Element->GetValue();
227 if ( Transfer == UI1_2_840_10008_1_2 )
233 * \brief Determines if the Transfer Syntax was already encountered
234 * and if it corresponds to a ExplicitVRLittleEndian one.
235 * @return True when ExplicitVRLittleEndian found. False in all other cases.
237 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void) {
238 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
241 LoadDocEntrySafe(Element);
243 std::string Transfer = Element->GetValue();
244 if ( Transfer == UI1_2_840_10008_1_2_1 )
250 * \brief Determines if the Transfer Syntax was already encountered
251 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
252 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
254 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
255 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
258 LoadDocEntrySafe(Element);
260 std::string Transfer = Element->GetValue();
261 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
267 * \brief Determines if the Transfer Syntax was already encountered
268 * and if it corresponds to a Explicit VR Big Endian one.
269 * @return True when big endian found. False in all other cases.
271 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void) {
272 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
275 LoadDocEntrySafe(Element);
277 std::string Transfer = Element->GetValue();
278 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
284 * \brief returns the File Type
285 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
286 * @return the FileType code
288 FileType gdcmDocument::GetFileType(void) {
293 * \brief opens the file
294 * @param exception_on_error
297 FILE *gdcmDocument::OpenFile(bool exception_on_error)
300 fp=fopen(filename.c_str(),"rb");
301 if(exception_on_error)
304 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
310 fread(&zero, (size_t)2, (size_t)1, fp);
312 //ACR -- or DICOM with no Preamble --
313 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
317 fseek(fp, 126L, SEEK_CUR);
319 fread(dicm, (size_t)4, (size_t)1, fp);
320 if( memcmp(dicm, "DICM", 4) == 0 )
324 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
327 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
333 * \brief closes the file
334 * @return TRUE if the close was successfull
336 bool gdcmDocument::CloseFile(void) {
337 int closed = fclose(fp);
345 * \brief Writes in a file all the Header Entries (Dicom Elements)
346 * of the Chained List
347 * @param fp file pointer on an already open file
348 * @param type Type of the File to be written
349 * (ACR-NEMA, ExplicitVR, ImplicitVR)
350 * \return Always true.
352 bool gdcmDocument::Write(FILE *fp, FileType type) {
355 /// The stuff will have to be rewritten using the SeQuence based
356 /// tree-like stucture instead of the chained list .
357 /// (so we shall remove the GroupHT from the gdcmDocument)
361 /// \todo move the following lines (and a lot of others, to be written)
362 /// to a future function CheckAndCorrectHeader
366 /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
367 /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
368 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
370 /// a moins de se livrer a un tres complique ajout des champs manquants.
371 /// faire un CheckAndCorrectHeader (?)
373 if (type == gdcmImplicitVR)
375 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
376 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
378 /// \todo Refer to standards on page 21, chapter 6.2
379 /// "Value representation": values with a VR of UI shall be
380 /// padded with a single trailing null
381 /// Dans le cas suivant on doit pader manuellement avec un 0
383 SetEntryLengthByNumber(18, 0x0002, 0x0010);
386 if (type == gdcmExplicitVR)
388 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
389 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
391 /// \todo Refer to standards on page 21, chapter 6.2
392 /// "Value representation": values with a VR of UI shall be
393 /// padded with a single trailing null
394 /// Dans le cas suivant on doit pader manuellement avec un 0
396 SetEntryLengthByNumber(20, 0x0002, 0x0010);
400 * \todo rewrite later, if really usefull
402 * --> Warning : un-updated odd groups lengths can causes pb
403 * --> (xmedcon breaks)
404 * --> to be re- written with future org.
406 * if ( (type == ImplicitVR) || (type == ExplicitVR) )
407 * UpdateGroupLength(false,type);
409 * UpdateGroupLength(true,ACR);
412 WriteEntries(fp,type);
417 * \brief Modifies the value of a given Header Entry (Dicom Element)
418 * when it exists. Create it with the given value when unexistant.
419 * \warning Adds the Header Entry to the HTable, NOT to the chained List
420 * @param Value Value to be set
421 * @param Group Group of the Entry
422 * @param Elem Element of the Entry
423 * \return pointer to the modified/created Header Entry (NULL when creation
428 gdcmDocEntry * gdcmDocument::ReplaceOrCreateByNumber(
433 a = GetDocEntryByNumber( Group, Elem);
435 a =NewDocEntryByNumber(Group, Elem);
440 SetEntryByNumber(Value, Group, Elem);
441 //a->SetValue(Value);
446 * \brief Set a new value if the invoked element exists
447 * Seems to be useless !!!
448 * @param Value new element value
449 * @param Group group of the Entry
450 * @param Elem element of the Entry
453 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
455 std::string v = Value;
456 SetEntryByNumber(v, Group, Elem);
460 //-----------------------------------------------------------------------------
464 * \brief Checks if a given Dicom Element exists
466 * @param group Group number of the searched Dicom Element
467 * @param element Element number of the searched Dicom Element
468 * @return number of occurences
470 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
471 std::string key = gdcmDictEntry::TranslateToKey(group, element );
472 return (tagHT.count(key));
476 * \brief Searches within Header Entries (Dicom Elements) parsed with
477 * the public and private dictionaries
478 * for the element value of a given tag.
479 * \warning Don't use any longer : use GetPubEntryByName
480 * @param tagName name of the searched element.
481 * @return Corresponding element value when it exists,
482 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
484 std::string gdcmDocument::GetEntryByName(std::string tagName) {
485 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
486 if( dictEntry == NULL)
489 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
493 * \brief Searches within Header Entries (Dicom Elements) parsed with
494 * the public and private dictionaries
495 * for the element value representation of a given tag.
497 * Obtaining the VR (Value Representation) might be needed by caller
498 * to convert the string typed content to caller's native type
499 * (think of C++ vs Python). The VR is actually of a higher level
500 * of semantics than just the native C++ type.
501 * @param tagName name of the searched element.
502 * @return Corresponding element value representation when it exists,
503 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
505 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
506 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
507 if( dictEntry == NULL)
510 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
511 dictEntry->GetElement());
512 return elem->GetVR();
517 * \brief Searches within Header Entries (Dicom Elements) parsed with
518 * the public and private dictionaries
519 * for the element value representation of a given tag.
520 * @param group Group of the searched tag.
521 * @param element Element of the searched tag.
522 * @return Corresponding element value representation when it exists,
523 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
525 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
526 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
527 if ( ! tagHT.count(key))
529 return tagHT.find(key)->second->GetValue();
533 * \brief Searches within Header Entries (Dicom Elements) parsed with
534 * the public and private dictionaries
535 * for the element value representation of a given tag..
537 * Obtaining the VR (Value Representation) might be needed by caller
538 * to convert the string typed content to caller's native type
539 * (think of C++ vs Python). The VR is actually of a higher level
540 * of semantics than just the native C++ type.
541 * @param group Group of the searched tag.
542 * @param element Element of the searched tag.
543 * @return Corresponding element value representation when it exists,
544 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
546 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
547 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
550 return elem->GetVR();
554 * \brief Searches within Header Entries (Dicom Elements) parsed with
555 * the public and private dictionaries
556 * for the value length of a given tag..
557 * @param group Group of the searched tag.
558 * @param element Element of the searched tag.
559 * @return Corresponding element length; -2 if not found
561 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
562 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
565 return elem->GetLength();
568 * \brief Sets the value (string) of the Header Entry (Dicom Element)
569 * @param content string value of the Dicom Element
570 * @param tagName name of the searched Dicom Element.
571 * @return true when found
573 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
574 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
575 if( dictEntry == NULL)
578 return(SetEntryByNumber(content,dictEntry->GetGroup(),
579 dictEntry->GetElement()));
583 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
584 * through it's (group, element) and modifies it's content with
586 * @param content new value to substitute with
587 * @param group group of the Dicom Element to modify
588 * @param element element of the Dicom Element to modify
590 bool gdcmDocument::SetEntryByNumber(std::string content,
594 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
595 if ( ! tagHT.count(key))
597 int l = content.length();
598 if(l%2) // Non even length are padded with a space (020H).
601 content = content + '\0';
606 TagDocEntryHT::iterator p2;
607 // DO NOT remove the following lines : they explain the stuff
608 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
609 //p2=p.first; // iterator on the first synonym
610 //a=p2->second; // H Table target column (2-nd col)
614 // Oops ! this was for multimap, right ?
615 a = ((tagHT.equal_range(key)).first)->second;
617 ((gdcmValEntry*)a)->SetValue(content);
619 std::string vr = a->GetVR();
622 if( (vr == "US") || (vr == "SS") )
624 else if( (vr == "UL") || (vr == "SL") )
634 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
635 * in the PubDocEntrySet of this instance
636 * through it's (group, element) and modifies it's length with
638 * \warning Use with extreme caution.
639 * @param l new length to substitute with
640 * @param group group of the Entry to modify
641 * @param element element of the Entry to modify
642 * @return true on success, false otherwise.
644 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
648 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
649 if ( ! tagHT.count(key))
651 if (l%2) l++; // length must be even
652 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
658 * \brief Gets (from Header) the offset of a 'non string' element value
659 * (LoadElementValues has already be executed)
660 * @param Group group of the Entry
661 * @param Elem element of the Entry
662 * @return File Offset of the Element Value
664 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
666 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
669 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
670 "failed to Locate gdcmDocEntry");
673 return Entry->GetOffset();
677 * \brief Gets (from Header) a 'non string' element value
678 * (LoadElementValues has already be executed)
679 * @param Group group of the Entry
680 * @param Elem element of the Entry
681 * @return Pointer to the 'non string' area
683 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
685 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
688 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
689 "failed to Locate gdcmDocEntry");
692 return ((gdcmBinEntry *)Entry)->GetVoidArea();
696 * \brief Loads (from disk) the element content
697 * when a string is not suitable
698 * @param Group group of the Entry
699 * @param Elem element of the Entry
701 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
703 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
706 size_t o =(size_t)Element->GetOffset();
707 fseek(fp, o, SEEK_SET);
708 size_t l=Element->GetLength();
709 char* a = new char[l];
713 SetEntryVoidAreaByNumber(a, Group, Elem);
714 /// \todo check the result
715 size_t l2 = fread(a, 1, l ,fp);
726 * \brief Sets a 'non string' value to a given Dicom Element
728 * @param group Group number of the searched Dicom Element
729 * @param element Element number of the searched Dicom Element
732 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
736 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
737 if ( ! tagHT.count(key))
739 // This was for multimap ?
740 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
746 * \brief Update the entries with the shadow dictionary.
747 * Only non even entries are analyzed
749 void gdcmDocument::UpdateShaEntries(void) {
750 gdcmDictEntry *entry;
753 for(ListTag::iterator it=listEntries.begin();
754 it!=listEntries.end();
757 // Odd group => from public dictionary
758 if((*it)->GetGroup()%2==0)
761 // Peer group => search the corresponding dict entry
763 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
767 if((*it)->IsImplicitVR())
772 //(*it)->SetValue(GetDocEntryUnvalue(*it));
773 // to go on compiling
775 // Set the new entry and the new value
776 (*it)->SetDictEntry(entry);
777 CheckDocEntryVR(*it,vr);
779 //(*it)->SetValue(GetDocEntryValue(*it));
780 // to go on compiling
785 // Remove precedent value transformation
786 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
792 * \brief Searches within the Header Entries for a Dicom Element of
794 * @param tagName name of the searched Dicom Element.
795 * @return Corresponding Dicom Element when it exists, and NULL
798 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
799 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
800 if( dictEntry == NULL)
803 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
807 * \brief retrieves a Dicom Element (the first one) using (group, element)
808 * \warning (group, element) IS NOT an identifier inside the Dicom Header
809 * if you think it's NOT UNIQUE, check the count number
810 * and use iterators to retrieve ALL the Dicoms Elements within
811 * a given couple (group, element)
812 * @param group Group number of the searched Dicom Element
813 * @param element Element number of the searched Dicom Element
816 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
818 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
819 if ( ! tagHT.count(key))
821 return tagHT.find(key)->second;
825 * \brief retrieves the Dicom Elements (all of them) using (group, element)
826 * @param group Group number of the searched Dicom Element.
827 * @param element Element number of the searched Dicom Element.
828 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
831 IterHT gdcmDocument::GetDocEntrySameNumber(guint16 group, guint16 element){
832 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
833 return (tagHT.equal_range(key));
837 * \brief Loads the element while preserving the current
838 * underlying file position indicator as opposed to
839 * to LoadDocEntry that modifies it.
840 * @param entry Header Entry whose value shall be loaded.
843 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
844 long PositionOnEntry = ftell(fp);
846 fseek(fp, PositionOnEntry, SEEK_SET);
850 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
851 * \warning : to be re-written using the chained list instead of the H table.
852 * \warning : DO NOT use (doesn't work any longer because of the multimap)
853 * \todo : to be re-written using the chained list instead of the H table
854 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
855 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
858 /* Probabely useless, now !
860 void gdcmDocument::UpdateGroupLength(bool SkipSequence, FileType type) {
866 std::string str_trash;
869 GroupHT groupHt; // to hold the length of each group
872 // typedef std::map<GroupKey, int> GroupHT;
876 // for each Tag in the DCM Header
878 for (TagDocEntryHT::iterator tag2 = tagHT.begin();
883 gr = elem->GetGroup();
884 el = elem->GetElement();
887 sprintf(trash, "%04x", gr);
888 key = trash; // generate 'group tag'
890 // if the caller decided not to take SEQUENCEs into account
891 // e.g : he wants to write an ACR-NEMA File
893 if (SkipSequence && vr == "SQ")
896 // Still unsolved problem :
897 // we cannot find the 'Sequence Delimitation Item'
898 // since it's at the end of the Hash Table
901 // there is SEQUENCE in ACR-NEMA
903 // --> la descente a l'interieur' des SQ
904 // devrait etre faite avec une liste chainee, pas avec une HTable...
906 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
908 if (el == 0x0000) // the first elem is 0x0000
910 groupHt[key] = 0; // initialize group length
914 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
917 else // any elem but the first
919 if (type == ExplicitVR)
921 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
923 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
926 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
930 unsigned short int gr_bid;
932 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
936 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
937 // warning: unsigned int format, different type arg
938 sscanf(g->first.c_str(),"%x",&gr_bid); //FIXME
939 tk = g->first + "|0000"; // generate the element full tag
941 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
943 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
944 elemZ = new gdcmDocEntry(tagZ);
946 AddEntry(elemZ); // create it
950 elemZ=GetDocEntryByNumber(gr_bid, 0x0000);
952 sprintf(trash ,"%d",g->second);
954 //elemZ->SetValue(str_trash); // to go on compiling
961 * \brief Writes in a file (according to the requested format)
962 * the group, the element, the value representation and the length
963 * of a single gdcmDocEntry passed as argument.
964 * @param tag pointer on the gdcmDocEntry to be written
965 * @param _fp already open file pointer
966 * @param type type of the File to be written
968 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
972 guint16 group = tag->GetGroup();
973 std::string vr = tag->GetVR();
974 guint16 el = tag->GetElement();
975 guint32 lgr = tag->GetReadLength();
977 if ( (group == 0xfffe) && (el == 0x0000) )
978 // Fix in order to make some MR PHILIPS images e-film readable
979 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
980 // we just *always* ignore spurious fffe|0000 tag !
983 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
984 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
986 if ( type == gdcmExplicitVR ) {
988 // Special case of delimiters:
989 if (group == 0xfffe) {
990 // Delimiters have NO Value Representation and have NO length.
991 // Hence we skip writing the VR and length and we pad by writing
995 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1000 guint16 shortLgr = lgr;
1001 if (vr == "unkn") { // Unknown was 'written'
1002 // deal with Little Endian
1003 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1004 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1006 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1007 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1009 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1010 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1012 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1018 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1023 * \brief Writes in a file (according to the requested format)
1024 * the value of a single gdcmDocEntry passed as argument.
1025 * @param tag Pointer on the gdcmDocEntry to be written
1026 * @param _fp Already open file pointer
1027 * @param type type of the File to be written
1030 // TODO : to be re -written recursively !
1032 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1035 guint16 group = tag->GetGroup();
1036 std::string vr = tag->GetVR();
1037 guint32 lgr = tag->GetReadLength();
1040 // SeQuences have no value:
1042 if (group == 0xfffe)
1043 // Delimiters have no associated value:
1047 // voidArea = tag->GetVoidArea();
1048 // to go on compiling
1049 if (voidArea != NULL)
1050 { // there is a 'non string' LUT, overlay, etc
1051 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1055 if (vr == "US" || vr == "SS")
1057 // some 'Short integer' fields may be mulivaluated
1058 // each single value is separated from the next one by '\'
1059 // we split the string and write each value as a short int
1060 std::vector<std::string> tokens;
1061 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1062 Tokenize (tag->GetValue(), tokens, "\\");
1063 for (unsigned int i=0; i<tokens.size();i++)
1065 guint16 val_uint16 = atoi(tokens[i].c_str());
1066 void *ptr = &val_uint16;
1067 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1072 // some 'Integer' fields may be mulivaluated
1073 // each single value is separated from the next one by '\'
1074 // we split the string and write each value as an int
1075 if (vr == "UL" || vr == "SL")
1077 std::vector<std::string> tokens;
1078 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1079 Tokenize (tag->GetValue(), tokens, "\\");
1080 for (unsigned int i=0; i<tokens.size();i++)
1082 guint32 val_uint32 = atoi(tokens[i].c_str());
1083 void *ptr = &val_uint32;
1084 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1089 fwrite (tag->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1093 * \brief Writes in a file (according to the requested format)
1094 * a single gdcmDocEntry passed as argument.
1095 * \sa WriteEntryValue, WriteEntryTagVRLength.
1096 * @param tag Pointer on the gdcmDocEntry to be written
1097 * @param _fp Already open file pointer
1098 * @param type type of the File to be written
1101 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1103 guint32 length = tag->GetLength();
1105 // The value of a tag MUST (see the DICOM norm) be an odd number of
1106 // bytes. When this is not the case, pad with an additional byte:
1109 // tag->SetValue(tag->GetValue()+"\0");
1110 // to go on compiling
1111 tag->SetLength(tag->GetReadLength()+1);
1114 WriteEntryTagVRLength(tag, _fp, type);
1115 WriteEntryValue(tag, _fp, type);
1120 * \brief writes on disc according to the requested format
1121 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1122 * using the Chained List
1123 * \warning does NOT add the missing elements in the header :
1124 * it's up to the user doing it !
1125 * (function CheckHeaderCoherence to be written)
1126 * \warning DON'T try, right now, to write a DICOM image
1127 * from an ACR Header (meta elements will be missing!)
1128 * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1129 * @param type type of the File to be written
1130 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1131 * @param _fp already open file pointer
1134 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1136 /// \todo (?) check write failures (after *each* fwrite)
1138 for (ListTag::iterator tag2=listEntries.begin();
1139 tag2 != listEntries.end();
1142 if ( type == gdcmACR ){
1143 if ((*tag2)->GetGroup() < 0x0008)
1144 // Ignore pure DICOM V3 groups
1146 if ((*tag2)->GetElement() %2)
1147 // Ignore the "shadow" groups
1149 if ((*tag2)->GetVR() == "SQ" ) // ignore Sequences
1151 if ((*tag2)->GetSQDepthLevel() != 0) // Not only ignore the SQ element
1154 if (! WriteEntry(*tag2,_fp,type) )
1161 * \brief writes on disc according to the requested format
1162 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1163 * using only the last synonym of each mutimap H Table post.
1164 * \warning Uses the H Table, instead of the Chained List
1165 * in order to be compliant with the old way to proceed
1166 * (added elements taken in to account)
1167 * Only THERALYS, during a transitory phase is supposed
1168 * to use this method !!!
1169 * \warning DON'T try, right now, to write a DICOM image
1170 * from an ACR Header (meta elements will be missing!)
1172 * @param _fp already open file pointer
1173 * @param type type of the File to be written
1174 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1176 void gdcmDocument::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1178 // restent a tester les echecs en ecriture (apres chaque fwrite)
1180 for (TagDocEntryHT::iterator tag2=tagHT.begin();
1181 tag2 != tagHT.end();
1183 if ( type == gdcmACR ){
1184 if ((*tag2->second).GetGroup() < 0x0008) continue; // ignore pure DICOM V3 groups
1185 if ((*tag2->second).GetElement() %2) continue; // ignore shadow groups
1186 if ((*tag2->second).GetVR() == "SQ" ) continue; // ignore Sequences
1187 if ((*tag2->second).GetSQDepthLevel() != 0) continue; // Not only ignore the SQ element
1189 if ( ! WriteEntry(tag2->second,_fp,type))
1195 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1197 * @return The properly swaped 32 bits integer.
1199 guint32 gdcmDocument::SwapLong(guint32 a) {
1204 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1205 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1209 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1213 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1216 std::cout << "swapCode= " << sw << std::endl;
1217 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1224 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1226 * @return The properly unswaped 32 bits integer.
1228 guint32 gdcmDocument::UnswapLong(guint32 a) {
1229 return (SwapLong(a));
1233 * \brief Swaps the bytes so they agree with the processor order
1234 * @return The properly swaped 16 bits integer.
1236 guint16 gdcmDocument::SwapShort(guint16 a) {
1237 if ( (sw==4321) || (sw==2143) )
1238 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1243 * \brief Unswaps the bytes so they agree with the processor order
1244 * @return The properly unswaped 16 bits integer.
1246 guint16 gdcmDocument::UnswapShort(guint16 a) {
1247 return (SwapShort(a));
1250 //-----------------------------------------------------------------------------
1256 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1257 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1260 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1262 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1268 cout << hex << "offset " << offset
1269 << " l_max "<< l_max
1270 << " ftell a l'entree " << ftell(fp)
1273 NewDocEntry = ReadNextDocEntry( );
1279 << NewDocEntry->GetGroup()
1281 << NewDocEntry->GetElement()
1283 << NewDocEntry->GetVR()
1285 << NewDocEntry->GetReadLength()
1287 << NewDocEntry->GetOffset()
1290 vr = NewDocEntry->GetVR();
1293 if (vr == "AE" || vr == "AS" || vr == "DA" || vr == "PN" ||
1294 vr == "UI" || vr == "TM" || vr == "SH" || vr == "LO" ||
1295 vr == "CS" || vr == "IS" || vr == "LO" || vr == "LT" ||
1296 vr == "SH" || vr == "ST" ||
1297 vr == "SL" || vr == "SS" || vr == "UL" || vr == "US"
1300 vl= new gdcmValEntry(NewDocEntry->GetDictEntry());
1301 vl->Copy(NewDocEntry);
1304 std::cout << "value [" << vl->GetValue() << "]" << std::endl;
1305 if (/*!delim_mode && */vl->isItemDelimitor())
1308 << " l_max = "<< l_max
1309 << " offset = " << offset
1310 << " ftell(fp) = " << ftell(fp)
1312 if ( !delim_mode && ftell(fp)-offset >= l_max)
1314 } else { // BinEntry
1316 // Hope the following VR *do* correspond to a BinEntry
1318 //AT Attribute Tag; // 2 16-bit unsigned short integers
1319 //FL Floating Point Single; // 32-bit IEEE 754:1985 float
1320 //FD Floating Point Double; // 64-bit IEEE 754:1985 double
1321 //UN Unknown; // Any length of bytes
1322 //UT Unlimited Text; // At most 2^32 -1 chars
1323 //OB Other Byte String; // String of bytes (VR independant)
1324 //OW Other Word String; // String of 16-bit words (VR dependant)
1326 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1327 bn->Copy(NewDocEntry);
1329 std::cout << "value [" << "Bin Entry, in voidArea" << "]" << std::endl;
1332 SkipToNextDocEntry(NewDocEntry); // to be sure we are at the beginning
1333 l = NewDocEntry->GetFullLength();
1335 } else { // VR = "SQ"
1337 std::cout << "gdcmDocument::ParseDES : SQ found " << std::endl;
1338 l=NewDocEntry->GetReadLength();
1340 if (l == 0xffffffff)
1345 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry());
1346 sq->Copy(NewDocEntry);
1347 sq->SetDelimitorMode(delim_mode);
1349 if (l != 0) { // Don't try to parse zero-length sequences
1350 long lgt = ParseSQ((gdcmDocEntrySet *)sq,
1351 //NewDocEntry->GetOffset(),
1352 offset, // marche pour DICOMDIR, plante sur 3...dcm
1355 // FIXME : on en fait quoi, de lgt ?
1357 cout << " l_max = " << l_max
1358 << " offset = " << offset
1359 << "ftell(fp) = " << ftell(fp)
1361 if ( !delim_mode && ftell(fp)-offset >= l_max)
1371 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1372 * @return parsed length for this level
1374 long gdcmDocument::ParseSQ(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1376 cout << "=================== gdcmDocument::ParseSQ on entre ds une Sequence"
1378 << " offset " << offset
1379 << " l_max " << l_max
1380 << " delim_mode " << delim_mode
1382 int SQItemNumber = 0;
1383 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1389 std::cout << " ===== gdcmDocument::ParseSQ on itere "
1390 << "sur les SQ Items : num "
1391 << SQItemNumber << std::endl;
1393 NewDocEntry = ReadNextDocEntry();
1394 cout << "=============================== isSequenceDelimitor "
1395 << NewDocEntry->isSequenceDelimitor()
1398 if (NewDocEntry->isSequenceDelimitor()) {
1399 cout << " SequenceDelimitationItem found" << endl;
1400 // add the Sequence Delimitor // TODO : find the trick to put it proprerly !
1401 // ((gdcmSeqEntry *)set)->SetSequenceDelimitationItem(NewDocEntry);
1405 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1407 << " offset " << offset
1408 << " l_max " << l_max
1409 << " ftell " << ftell(fp)
1411 cout << "depasse ou atteint : on sort " << endl;
1414 itemSQ = new gdcmSQItem();
1415 itemSQ->AddEntry(NewDocEntry); // no value, no voidArea. Think of it while printing !
1416 l= NewDocEntry->GetReadLength();
1417 cout << "NewDocEntry->GetReadLength() " << l << endl;
1422 cout << "================================ appel ParseDES :dlm_mod = " << dlm_mod <<endl;
1423 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1424 ((gdcmSeqEntry *)set)->AddEntry(itemSQ);
1425 cout << "================================ sortie ParseDES " << endl;
1429 lgth = ftell(fp) - offset;
1430 cout << "=============== lgr Sequence :" << lgth <<endl;
1436 * \brief Parses the header of the file and load element values.
1437 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1440 /* =======================================================================
1441 // Replaced by ParseSQ
1443 bool gdcmDocument::LoadHeaderEntries(bool exception_on_error) throw(gdcmFormatError) {
1444 (void)exception_on_error;
1449 gdcmDocEntry *newDocEntry = (gdcmDocEntry *)0;
1450 while ( (newDocEntry = ReadNextDocEntry()) ) {
1451 SkipDocEntry(newDocEntry);
1452 if ( (ignoreShadow==0) || (newDocEntry->GetGroup()%2) == 0) {
1453 AddEntry(newDocEntry);
1457 // Be carefull : merging this two loops may cause troubles ...
1458 for (ListTag::iterator i = GetListEntry().begin();
1459 i != GetListEntry().end();
1466 // Load 'non string' values
1469 // --------------------------------------------------------------
1470 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1472 // if recognition code tells us we deal with a LibIDO image
1473 // we switch lineNumber and columnNumber
1475 std::string RecCode;
1476 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1477 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1478 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
1479 // with "little-endian strings"
1481 filetype = ACR_LIBIDO;
1482 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1483 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1484 SetEntryByNumber(columns, 0x0028, 0x0010);
1485 SetEntryByNumber(rows , 0x0028, 0x0011);
1487 // ----------------- End of Special Patch ----------------
1490 ======================================================================= */
1494 * \brief Loads the element content if its length doesn't exceed
1495 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1496 * @param Entry Header Entry (Dicom Element) to be dealt with
1498 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry) {
1500 guint16 group = Entry->GetGroup();
1501 std::string vr= Entry->GetVR();
1502 guint32 length = Entry->GetLength();
1504 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1506 // A SeQuence "contains" a set of Elements.
1507 // (fffe e000) tells us an Element is beginning
1508 // (fffe e00d) tells us an Element just ended
1509 // (fffe e0dd) tells us the current SeQuence just ended
1510 if( group == 0xfffe ) {
1511 // NO more value field for SQ !
1512 //Entry->SetValue("gdcm::Skipped");
1513 // appel recursif de Load Value
1514 // (meme pb que pour le parsing)
1518 // When the length is zero things are easy:
1519 if ( length == 0 ) {
1520 ((gdcmValEntry *)Entry)->SetValue("");
1524 // The elements whose length is bigger than the specified upper bound
1525 // are not loaded. Instead we leave a short notice of the offset of
1526 // the element content and it's length.
1527 if (length > MaxSizeLoadEntry) {
1528 std::ostringstream s;
1529 s << "gdcm::NotLoaded.";
1530 s << " Address:" << (long)Entry->GetOffset();
1531 s << " Length:" << Entry->GetLength();
1532 s << " x(" << std::hex << Entry->GetLength() << ")";
1533 ((gdcmValEntry *)Entry)->SetValue(s.str());
1537 // Any compacter code suggested (?)
1538 if ( IsDocEntryAnInteger(Entry) ) {
1540 std::ostringstream s;
1542 // When short integer(s) are expected, read and convert the following
1543 // n *two characters properly i.e. as short integers as opposed to strings.
1544 // Elements with Value Multiplicity > 1
1545 // contain a set of integers (not a single one)
1546 if (vr == "US" || vr == "SS") {
1548 NewInt = ReadInt16();
1551 for (int i=1; i < nbInt; i++) {
1553 NewInt = ReadInt16();
1558 // When integer(s) are expected, read and convert the following
1559 // n * four characters properly i.e. as integers as opposed to strings.
1560 // Elements with Value Multiplicity > 1
1561 // contain a set of integers (not a single one)
1562 else if (vr == "UL" || vr == "SL") {
1564 NewInt = ReadInt32();
1567 for (int i=1; i < nbInt; i++) {
1569 NewInt = ReadInt32();
1574 #ifdef GDCM_NO_ANSI_STRING_STREAM
1575 s << std::ends; // to avoid oddities on Solaris
1576 #endif //GDCM_NO_ANSI_STRING_STREAM
1578 ((gdcmValEntry *)Entry)->SetValue(s.str());
1582 // We need an additional byte for storing \0 that is not on disk
1583 std::string NewValue(length,0);
1584 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1585 if ( item_read != 1 ) {
1586 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1587 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1591 if( (vr == "UI") ) // Because of correspondance with the VR dic
1592 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1594 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1599 * \brief Find the value Length of the passed Header Entry
1600 * @param Entry Header Entry whose length of the value shall be loaded.
1602 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1603 guint16 element = Entry->GetElement();
1604 //guint16 group = Entry->GetGroup(); //FIXME
1605 std::string vr = Entry->GetVR();
1609 if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1611 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1613 // The following reserved two bytes (see PS 3.5-2001, section
1614 // 7.1.2 Data element structure with explicit vr p27) must be
1615 // skipped before proceeding on reading the length on 4 bytes.
1616 fseek(fp, 2L, SEEK_CUR);
1617 guint32 length32 = ReadInt32();
1619 if ( (vr == "OB") && (length32 == 0xffffffff) )
1621 Entry->SetLength(FindDocEntryLengthOB());
1624 FixDocEntryFoundLength(Entry, length32);
1628 // Length is encoded on 2 bytes.
1629 length16 = ReadInt16();
1631 // We can tell the current file is encoded in big endian (like
1632 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1633 // and it's value is the one of the encoding of a big endian file.
1634 // In order to deal with such big endian encoded files, we have
1635 // (at least) two strategies:
1636 // * when we load the "Transfer Syntax" tag with value of big endian
1637 // encoding, we raise the proper flags. Then we wait for the end
1638 // of the META group (0x0002) among which is "Transfer Syntax",
1639 // before switching the swap code to big endian. We have to postpone
1640 // the switching of the swap code since the META group is fully encoded
1641 // in little endian, and big endian coding only starts at the next
1642 // group. The corresponding code can be hard to analyse and adds
1643 // many additional unnecessary tests for regular tags.
1644 // * the second strategy consists in waiting for trouble, that shall
1645 // appear when we find the first group with big endian encoding. This
1646 // is easy to detect since the length of a "Group Length" tag (the
1647 // ones with zero as element number) has to be of 4 (0x0004). When we
1648 // encounter 1024 (0x0400) chances are the encoding changed and we
1649 // found a group with big endian encoding.
1650 // We shall use this second strategy. In order to make sure that we
1651 // can interpret the presence of an apparently big endian encoded
1652 // length of a "Group Length" without committing a big mistake, we
1653 // add an additional check: we look in the already parsed elements
1654 // for the presence of a "Transfer Syntax" whose value has to be "big
1655 // endian encoding". When this is the case, chances are we have got our
1656 // hands on a big endian encoded file: we switch the swap code to
1657 // big endian and proceed...
1658 if ( (element == 0x0000) && (length16 == 0x0400) )
1660 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1662 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1667 SwitchSwapToBigEndian();
1668 // Restore the unproperly loaded values i.e. the group, the element
1669 // and the dictionary entry depending on them.
1670 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1671 guint16 CorrectElem = SwapShort(Entry->GetElement());
1672 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1676 // This correct tag is not in the dictionary. Create a new one.
1677 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1679 // FIXME this can create a memory leaks on the old entry that be
1680 // left unreferenced.
1681 Entry->SetDictEntry(NewTag);
1684 // Heuristic: well some files are really ill-formed.
1685 if ( length16 == 0xffff)
1688 //dbg.Verbose(0, "gdcmDocument::FindLength",
1689 // "Erroneous element length fixed.");
1690 // Actually, length= 0xffff means that we deal with
1691 // Unknown Sequence Length
1693 FixDocEntryFoundLength(Entry, (guint32)length16);
1698 // Either implicit VR or a non DICOM conformal (see note below) explicit
1699 // VR that ommited the VR of (at least) this element. Farts happen.
1700 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1701 // on Data elements "Implicit and Explicit VR Data Elements shall
1702 // not coexist in a Data Set and Data Sets nested within it".]
1703 // Length is on 4 bytes.
1705 FixDocEntryFoundLength(Entry, ReadInt32());
1711 * \brief Find the Value Representation of the current Dicom Element.
1714 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1716 if (filetype != gdcmExplicitVR)
1721 long PositionOnEntry = ftell(fp);
1722 // Warning: we believe this is explicit VR (Value Representation) because
1723 // we used a heuristic that found "UL" in the first tag. Alas this
1724 // doesn't guarantee that all the tags will be in explicit VR. In some
1725 // cases (see e-film filtered files) one finds implicit VR tags mixed
1726 // within an explicit VR file. Hence we make sure the present tag
1727 // is in explicit VR and try to fix things if it happens not to be
1730 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1732 if(!CheckDocEntryVR(Entry,VR))
1734 fseek(fp, PositionOnEntry, SEEK_SET);
1735 // When this element is known in the dictionary we shall use, e.g. for
1736 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1737 // dictionary entry. Still we have to flag the element as implicit since
1738 // we know now our assumption on expliciteness is not furfilled.
1740 if ( Entry->IsVRUnknown() )
1741 Entry->SetVR("Implicit");
1742 Entry->SetImplicitVR();
1747 * \brief Check the correspondance between the VR of the header entry
1748 * and the taken VR. If they are different, the header entry is
1749 * updated with the new VR.
1750 * @param Entry Header Entry to check
1751 * @param vr Dicom Value Representation
1752 * @return false if the VR is incorrect of if the VR isn't referenced
1753 * otherwise, it returns true
1755 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1757 char msg[100]; // for sprintf
1758 bool RealExplicit = true;
1760 // Assume we are reading a falsely explicit VR file i.e. we reached
1761 // a tag where we expect reading a VR but are in fact we read the
1762 // first to bytes of the length. Then we will interogate (through find)
1763 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1764 // both GCC and VC++ implementations of the STL map. Hence when the
1765 // expected VR read happens to be non-ascii characters we consider
1766 // we hit falsely explicit VR tag.
1768 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1769 RealExplicit = false;
1771 // CLEANME searching the dicom_vr at each occurence is expensive.
1772 // PostPone this test in an optional integrity check at the end
1773 // of parsing or only in debug mode.
1774 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1775 RealExplicit= false;
1777 if ( !RealExplicit )
1779 // We thought this was explicit VR, but we end up with an
1780 // implicit VR tag. Let's backtrack.
1781 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1782 Entry->GetGroup(),Entry->GetElement());
1783 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1784 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1785 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1786 Entry->GetGroup(),Entry->GetElement(),
1787 "UL","FIXME","Group Length");
1788 Entry->SetDictEntry(NewEntry);
1793 if ( Entry->IsVRUnknown() )
1795 // When not a dictionary entry, we can safely overwrite the VR.
1796 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1802 else if ( Entry->GetVR() != vr )
1804 // The VR present in the file and the dictionary disagree. We assume
1805 // the file writer knew best and use the VR of the file. Since it would
1806 // be unwise to overwrite the VR of a dictionary (since it would
1807 // compromise it's next user), we need to clone the actual DictEntry
1808 // and change the VR for the read one.
1809 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1810 Entry->GetGroup(),Entry->GetElement(),
1811 vr,"FIXME",Entry->GetName());
1812 Entry->SetDictEntry(NewEntry);
1818 * \brief Get the transformed value of the header entry. The VR value
1819 * is used to define the transformation to operate on the value
1820 * \warning NOT end user intended method !
1822 * @return Transformed entry value
1824 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1826 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1828 std::string val=Entry->GetValue();
1829 std::string vr=Entry->GetVR();
1830 guint32 length = Entry->GetLength();
1831 std::ostringstream s;
1834 // When short integer(s) are expected, read and convert the following
1835 // n * 2 bytes properly i.e. as a multivaluated strings
1836 // (each single value is separated fromthe next one by '\'
1837 // as usual for standard multivaluated filels
1838 // Elements with Value Multiplicity > 1
1839 // contain a set of short integers (not a single one)
1841 if (vr == "US" || vr == "SS")
1846 for (int i=0; i < nbInt; i++)
1850 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1851 NewInt16 = SwapShort(NewInt16);
1856 // When integer(s) are expected, read and convert the following
1857 // n * 4 bytes properly i.e. as a multivaluated strings
1858 // (each single value is separated fromthe next one by '\'
1859 // as usual for standard multivaluated filels
1860 // Elements with Value Multiplicity > 1
1861 // contain a set of integers (not a single one)
1862 else if (vr == "UL" || vr == "SL")
1867 for (int i=0; i < nbInt; i++)
1871 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1872 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1873 NewInt32=SwapLong(NewInt32);
1877 #ifdef GDCM_NO_ANSI_STRING_STREAM
1878 s << std::ends; // to avoid oddities on Solaris
1879 #endif //GDCM_NO_ANSI_STRING_STREAM
1883 return(Entry->GetValue());
1887 * \brief Get the reverse transformed value of the header entry. The VR
1888 * value is used to define the reverse transformation to operate on
1890 * \warning NOT end user intended method !
1892 * @return Reverse transformed entry value
1894 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1896 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1898 std::string vr=Entry->GetVR();
1899 std::ostringstream s;
1900 std::vector<std::string> tokens;
1902 if (vr == "US" || vr == "SS")
1906 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1907 Tokenize (Entry->GetValue(), tokens, "\\");
1908 for (unsigned int i=0; i<tokens.size();i++)
1910 NewInt16 = atoi(tokens[i].c_str());
1911 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1915 if (vr == "UL" || vr == "SL")
1919 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1920 Tokenize (Entry->GetValue(), tokens, "\\");
1921 for (unsigned int i=0; i<tokens.size();i++)
1923 NewInt32 = atoi(tokens[i].c_str());
1924 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1925 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1930 #ifdef GDCM_NO_ANSI_STRING_STREAM
1931 s << std::ends; // to avoid oddities on Solaris
1932 #endif //GDCM_NO_ANSI_STRING_STREAM
1936 return(Entry->GetValue());
1940 * \brief Skip a given Header Entry
1941 * \warning NOT end user intended method !
1944 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1946 SkipBytes(entry->GetLength());
1950 * \brief Skips to the begining of the next Header Entry
1951 * \warning NOT end user intended method !
1954 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1956 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1957 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1961 * \brief Loads the value for a a given VLEntry
1962 * \warning NOT end user intended method !
1965 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
1967 //SkipBytes(entry->GetLength());
1968 LoadDocEntry(entry);
1971 * \brief When the length of an element value is obviously wrong (because
1972 * the parser went Jabberwocky) one can hope improving things by
1973 * applying this heuristic.
1975 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry, guint32 FoundLength)
1977 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1978 if ( FoundLength == 0xffffffff) {
1982 guint16 gr =Entry->GetGroup();
1983 guint16 el =Entry->GetElement();
1985 if (FoundLength%2) {
1986 std::ostringstream s;
1987 s << "Warning : Tag with uneven length " << FoundLength
1988 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1989 dbg.Verbose(0,s.str().c_str());
1992 // Sorry for the patch!
1993 // XMedCom did the trick to read some naughty GE images ...
1994 if (FoundLength == 13) {
1995 // The following 'if' will be removed when there is no more
1996 // images on Creatis HDs with a 13 length for Manufacturer...
1997 if ( (Entry->GetGroup() != 0x0008) ||
1998 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1999 // end of remove area
2001 Entry->SetReadLength(10); // a bug is to be fixed
2005 // to fix some garbage 'Leonardo' Siemens images
2006 // May be commented out to avoid overhead
2007 else if ( (Entry->GetGroup() == 0x0009) &&
2008 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
2010 Entry->SetReadLength(4); // a bug is to be fixed
2014 // to try to 'go inside' SeQuences (with length), and not to skip them
2015 else if ( Entry->GetVR() == "SQ")
2017 if (enableSequences) // only if the user does want to !
2018 FoundLength =0; // ReadLength is unchanged
2021 // we found a 'delimiter' element
2022 // fffe|xxxx is just a marker, we don't take its length into account
2023 else if(Entry->GetGroup() == 0xfffe)
2025 // *normally, fffe|0000 doesn't exist !
2026 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
2027 // causes extra troubles :-(
2031 Entry->SetUsableLength(FoundLength);
2035 * \brief Apply some heuristics to predict whether the considered
2036 * element value contains/represents an integer or not.
2037 * @param Entry The element value on which to apply the predicate.
2038 * @return The result of the heuristical predicate.
2040 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2041 guint16 element = Entry->GetElement();
2042 guint16 group = Entry->GetGroup();
2043 std::string vr = Entry->GetVR();
2044 guint32 length = Entry->GetLength();
2045 // When we have some semantics on the element we just read, and if we
2046 // a priori know we are dealing with an integer, then we shall be
2047 // able to swap it's element value properly.
2048 if ( element == 0 ) // This is the group length of the group
2054 std::ostringstream s;
2055 int filePosition = ftell(fp);
2056 s << "Erroneous Group Length element length on : (" \
2057 << std::hex << group << " , " << element
2058 << ") -before- position x(" << filePosition << ")"
2059 << "lgt : " << length;
2060 // These 2 lines commented out : a *very dirty* patch
2061 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
2062 // have a glance at offset x(8336) ...
2063 // For *regular* headers, the test is useless..
2064 // lets's print a warning message and go on,
2065 // instead of giving up with an error message
2067 //std::cout << s.str().c_str() << std::endl;
2068 // dbg.Error("gdcmDocument::IsDocEntryAnInteger",
2069 // s.str().c_str());
2072 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2078 * \brief Find the Length till the next sequence delimiter
2079 * \warning NOT end user intended method !
2083 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2084 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2087 long PositionOnEntry = ftell(fp);
2088 bool FoundSequenceDelimiter = false;
2089 guint32 TotalLength = 0;
2092 while ( ! FoundSequenceDelimiter)
2098 TotalLength += 4; // We even have to decount the group and element
2100 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2102 char msg[100]; // for sprintf. Sorry
2103 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2104 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2108 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2109 FoundSequenceDelimiter = true;
2110 else if ( n != 0xe000 )
2112 char msg[100]; // for sprintf. Sorry
2113 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2115 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2119 ItemLength = ReadInt32();
2120 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2121 // the ItemLength with ReadInt32
2122 SkipBytes(ItemLength);
2124 fseek(fp, PositionOnEntry, SEEK_SET);
2129 * \brief Reads a supposed to be 16 Bits integer
2130 * (swaps it depending on processor endianity)
2131 * @return read value
2133 guint16 gdcmDocument::ReadInt16(void) {
2136 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2137 if ( item_read != 1 ) {
2139 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2149 * \brief Reads a supposed to be 32 Bits integer
2150 * (swaps it depending on processor endianity)
2151 * @return read value
2153 guint32 gdcmDocument::ReadInt32(void) {
2156 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2157 if ( item_read != 1 ) {
2159 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2169 * \brief skips bytes inside the source file
2170 * \warning NOT end user intended method !
2173 void gdcmDocument::SkipBytes(guint32 NBytes) {
2174 //FIXME don't dump the returned value
2175 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2179 * \brief Loads all the needed Dictionaries
2180 * \warning NOT end user intended method !
2182 void gdcmDocument::Initialise(void)
2184 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2185 RefShaDict = (gdcmDict*)0;
2189 * \brief Discover what the swap code is (among little endian, big endian,
2190 * bad little endian, bad big endian).
2192 * @return false when we are absolutely sure
2193 * it's neither ACR-NEMA nor DICOM
2194 * true when we hope ours assuptions are OK
2196 bool gdcmDocument::CheckSwap() {
2198 // The only guaranted way of finding the swap code is to find a
2199 // group tag since we know it's length has to be of four bytes i.e.
2200 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2201 // occurs when we can't find such group...
2203 guint32 x=4; // x : for ntohs
2204 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2210 char deb[HEADER_LENGTH_TO_READ];
2212 // First, compare HostByteOrder and NetworkByteOrder in order to
2213 // determine if we shall need to swap bytes (i.e. the Endian type).
2219 // The easiest case is the one of a DICOM header, since it possesses a
2220 // file preamble where it suffice to look for the string "DICM".
2221 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2224 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2225 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2227 // Next, determine the value representation (VR). Let's skip to the
2228 // first element (0002, 0000) and check there if we find "UL"
2229 // - or "OB" if the 1st one is (0002,0001) -,
2230 // in which case we (almost) know it is explicit VR.
2231 // WARNING: if it happens to be implicit VR then what we will read
2232 // is the length of the group. If this ascii representation of this
2233 // length happens to be "UL" then we shall believe it is explicit VR.
2234 // FIXME: in order to fix the above warning, we could read the next
2235 // element value (or a couple of elements values) in order to make
2236 // sure we are not commiting a big mistake.
2237 // We need to skip :
2238 // * the 128 bytes of File Preamble (often padded with zeroes),
2239 // * the 4 bytes of "DICM" string,
2240 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2241 // i.e. a total of 136 bytes.
2245 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2246 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2247 // *Implicit* VR. -and it is !-
2249 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2250 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2251 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2252 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2253 // when Write DCM *adds*
2255 // Use gdcmDocument::dicom_vr to test all the possibilities
2256 // instead of just checking for UL, OB and UI !? group 0000
2258 filetype = gdcmExplicitVR;
2259 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2260 "explicit Value Representation");
2264 filetype = gdcmImplicitVR;
2265 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2266 "not an explicit Value Representation");
2272 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2273 "HostByteOrder != NetworkByteOrder");
2278 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2279 "HostByteOrder = NetworkByteOrder");
2282 // Position the file position indicator at first tag (i.e.
2283 // after the file preamble and the "DICM" string).
2285 fseek (fp, 132L, SEEK_SET);
2289 // Alas, this is not a DicomV3 file and whatever happens there is no file
2290 // preamble. We can reset the file position indicator to where the data
2291 // is (i.e. the beginning of the file).
2292 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2295 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2296 // By clean we mean that the length of the first tag is written down.
2297 // If this is the case and since the length of the first group HAS to be
2298 // four (bytes), then determining the proper swap code is straightforward.
2301 // We assume the array of char we are considering contains the binary
2302 // representation of a 32 bits integer. Hence the following dirty
2304 s32 = *((guint32 *)(entCur));
2325 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2326 // It is time for despaired wild guesses.
2327 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2328 // i.e. the 'group length' element is not present :
2330 // check the supposed to be 'group number'
2331 // 0x0002 or 0x0004 or 0x0008
2332 // to determine ' sw' value .
2333 // Only 0 or 4321 will be possible
2334 // (no oportunity to check for the formerly well known
2335 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2336 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2337 // the file IS NOT ACR-NEMA nor DICOM V3
2338 // Find a trick to tell it the caller...
2340 s16 = *((guint16 *)(deb));
2356 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2357 "ACR/NEMA unfound swap info (Really hopeless !)");
2358 filetype = gdcmUnknown;
2362 // Then the only info we have is the net2host one.
2372 * \brief Restore the unproperly loaded values i.e. the group, the element
2373 * and the dictionary entry depending on them.
2375 void gdcmDocument::SwitchSwapToBigEndian(void)
2377 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2378 "Switching to BigEndian mode.");
2399 * \brief during parsing, Header Elements too long are not loaded in memory
2402 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2406 if ((guint32)NewSize >= (guint32)0xffffffff)
2408 MaxSizeLoadEntry = 0xffffffff;
2411 MaxSizeLoadEntry = NewSize;
2416 * \brief Header Elements too long will not be printed
2417 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2420 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2424 if ((guint32)NewSize >= (guint32)0xffffffff)
2426 MaxSizePrintEntry = 0xffffffff;
2429 MaxSizePrintEntry = NewSize;
2435 * \brief Read the next tag but WITHOUT loading it's value
2436 * (read the 'Group Number', the 'Element Number',
2437 * gets the Dict Entry
2438 * gets the VR, gets the length, gets the offset value)
2439 * @return On succes the newly created DocEntry, NULL on failure.
2441 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2443 gdcmDocEntry *NewEntry;
2448 // We reached the EOF (or an error occured) therefore
2449 // header parsing has to be considered as finished.
2450 return (gdcmDocEntry *)0;
2452 // Pb : how to propagate the element length (used in SkipDocEntry)
2453 // direct call to SkipBytes ?
2455 // if (ignoreShadow == 1 && g%2 ==1)
2456 // if user wants to skip shadow groups
2457 // and current element *is* a shadow element
2458 // we don't create anything
2459 // return (gdcmDocEntry *)1; // to tell caller it's NOT finished
2461 NewEntry = NewDocEntryByNumber(g, n);
2462 FindDocEntryVR(NewEntry);
2463 FindDocEntryLength(NewEntry);
2470 NewEntry->SetOffset(ftell(fp));
2475 * \brief Build a new Element Value from all the low level arguments.
2476 * Check for existence of dictionary entry, and build
2477 * a default one when absent.
2478 * @param Name Name of the underlying DictEntry
2480 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2482 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2484 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2486 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2489 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2490 "failed to allocate gdcmDocEntry");
2491 return (gdcmDocEntry *)0;
2497 * \brief Request a new virtual dict entry to the dict set
2498 * @param group group of the underlying DictEntry
2499 * @param element element of the underlying DictEntry
2500 * @param vr VR of the underlying DictEntry
2501 * @param fourth owner group
2502 * @param name english name
2504 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2509 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2513 * \brief Build a new Element Value from all the low level arguments.
2514 * Check for existence of dictionary entry, and build
2515 * a default one when absent.
2516 * @param Group group of the underlying DictEntry
2517 * @param Elem element of the underlying DictEntry
2519 gdcmDocEntry *gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2521 // Find out if the tag we encountered is in the dictionaries:
2522 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2524 DictEntry = NewVirtualDictEntry(Group, Elem);
2526 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2529 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2530 "failed to allocate gdcmDocEntry");
2536 /// \todo Never used; commented out, waiting for removal.
2538 * \brief Small utility function that creates a new manually crafted
2539 * (as opposed as read from the file) gdcmDocEntry with user
2540 * specified name and adds it to the public tag hash table.
2541 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2542 * @param NewTagName The name to be given to this new tag.
2543 * @param VR The Value Representation to be given to this new tag.
2544 * @return The newly hand crafted Element Value.
2546 //gdcmDocEntry *gdcmDocument::NewManualDocEntryToPubDict(std::string NewTagName,
2549 // gdcmDocEntry *NewEntry = NULL;
2550 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2551 // guint32 FreeElem = 0;
2552 // gdcmDictEntry *DictEntry = NULL;
2554 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2555 // if (FreeElem == UINT32_MAX)
2557 // dbg.Verbose(1, "gdcmHeader::NewManualDocEntryToPubDict",
2558 // "Group 0xffff in Public Dict is full");
2562 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2563 // VR, "GDCM", NewTagName);
2564 // NewEntry = new gdcmDocEntry(DictEntry);
2565 // AddEntry(NewEntry);
2570 * \brief Generate a free TagKey i.e. a TagKey that is not present
2571 * in the TagHt dictionary.
2572 * @param group The generated tag must belong to this group.
2573 * @return The element of tag with given group which is fee.
2575 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2577 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2579 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2580 if (tagHT.count(key) == 0)
2588 * \brief Searches both the public and the shadow dictionary (when they
2589 * exist) for the presence of the DictEntry with given name.
2590 * The public dictionary has precedence on the shadow one.
2591 * @param Name name of the searched DictEntry
2592 * @return Corresponding DictEntry when it exists, NULL otherwise.
2594 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2596 gdcmDictEntry *found = (gdcmDictEntry *)0;
2597 if (!RefPubDict && !RefShaDict)
2599 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2600 "we SHOULD have a default dictionary");
2604 found = RefPubDict->GetDictEntryByName(Name);
2610 found = RefShaDict->GetDictEntryByName(Name);
2618 * \brief Searches both the public and the shadow dictionary (when they
2619 * exist) for the presence of the DictEntry with given
2620 * group and element. The public dictionary has precedence on the
2622 * @param group group of the searched DictEntry
2623 * @param element element of the searched DictEntry
2624 * @return Corresponding DictEntry when it exists, NULL otherwise.
2626 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2628 gdcmDictEntry *found = (gdcmDictEntry *)0;
2629 if (!RefPubDict && !RefShaDict)
2631 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2632 "we SHOULD have a default dictionary");
2636 found = RefPubDict->GetDictEntryByNumber(group, element);
2642 found = RefShaDict->GetDictEntryByNumber(group, element);
2651 //-----------------------------------------------------------------------------