2 //-----------------------------------------------------------------------------
10 #include <netinet/in.h>
13 #ifdef GDCM_NO_ANSI_STRING_STREAM
15 # define ostringstream ostrstream
21 #include "gdcmParser.h"
22 #include "gdcmGlobal.h"
24 #include "gdcmDebug.h"
26 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
27 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
28 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
29 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
32 guint32 totalSQlength;
33 guint32 alreadyParsedlength;
36 //-----------------------------------------------------------------------------
37 // Refer to gdcmParser::CheckSwap()
38 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
40 // Refer to gdcmParser::SetMaxSizeLoadEntry()
41 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
43 // Refer to gdcmParser::SetMaxSizePrintEntry()
44 // TODO : Right now, better see "define, in gdcmHederEntry.cxx
45 const unsigned int gdcmParser::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
47 //-----------------------------------------------------------------------------
48 // Constructor / Destructor
52 * @param inFilename file to be opened for parsing
53 * @param exception_on_error whether we throw an exception or not
54 * @param enable_sequences = true to allow the header
55 * to be parsed *inside* the SeQuences,
56 * when they have an actual length
57 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
58 * @param ignore_shadow to allow skipping the shadow elements,
59 * to save memory space.
60 * \warning The TRUE value for this param has to be used
61 * with a FALSE value for the 'enable_sequence' param.
62 * ('public elements' may be embedded in 'shadow Sequences')
64 gdcmParser::gdcmParser(const char *inFilename,
65 bool exception_on_error,
66 bool enable_sequences,
68 enableSequences=enable_sequences;
69 ignoreShadow =ignore_shadow;
71 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
72 filename = inFilename;
75 if ( !OpenFile(exception_on_error))
82 wasUpdated = 0; // will be set to 1 if user adds an entry
83 printLevel = 1; // 'Medium' print level by default
89 * @param exception_on_error
91 gdcmParser::gdcmParser(bool exception_on_error) {
92 (void)exception_on_error;
95 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
98 wasUpdated = 0; // will be set to 1 if user adds an entry
99 printLevel = 1; // 'Medium' print level by default
103 * \ingroup gdcmParser
104 * \brief Canonical destructor.
106 gdcmParser::~gdcmParser (void) {
111 //-----------------------------------------------------------------------------
114 * \ingroup gdcmParser
115 * \brief Prints the Header Entries (Dicom Elements)
116 * from the chained list
119 void gdcmParser::PrintEntry(std::ostream & os) {
121 for (ListTag::iterator i = listEntries.begin();
122 i != listEntries.end();
125 (*i)->SetPrintLevel(printLevel);
131 * \ingroup gdcmParser
132 * \brief Prints the Header Entries (Dicom Elements)
133 * from the chained list
134 * and skips the elements belonging to a 'no length' SeQuence
137 void gdcmParser::PrintEntryNoSQ(std::ostream & os) {
139 for (ListTag::iterator i = listEntries.begin();
140 i != listEntries.end();
143 if ( (*i)->GetVR() == "SQ"){
147 if ( (*i)->GetGroup() == 0xfffe && (*i)->GetElement() == 0xe0dd){
153 (*i)->SetPrintLevel(printLevel);
160 * \ingroup gdcmParser
161 * \brief Prints the Header Entries (Dicom Elements)
162 * from the chained list
163 * and indents the elements belonging to any SeQuence
164 * \warning : will be removed
167 void gdcmParser::PrintEntryNiceSQ(std::ostream & os) {
168 pileElem pile[50]; // Hope embedded sequence depth is no more than 50
171 int currentParsedlength = 0;
172 int totalElementlength;
173 std::ostringstream tab;
176 int DEBUG = 0; // Sorry; Dealing with e-film breaker images
177 // will (certainly) cause a lot of troubles ...
178 // I prefer keeping my 'trace' on .
180 for (ListTag::iterator i = listEntries.begin();
181 i != listEntries.end();
183 if ( (*i)->GetVR() == "SQ" && (*i)->GetReadLength() != 0) { // SQ found
187 std::cout << "Kaie ! Kaie! SQ stack overflow" << std::endl;
190 if (DEBUG) std::cout << "\n >>>>> empile niveau " << top
191 << "; Lgr SeQ: " << (*i)->GetReadLength()
194 pile[top].totalSQlength = (*i)->GetReadLength();
195 pile[top].alreadyParsedlength = 0;
196 currentParsedlength = 0;
198 } else { // non SQ found
200 if (countSQ != 0) { // we are 'inside a SeQuence'
201 if ( (*i)->GetGroup()==0xfffe && (*i)->GetElement()==0xe0dd){
202 // we just found 'end of SeQuence'
205 std::cout << "fffe,e0dd : depile" << std::endl;
206 currentParsedlength += 8; // gr:2 elem:2 vr:2 lgt:2
209 pile[top].alreadyParsedlength += currentParsedlength;
211 // we are on a 'standard' elem
212 // or a Zero-length SeQuence
214 totalElementlength = (*i)->GetFullLength();
215 currentParsedlength += totalElementlength;
216 pile[top].alreadyParsedlength += totalElementlength;
218 if (pile[top].totalSQlength == 0xffffffff) {
220 std::cout << "totalSeQlength == 0xffffffff"
224 std::cout << "alrdyPseLgt:"
225 << pile[top].alreadyParsedlength << " totSeQlgt: "
226 << pile[top].totalSQlength << " curPseLgt: "
227 << currentParsedlength
229 while (pile[top].alreadyParsedlength==pile[top].totalSQlength) {
232 std::cout << " \n<<<<<< On depile niveau " << top
233 << "\n" << std::endl;
235 currentParsedlength = pile[top].alreadyParsedlength;
240 pile[top].alreadyParsedlength += currentParsedlength +12;
241 // 12 : length of 'SQ embedded' SQ element
242 currentParsedlength += 8; // gr:2 elem:2 vr:2 lgt:2
245 std::cout << pile[top].alreadyParsedlength << " "
246 << pile[top].totalSQlength << " "
247 << currentParsedlength
251 currentParsedlength = 0;
257 } // end : 'inside a SeQuence'
261 for (int i=0;i<countSQ;i++)
264 (*i)->SetPrintLevel(printLevel);
273 * \brief Prints The Dict Entries of THE public Dicom Dictionary
276 void gdcmParser::PrintPubDict(std::ostream & os) {
277 RefPubDict->Print(os);
281 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
284 void gdcmParser::PrintShaDict(std::ostream & os) {
285 RefShaDict->Print(os);
288 //-----------------------------------------------------------------------------
291 * \brief Get the public dictionary used
293 gdcmDict *gdcmParser::GetPubDict(void) {
298 * \brief Get the shadow dictionary used
300 gdcmDict *gdcmParser::GetShaDict(void) {
305 * \brief Set the shadow dictionary used
306 * \param dict dictionary to use in shadow
308 bool gdcmParser::SetShaDict(gdcmDict *dict){
314 * \brief Set the shadow dictionary used
315 * \param dictName name of the dictionary to use in shadow
317 bool gdcmParser::SetShaDict(DictKey dictName){
318 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
323 * \brief This predicate, based on hopefully reasonable heuristics,
324 * decides whether or not the current gdcmParser was properly parsed
325 * and contains the mandatory information for being considered as
326 * a well formed and usable Dicom/Acr File.
327 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
330 bool gdcmParser::IsReadable(void) {
331 if(filetype==Unknown) {
334 if(listEntries.size()<=0) {
342 * \brief Determines if the Transfer Syntax was already encountered
343 * and if it corresponds to a ImplicitVRLittleEndian one.
344 * @return True when ImplicitVRLittleEndian found. False in all other cases.
346 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
347 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
350 LoadHeaderEntrySafe(Element);
352 std::string Transfer = Element->GetValue();
353 if ( Transfer == UI1_2_840_10008_1_2 )
359 * \ingroup gdcmParser
360 * \brief Determines if the Transfer Syntax was already encountered
361 * and if it corresponds to a ExplicitVRLittleEndian one.
362 * @return True when ExplicitVRLittleEndian found. False in all other cases.
364 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
365 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
368 LoadHeaderEntrySafe(Element);
370 std::string Transfer = Element->GetValue();
371 if ( Transfer == UI1_2_840_10008_1_2_1 )
377 * \brief Determines if the Transfer Syntax was already encountered
378 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
379 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
381 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
382 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
385 LoadHeaderEntrySafe(Element);
387 std::string Transfer = Element->GetValue();
388 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
394 * \brief Determines if the Transfer Syntax was already encountered
395 * and if it corresponds to a Explicit VR Big Endian one.
396 * @return True when big endian found. False in all other cases.
398 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
399 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
402 LoadHeaderEntrySafe(Element);
404 std::string Transfer = Element->GetValue();
405 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
411 * \brief returns the File Type
412 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
413 * @return the FileType code
415 FileType gdcmParser::GetFileType(void) {
420 * \brief opens the file
421 * @param exception_on_error
424 FILE *gdcmParser::OpenFile(bool exception_on_error)
427 fp=fopen(filename.c_str(),"rb");
428 if(exception_on_error)
431 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
437 fread(&zero, (size_t)2, (size_t)1, fp);
439 //ACR -- or DICOM with no Preamble --
440 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
444 fseek(fp, 126L, SEEK_CUR);
446 fread(dicm, (size_t)4, (size_t)1, fp);
447 if( memcmp(dicm, "DICM", 4) == 0 )
451 dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
454 dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
460 * \brief closes the file
461 * @return TRUE if the close was successfull
463 bool gdcmParser::CloseFile(void) {
464 int closed = fclose(fp);
472 * \brief Writes in a file all the Header Entries (Dicom Elements)
473 * of the Chained List
474 * @param fp file pointer on an already open file
475 * @param type Type of the File to be written
476 * (ACR-NEMA, ExplicitVR, ImplicitVR)
477 * \return Always true.
479 bool gdcmParser::Write(FILE *fp, FileType type) {
481 // TODO The stuff was rewritten using the chained list instead
483 // so we could remove the GroupHT from the gdcmParser
487 // TODO : move the following lines (and a lot of others, to be written)
488 // to a future function CheckAndCorrectHeader
491 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier
492 // DicomV3 ou non (FileType est un champ de gdcmParser ...)
493 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
495 // a moins de se livrer a un tres complique ajout des champs manquants.
496 // faire un CheckAndCorrectHeader (?)
498 if (type == ImplicitVR)
500 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
501 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
503 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
504 // values with a VR of UI shall be padded with a single trailing null
505 // Dans le cas suivant on doit pader manuellement avec un 0
507 SetEntryLengthByNumber(18, 0x0002, 0x0010);
510 if (type == ExplicitVR)
512 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
513 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
515 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
516 // values with a VR of UI shall be padded with a single trailing null
517 // Dans le cas suivant on doit pader manuellement avec un 0
519 SetEntryLengthByNumber(20, 0x0002, 0x0010);
522 /* TODO : rewrite later, if really usefull
524 --> Warning : un-updated odd groups lengths can causes pb
526 --> to be re- written with future org.
528 if ( (type == ImplicitVR) || (type == ExplicitVR) )
529 UpdateGroupLength(false,type);
531 UpdateGroupLength(true,ACR);
534 WriteEntries(fp,type);
539 * \brief Modifies the value of a given Header Entry (Dicom Element)
540 * when it exists. Create it with the given value when unexistant.
541 * \warning Adds the Header Entry to the HTable, NOT to the chained List
542 * @param Value Value to be set
543 * @param Group Group of the Entry
544 * @param Elem Element of the Entry
545 * \return pointer to the modified/created Header Entry (NULL when creation
548 gdcmHeaderEntry * gdcmParser::ReplaceOrCreateByNumber(
553 a = GetHeaderEntryByNumber( Group, Elem);
555 a =NewHeaderEntryByNumber(Group, Elem);
560 //CLEANME SetEntryByNumber(Value, Group, Elem);
566 * \brief Set a new value if the invoked element exists
567 * Seems to be useless !!!
568 * @param Value new element value
569 * @param Group group of the Entry
570 * @param Elem element of the Entry
573 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
575 std::string v = Value;
576 SetEntryByNumber(v, Group, Elem);
580 //-----------------------------------------------------------------------------
584 * \brief Checks if a given Dicom Element exists
586 * @param group Group number of the searched Dicom Element
587 * @param element Element number of the searched Dicom Element
588 * @return number of occurences
590 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
591 std::string key = gdcmDictEntry::TranslateToKey(group, element );
592 return (tagHT.count(key));
596 * \ingroup gdcmParser
597 * \brief Searches within Header Entries (Dicom Elements) parsed with
598 * the public and private dictionaries
599 * for the element value of a given tag.
600 * \warning Don't use any longer : use GetPubEntryByName
601 * @param tagName name of the searched element.
602 * @return Corresponding element value when it exists,
603 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
605 std::string gdcmParser::GetEntryByName(std::string tagName) {
606 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
607 if( dictEntry == NULL)
610 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
614 * \ingroup gdcmParser
615 * \brief Searches within Header Entries (Dicom Elements) parsed with
616 * the public and private dictionaries
617 * for the element value representation of a given tag.
619 * Obtaining the VR (Value Representation) might be needed by caller
620 * to convert the string typed content to caller's native type
621 * (think of C++ vs Python). The VR is actually of a higher level
622 * of semantics than just the native C++ type.
623 * @param tagName name of the searched element.
624 * @return Corresponding element value representation when it exists,
625 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
627 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
628 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
629 if( dictEntry == NULL)
632 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
633 dictEntry->GetElement());
634 return elem->GetVR();
639 * \ingroup gdcmParser
640 * \brief Searches within Header Entries (Dicom Elements) parsed with
641 * the public and private dictionaries
642 * for the element value representation of a given tag.
643 * @param group Group of the searched tag.
644 * @param element Element of the searched tag.
645 * @return Corresponding element value representation when it exists,
646 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
648 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
649 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
650 if ( ! tagHT.count(key))
652 return tagHT.find(key)->second->GetValue();
656 * \ingroup gdcmParser
657 * \brief Searches within Header Entries (Dicom Elements) parsed with
658 * the public and private dictionaries
659 * for the element value representation of a given tag..
661 * Obtaining the VR (Value Representation) might be needed by caller
662 * to convert the string typed content to caller's native type
663 * (think of C++ vs Python). The VR is actually of a higher level
664 * of semantics than just the native C++ type.
665 * @param group Group of the searched tag.
666 * @param element Element of the searched tag.
667 * @return Corresponding element value representation when it exists,
668 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
670 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
671 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
674 return elem->GetVR();
678 * \ingroup gdcmParser
679 * \brief Searches within Header Entries (Dicom Elements) parsed with
680 * the public and private dictionaries
681 * for the value length of a given tag..
682 * @param group Group of the searched tag.
683 * @param element Element of the searched tag.
684 * @return Corresponding element length; -2 if not found
686 int gdcmParser::GetEntryLengthByNumber(guint16 group, guint16 element) {
687 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
690 return elem->GetLength();
693 * \ingroup gdcmParser
694 * \brief Sets the value (string) of the Header Entry (Dicom Element)
695 * @param content string value of the Dicom Element
696 * @param tagName name of the searched Dicom Element.
697 * @return true when found
699 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
700 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
701 if( dictEntry == NULL)
704 return(SetEntryByNumber(content,dictEntry->GetGroup(),
705 dictEntry->GetElement()));
709 * \ingroup gdcmParser
710 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
711 * through it's (group, element) and modifies it's content with
713 * \warning Don't use any longer : use SetPubEntryByNumber
714 * @param content new value to substitute with
715 * @param group group of the Dicom Element to modify
716 * @param element element of the Dicom Element to modify
718 bool gdcmParser::SetEntryByNumber(std::string content,
722 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
723 if ( ! tagHT.count(key))
725 int l = content.length();
726 if(l%2) // Non even length are padded with a space (020H).
729 content = content + '\0';
734 TagHeaderEntryHT::iterator p2;
735 // DO NOT remove the following lines : they explain the stuff
736 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
737 //p2=p.first; // iterator on the first synonym
738 //a=p2->second; // H Table target column (2-nd col)
741 a = ((tagHT.equal_range(key)).first)->second;
743 a-> SetValue(content);
745 std::string vr = a->GetVR();
748 if( (vr == "US") || (vr == "SS") )
750 else if( (vr == "UL") || (vr == "SL") )
760 * \ingroup gdcmParser
761 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
762 * in the PubHeaderEntrySet of this instance
763 * through it's (group, element) and modifies it's length with
765 * \warning Use with extreme caution.
766 * @param l new length to substitute with
767 * @param group group of the Entry to modify
768 * @param element element of the Entry to modify
769 * @return true on success, false otherwise.
771 bool gdcmParser::SetEntryLengthByNumber(guint32 l,
775 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
776 if ( ! tagHT.count(key))
778 if (l%2) l++; // length must be even
779 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
785 * \ingroup gdcmParser
786 * \brief Gets (from Header) the offset of a 'non string' element value
787 * (LoadElementValues has already be executed)
788 * @param Group group of the Entry
789 * @param Elem element of the Entry
790 * @return File Offset of the Element Value
792 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
794 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
797 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
798 "failed to Locate gdcmHeaderEntry");
801 return Entry->GetOffset();
805 * \ingroup gdcmParser
806 * \brief Gets (from Header) a 'non string' element value
807 * (LoadElementValues has already be executed)
808 * @param Group group of the Entry
809 * @param Elem element of the Entry
810 * @return Pointer to the 'non string' area
812 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
814 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
817 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
818 "failed to Locate gdcmHeaderEntry");
821 return Entry->GetVoidArea();
825 * \brief Loads (from disk) the element content
826 * when a string is not suitable
827 * @param Group group of the Entry
828 * @param Elem element of the Entry
830 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
832 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
835 size_t o =(size_t)Element->GetOffset();
836 fseek(fp, o, SEEK_SET);
837 size_t l=Element->GetLength();
838 char* a = new char[l];
842 SetEntryVoidAreaByNumber(a, Group, Elem);
843 // TODO check the result
844 size_t l2 = fread(a, 1, l ,fp);
855 * \ingroup gdcmParser
856 * \brief Sets a 'non string' value to a given Dicom Element
858 * @param group Group number of the searched Dicom Element
859 * @param element Element number of the searched Dicom Element
862 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
866 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
867 if ( ! tagHT.count(key))
869 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
874 * \ingroup gdcmParser
875 * \brief Update the entries with the shadow dictionary.
876 * Only non even entries are analyzed
878 void gdcmParser::UpdateShaEntries(void) {
879 gdcmDictEntry *entry;
882 for(ListTag::iterator it=listEntries.begin();
883 it!=listEntries.end();
886 // Odd group => from public dictionary
887 if((*it)->GetGroup()%2==0)
890 // Peer group => search the corresponding dict entry
892 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
896 if((*it)->IsImplicitVR())
901 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
903 // Set the new entry and the new value
904 (*it)->SetDictEntry(entry);
905 CheckHeaderEntryVR(*it,vr);
907 (*it)->SetValue(GetHeaderEntryValue(*it));
911 // Remove precedent value transformation
912 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
918 * \ingroup gdcmParser
919 * \brief Searches within the Header Entries for a Dicom Element of
921 * @param tagName name of the searched Dicom Element.
922 * @return Corresponding Dicom Element when it exists, and NULL
925 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
926 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
927 if( dictEntry == NULL)
930 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
934 * \ingroup gdcmParser
935 * \brief retrieves a Dicom Element (the first one) using (group, element)
936 * \warning (group, element) IS NOT an identifier inside the Dicom Header
937 * if you think it's NOT UNIQUE, check the count number
938 * and use iterators to retrieve ALL the Dicoms Elements within
939 * a given couple (group, element)
940 * @param group Group number of the searched Dicom Element
941 * @param element Element number of the searched Dicom Element
944 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
946 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
947 if ( ! tagHT.count(key))
949 return tagHT.find(key)->second;
953 * \ingroup gdcmParser
954 * \brief retrieves the Dicom Elements (all of them) using (group, element)
955 * @param group Group number of the searched Dicom Element.
956 * @param element Element number of the searched Dicom Element.
957 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
960 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
961 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
962 return (tagHT.equal_range(key));
966 * \ingroup gdcmParser
967 * \brief Loads the element while preserving the current
968 * underlying file position indicator as opposed to
969 * to LoadHeaderEntry that modifies it.
970 * @param entry Header Entry whose value shall be loaded.
973 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
974 long PositionOnEntry = ftell(fp);
975 LoadHeaderEntry(entry);
976 fseek(fp, PositionOnEntry, SEEK_SET);
980 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
981 * \warning : to be re-written using the chained list instead of the H table.
982 * \warning : DO NOT use (doesn't work any longer because of the multimap)
983 * \todo : to be re-written using the chained list instead of the H table
984 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
985 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
987 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
991 gdcmHeaderEntry *elem;
993 std::string str_trash;
996 GroupHT groupHt; // to hold the length of each group
999 // typedef std::map<GroupKey, int> GroupHT;
1001 gdcmHeaderEntry *elemZ;
1003 // for each Tag in the DCM Header
1005 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
1006 tag2 != tagHT.end();
1009 elem = tag2->second;
1010 gr = elem->GetGroup();
1011 el = elem->GetElement();
1014 sprintf(trash, "%04x", gr);
1015 key = trash; // generate 'group tag'
1017 // if the caller decided not to take SEQUENCEs into account
1018 // e.g : he wants to write an ACR-NEMA File
1020 if (SkipSequence && vr == "SQ")
1023 // Still unsolved problem :
1024 // we cannot find the 'Sequence Delimitation Item'
1025 // since it's at the end of the Hash Table
1028 // there is SEQUENCE in ACR-NEMA
1030 // --> la descente a l'interieur' des SQ
1031 // devrait etre faite avec une liste chainee, pas avec une HTable...
1033 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
1035 if (el == 0x0000) // the first elem is 0x0000
1037 groupHt[key] = 0; // initialize group length
1041 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
1044 else // any elem but the first
1046 if (type == ExplicitVR)
1048 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1050 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
1053 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
1057 unsigned short int gr_bid;
1059 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
1063 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
1064 // warning: unsigned int format, different type arg
1065 sscanf(g->first.c_str(),"%x",&gr_bid); //FIXME
1066 tk = g->first + "|0000"; // generate the element full tag
1068 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
1070 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
1071 elemZ = new gdcmHeaderEntry(tagZ);
1072 elemZ->SetLength(4);
1073 AddHeaderEntry(elemZ); // create it
1077 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
1079 sprintf(trash ,"%d",g->second);
1081 elemZ->SetValue(str_trash);
1086 * \brief Writes in a file (according to the requested format)
1087 * the group, the element, the value representation and the length
1088 * of a single gdcmHeaderEntry passed as argument.
1089 * @param tag pointer on the gdcmHeaderEntry to be written
1090 * @param _fp already open file pointer
1091 * @param type type of the File to be written
1093 void gdcmParser::WriteEntryTagVRLength(gdcmHeaderEntry *tag,
1097 guint16 group = tag->GetGroup();
1098 std::string vr = tag->GetVR();
1099 guint16 el = tag->GetElement();
1100 guint32 lgr = tag->GetReadLength();
1102 if ( (group == 0xfffe) && (el == 0x0000) )
1103 // Fix in order to make some MR PHILIPS images e-film readable
1104 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1105 // we just *always* ignore spurious fffe|0000 tag !
1108 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1109 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1111 if ( type == ExplicitVR ) {
1113 // Special case of delimiters:
1114 if (group == 0xfffe) {
1115 // Delimiters have NO Value Representation and have NO length.
1116 // Hence we skip writing the VR and length and we pad by writing
1120 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1125 guint16 shortLgr = lgr;
1126 if (vr == "unkn") { // Unknown was 'written'
1127 // deal with Little Endian
1128 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1129 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1131 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1132 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1134 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1135 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1137 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1143 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1148 * \brief Writes in a file (according to the requested format)
1149 * the value of a single gdcmHeaderEntry passed as argument.
1150 * @param tag Pointer on the gdcmHeaderEntry to be written
1151 * @param _fp Already open file pointer
1152 * @param type type of the File to be written
1154 void gdcmParser::WriteEntryValue(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1157 guint16 group = tag->GetGroup();
1158 std::string vr = tag->GetVR();
1159 guint32 lgr = tag->GetReadLength();
1162 // SeQuences have no value:
1164 if (group == 0xfffe)
1165 // Delimiters have no associated value:
1169 voidArea = tag->GetVoidArea();
1170 if (voidArea != NULL)
1171 { // there is a 'non string' LUT, overlay, etc
1172 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1176 if (vr == "US" || vr == "SS")
1178 // some 'Short integer' fields may be mulivaluated
1179 // each single value is separated from the next one by '\'
1180 // we split the string and write each value as a short int
1181 std::vector<std::string> tokens;
1182 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1183 Tokenize (tag->GetValue(), tokens, "\\");
1184 for (unsigned int i=0; i<tokens.size();i++)
1186 guint16 val_uint16 = atoi(tokens[i].c_str());
1187 void *ptr = &val_uint16;
1188 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1193 // some 'Integer' fields may be mulivaluated
1194 // each single value is separated from the next one by '\'
1195 // we split the string and write each value as an int
1196 if (vr == "UL" || vr == "SL")
1198 std::vector<std::string> tokens;
1199 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1200 Tokenize (tag->GetValue(), tokens, "\\");
1201 for (unsigned int i=0; i<tokens.size();i++)
1203 guint32 val_uint32 = atoi(tokens[i].c_str());
1204 void *ptr = &val_uint32;
1205 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1210 fwrite (tag->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1214 * \brief Writes in a file (according to the requested format)
1215 * a single gdcmHeaderEntry passed as argument.
1216 * \sa WriteEntryValue, WriteEntryTagVRLength.
1217 * @param tag Pointer on the gdcmHeaderEntry to be written
1218 * @param _fp Already open file pointer
1219 * @param type type of the File to be written
1222 bool gdcmParser::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1224 guint32 length = tag->GetLength();
1226 // The value of a tag MUST (see the DICOM norm) be an odd number of
1227 // bytes. When this is not the case, pad with an additional byte:
1230 tag->SetValue(tag->GetValue()+"\0");
1231 tag->SetLength(tag->GetReadLength()+1);
1234 WriteEntryTagVRLength(tag, _fp, type);
1235 WriteEntryValue(tag, _fp, type);
1240 * \brief writes on disc according to the requested format
1241 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1242 * using the Chained List
1243 * \warning does NOT add the missing elements in the header :
1244 * it's up to the user doing it !
1245 * (function CheckHeaderCoherence to be written)
1246 * \warning DON'T try, right now, to write a DICOM image
1247 * from an ACR Header (meta elements will be missing!)
1248 * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1249 * @param type type of the File to be written
1250 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1251 * @param _fp already open file pointer
1254 bool gdcmParser::WriteEntries(FILE *_fp,FileType type)
1256 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1258 for (ListTag::iterator tag2=listEntries.begin();
1259 tag2 != listEntries.end();
1263 if ((*tag2)->GetGroup() < 0x0008)
1264 // Ignore pure DICOM V3 groups
1266 if ((*tag2)->GetElement() %2)
1267 // Ignore the "shadow" groups
1269 if ((*tag2)->GetVR() == "SQ" )
1270 // For the time being sequences are simply ignored
1271 // TODO : find a trick not to *skip* the SeQuences !
1273 if ((*tag2)->GetGroup() == 0xfffe )
1274 // Ignore the documented delimiter
1277 if (! WriteEntry(*tag2,_fp,type) )
1284 * \ingroup gdcmParser
1285 * \brief writes on disc according to the requested format
1286 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1287 * using only the last synonym of each mutimap H Table post.
1288 * \warning Uses the H Table, instead of the Chained List
1289 * in order to be compliant with the old way to proceed
1290 * (added elements taken in to account)
1291 * Only THERALYS, during a transitory phase is supposed
1292 * to use this method !!!
1293 * \warning DON'T try, right now, to write a DICOM image
1294 * from an ACR Header (meta elements will be missing!)
1296 * @param _fp already open file pointer
1297 * @param type type of the File to be written
1298 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1300 void gdcmParser::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1302 // restent a tester les echecs en ecriture (apres chaque fwrite)
1304 for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1305 tag2 != tagHT.end();
1308 if ((*tag2->second).GetGroup() < 0x0008) continue; // ignore pure DICOM V3 groups
1309 if ((*tag2->second).GetElement() %2) continue; // ignore shadow groups
1310 if ((*tag2->second).GetVR() == "SQ" ) continue; // ignore Sequences
1311 // TODO : find a trick to *skip* the SeQuences !
1312 // Not only ignore the SQ element
1313 // --> will be done with the next organization
1314 if ((*tag2->second).GetGroup() == 0xfffe ) continue; // ignore delimiters
1316 if ( ! WriteEntry(tag2->second,_fp,type))
1322 * \ingroup gdcmParser
1323 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1325 * @return The properly swaped 32 bits integer.
1327 guint32 gdcmParser::SwapLong(guint32 a) {
1332 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1333 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1337 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1341 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1344 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1351 * \ingroup gdcmParser
1352 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1354 * @return The properly unswaped 32 bits integer.
1356 guint32 gdcmParser::UnswapLong(guint32 a) {
1357 return (SwapLong(a));
1361 * \ingroup gdcmParser
1362 * \brief Swaps the bytes so they agree with the processor order
1363 * @return The properly swaped 16 bits integer.
1365 guint16 gdcmParser::SwapShort(guint16 a) {
1366 if ( (sw==4321) || (sw==2143) )
1367 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1372 * \ingroup gdcmParser
1373 * \brief Unswaps the bytes so they agree with the processor order
1374 * @return The properly unswaped 16 bits integer.
1376 guint16 gdcmParser::UnswapShort(guint16 a) {
1377 return (SwapShort(a));
1380 //-----------------------------------------------------------------------------
1383 * \ingroup gdcmParser
1384 * \brief Parses the header of the file but WITHOUT loading element values.
1385 * @return false if file is not ACR-NEMA / DICOM
1387 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1388 (void)exception_on_error;
1393 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1394 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1395 SkipHeaderEntry(newHeaderEntry);
1396 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1397 AddHeaderEntry(newHeaderEntry);
1404 * \ingroup gdcmParser
1405 * \brief Loads the element values of all the Header Entries pointed in the
1406 * public Chained List.
1408 void gdcmParser::LoadHeaderEntries(void) {
1410 for (ListTag::iterator i = GetListEntry().begin();
1411 i != GetListEntry().end();
1414 LoadHeaderEntry(*i);
1419 // Load 'non string' values
1420 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1421 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1422 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1423 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1424 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1425 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1427 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1428 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1429 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1431 //FIXME : how to use it?
1432 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1434 // --------------------------------------------------------------
1435 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1437 // if recognition code tells us we deal with a LibIDO image
1438 // we switch lineNumber and columnNumber
1440 std::string RecCode;
1441 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1442 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1443 RecCode == "CANRME_AILIBOD1_1." )
1445 filetype = ACR_LIBIDO;
1446 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1447 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1448 SetEntryByNumber(columns, 0x0028, 0x0010);
1449 SetEntryByNumber(rows , 0x0028, 0x0011);
1451 // ----------------- End of Special Patch ----------------
1455 * \ingroup gdcmParser
1456 * \brief Loads the element content if its length doesn't exceed
1457 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1458 * @param Entry Header Entry (Dicom Element) to be dealt with
1460 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1462 guint16 group = Entry->GetGroup();
1463 std::string vr= Entry->GetVR();
1464 guint32 length = Entry->GetLength();
1466 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1468 // A SeQuence "contains" a set of Elements.
1469 // (fffe e000) tells us an Element is beginning
1470 // (fffe e00d) tells us an Element just ended
1471 // (fffe e0dd) tells us the current SeQuence just ended
1472 if( group == 0xfffe ) {
1473 Entry->SetValue("gdcm::Skipped");
1477 // When the length is zero things are easy:
1478 if ( length == 0 ) {
1479 Entry->SetValue("");
1483 // The elements whose length is bigger than the specified upper bound
1484 // are not loaded. Instead we leave a short notice of the offset of
1485 // the element content and it's length.
1486 if (length > MaxSizeLoadEntry) {
1487 std::ostringstream s;
1488 s << "gdcm::NotLoaded.";
1489 s << " Address:" << (long)Entry->GetOffset();
1490 s << " Length:" << Entry->GetLength();
1491 s << " x(" << std::hex << Entry->GetLength() << ")";
1492 Entry->SetValue(s.str());
1496 // Any compacter code suggested (?)
1497 if ( IsHeaderEntryAnInteger(Entry) ) {
1499 std::ostringstream s;
1501 // When short integer(s) are expected, read and convert the following
1502 // n *two characters properly i.e. as short integers as opposed to strings.
1503 // Elements with Value Multiplicity > 1
1504 // contain a set of integers (not a single one)
1505 if (vr == "US" || vr == "SS") {
1507 NewInt = ReadInt16();
1510 for (int i=1; i < nbInt; i++) {
1512 NewInt = ReadInt16();
1517 // When integer(s) are expected, read and convert the following
1518 // n * four characters properly i.e. as integers as opposed to strings.
1519 // Elements with Value Multiplicity > 1
1520 // contain a set of integers (not a single one)
1521 else if (vr == "UL" || vr == "SL") {
1523 NewInt = ReadInt32();
1526 for (int i=1; i < nbInt; i++) {
1528 NewInt = ReadInt32();
1533 #ifdef GDCM_NO_ANSI_STRING_STREAM
1534 s << std::ends; // to avoid oddities on Solaris
1535 #endif //GDCM_NO_ANSI_STRING_STREAM
1537 Entry->SetValue(s.str());
1541 // We need an additional byte for storing \0 that is not on disk
1542 std::string NewValue(length,0);
1543 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1544 if ( item_read != 1 ) {
1545 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1546 Entry->SetValue("gdcm::UnRead");
1550 if( (vr == "UI") ) // Because of correspondance with the VR dic
1551 Entry->SetValue(NewValue.c_str());
1553 Entry->SetValue(NewValue);
1557 * \ingroup gdcmParser
1558 * \brief add a new Dicom Element pointer to
1559 * the H Table and at the end of the chained List
1560 * \warning push_bash in listEntries ONLY during ParseHeader
1561 * \todo something to allow further Elements addition,
1562 * (at their right place in the chained list)
1563 * when position to be taken care of
1564 * @param newHeaderEntry
1566 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1567 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1568 listEntries.push_back(newHeaderEntry);
1573 * \ingroup gdcmParser
1574 * \brief Find the value Length of the passed Header Entry
1575 * @param Entry Header Entry whose length of the value shall be loaded.
1577 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1578 guint16 element = Entry->GetElement();
1579 //guint16 group = Entry->GetGroup(); //FIXME
1580 std::string vr = Entry->GetVR();
1584 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1586 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1588 // The following reserved two bytes (see PS 3.5-2001, section
1589 // 7.1.2 Data element structure with explicit vr p27) must be
1590 // skipped before proceeding on reading the length on 4 bytes.
1591 fseek(fp, 2L, SEEK_CUR);
1592 guint32 length32 = ReadInt32();
1594 if ( (vr == "OB") && (length32 == 0xffffffff) )
1596 Entry->SetLength(FindHeaderEntryLengthOB());
1599 FixHeaderEntryFoundLength(Entry, length32);
1603 // Length is encoded on 2 bytes.
1604 length16 = ReadInt16();
1606 // We can tell the current file is encoded in big endian (like
1607 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1608 // and it's value is the one of the encoding of a big endian file.
1609 // In order to deal with such big endian encoded files, we have
1610 // (at least) two strategies:
1611 // * when we load the "Transfer Syntax" tag with value of big endian
1612 // encoding, we raise the proper flags. Then we wait for the end
1613 // of the META group (0x0002) among which is "Transfer Syntax",
1614 // before switching the swap code to big endian. We have to postpone
1615 // the switching of the swap code since the META group is fully encoded
1616 // in little endian, and big endian coding only starts at the next
1617 // group. The corresponding code can be hard to analyse and adds
1618 // many additional unnecessary tests for regular tags.
1619 // * the second strategy consists in waiting for trouble, that shall
1620 // appear when we find the first group with big endian encoding. This
1621 // is easy to detect since the length of a "Group Length" tag (the
1622 // ones with zero as element number) has to be of 4 (0x0004). When we
1623 // encounter 1024 (0x0400) chances are the encoding changed and we
1624 // found a group with big endian encoding.
1625 // We shall use this second strategy. In order to make sure that we
1626 // can interpret the presence of an apparently big endian encoded
1627 // length of a "Group Length" without committing a big mistake, we
1628 // add an additional check: we look in the already parsed elements
1629 // for the presence of a "Transfer Syntax" whose value has to be "big
1630 // endian encoding". When this is the case, chances are we have got our
1631 // hands on a big endian encoded file: we switch the swap code to
1632 // big endian and proceed...
1633 if ( (element == 0x0000) && (length16 == 0x0400) )
1635 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1637 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1642 SwitchSwapToBigEndian();
1643 // Restore the unproperly loaded values i.e. the group, the element
1644 // and the dictionary entry depending on them.
1645 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1646 guint16 CorrectElem = SwapShort(Entry->GetElement());
1647 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1651 // This correct tag is not in the dictionary. Create a new one.
1652 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1654 // FIXME this can create a memory leaks on the old entry that be
1655 // left unreferenced.
1656 Entry->SetDictEntry(NewTag);
1659 // Heuristic: well some files are really ill-formed.
1660 if ( length16 == 0xffff)
1663 //dbg.Verbose(0, "gdcmParser::FindLength",
1664 // "Erroneous element length fixed.");
1665 // Actually, length= 0xffff means that we deal with
1666 // Unknown Sequence Length
1668 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1673 // Either implicit VR or a non DICOM conformal (see note below) explicit
1674 // VR that ommited the VR of (at least) this element. Farts happen.
1675 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1676 // on Data elements "Implicit and Explicit VR Data Elements shall
1677 // not coexist in a Data Set and Data Sets nested within it".]
1678 // Length is on 4 bytes.
1680 FixHeaderEntryFoundLength(Entry, ReadInt32());
1686 * \ingroup gdcmParser
1687 * \brief Find the Value Representation of the current Dicom Element.
1690 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1692 if (filetype != ExplicitVR)
1697 long PositionOnEntry = ftell(fp);
1698 // Warning: we believe this is explicit VR (Value Representation) because
1699 // we used a heuristic that found "UL" in the first tag. Alas this
1700 // doesn't guarantee that all the tags will be in explicit VR. In some
1701 // cases (see e-film filtered files) one finds implicit VR tags mixed
1702 // within an explicit VR file. Hence we make sure the present tag
1703 // is in explicit VR and try to fix things if it happens not to be
1706 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1708 if(!CheckHeaderEntryVR(Entry,VR))
1710 fseek(fp, PositionOnEntry, SEEK_SET);
1711 // When this element is known in the dictionary we shall use, e.g. for
1712 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1713 // dictionary entry. Still we have to flag the element as implicit since
1714 // we know now our assumption on expliciteness is not furfilled.
1716 if ( Entry->IsVRUnknown() )
1717 Entry->SetVR("Implicit");
1718 Entry->SetImplicitVR();
1723 * \ingroup gdcmParser
1724 * \brief Check the correspondance between the VR of the header entry
1725 * and the taken VR. If they are different, the header entry is
1726 * updated with the new VR.
1727 * @param Entry Header Entry to check
1728 * @param vr Dicom Value Representation
1729 * @return false if the VR is incorrect of if the VR isn't referenced
1730 * otherwise, it returns true
1732 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1734 char msg[100]; // for sprintf
1735 bool RealExplicit = true;
1737 // Assume we are reading a falsely explicit VR file i.e. we reached
1738 // a tag where we expect reading a VR but are in fact we read the
1739 // first to bytes of the length. Then we will interogate (through find)
1740 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1741 // both GCC and VC++ implementations of the STL map. Hence when the
1742 // expected VR read happens to be non-ascii characters we consider
1743 // we hit falsely explicit VR tag.
1745 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1746 RealExplicit = false;
1748 // CLEANME searching the dicom_vr at each occurence is expensive.
1749 // PostPone this test in an optional integrity check at the end
1750 // of parsing or only in debug mode.
1751 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1752 RealExplicit= false;
1754 if ( !RealExplicit )
1756 // We thought this was explicit VR, but we end up with an
1757 // implicit VR tag. Let's backtrack.
1758 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1759 Entry->GetGroup(),Entry->GetElement());
1760 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1761 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1762 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1763 Entry->GetGroup(),Entry->GetElement(),
1764 "UL","FIXME","Group Length");
1765 Entry->SetDictEntry(NewEntry);
1770 if ( Entry->IsVRUnknown() )
1772 // When not a dictionary entry, we can safely overwrite the VR.
1773 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1779 else if ( Entry->GetVR() != vr )
1781 // The VR present in the file and the dictionary disagree. We assume
1782 // the file writer knew best and use the VR of the file. Since it would
1783 // be unwise to overwrite the VR of a dictionary (since it would
1784 // compromise it's next user), we need to clone the actual DictEntry
1785 // and change the VR for the read one.
1786 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1787 Entry->GetGroup(),Entry->GetElement(),
1788 vr,"FIXME",Entry->GetName());
1789 Entry->SetDictEntry(NewEntry);
1795 * \ingroup gdcmParser
1796 * \brief Get the transformed value of the header entry. The VR value
1797 * is used to define the transformation to operate on the value
1798 * \warning NOT end user intended method !
1800 * @return Transformed entry value
1802 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1804 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1806 std::string val=Entry->GetValue();
1807 std::string vr=Entry->GetVR();
1808 guint32 length = Entry->GetLength();
1809 std::ostringstream s;
1812 // When short integer(s) are expected, read and convert the following
1813 // n * 2 bytes properly i.e. as a multivaluated strings
1814 // (each single value is separated fromthe next one by '\'
1815 // as usual for standard multivaluated filels
1816 // Elements with Value Multiplicity > 1
1817 // contain a set of short integers (not a single one)
1819 if (vr == "US" || vr == "SS")
1824 for (int i=0; i < nbInt; i++)
1828 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1829 NewInt16 = SwapShort(NewInt16);
1834 // When integer(s) are expected, read and convert the following
1835 // n * 4 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 integers (not a single one)
1840 else if (vr == "UL" || vr == "SL")
1845 for (int i=0; i < nbInt; i++)
1849 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1850 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1851 NewInt32=SwapLong(NewInt32);
1855 #ifdef GDCM_NO_ANSI_STRING_STREAM
1856 s << std::ends; // to avoid oddities on Solaris
1857 #endif //GDCM_NO_ANSI_STRING_STREAM
1861 return(Entry->GetValue());
1865 * \ingroup gdcmParser
1866 * \brief Get the reverse transformed value of the header entry. The VR
1867 * value is used to define the reverse transformation to operate on
1869 * \warning NOT end user intended method !
1871 * @return Reverse transformed entry value
1873 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1875 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1877 std::string vr=Entry->GetVR();
1878 std::ostringstream s;
1879 std::vector<std::string> tokens;
1881 if (vr == "US" || vr == "SS")
1885 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1886 Tokenize (Entry->GetValue(), tokens, "\\");
1887 for (unsigned int i=0; i<tokens.size();i++)
1889 NewInt16 = atoi(tokens[i].c_str());
1890 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1894 if (vr == "UL" || vr == "SL")
1898 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1899 Tokenize (Entry->GetValue(), tokens, "\\");
1900 for (unsigned int i=0; i<tokens.size();i++)
1902 NewInt32 = atoi(tokens[i].c_str());
1903 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1904 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1909 #ifdef GDCM_NO_ANSI_STRING_STREAM
1910 s << std::ends; // to avoid oddities on Solaris
1911 #endif //GDCM_NO_ANSI_STRING_STREAM
1915 return(Entry->GetValue());
1919 * \ingroup gdcmParser
1920 * \brief Skip a given Header Entry
1921 * \warning NOT end user intended method !
1924 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1926 SkipBytes(entry->GetLength());
1930 * \ingroup gdcmParser
1931 * \brief When the length of an element value is obviously wrong (because
1932 * the parser went Jabberwocky) one can hope improving things by
1933 * applying this heuristic.
1935 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1937 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1938 if ( FoundLength == 0xffffffff) {
1942 guint16 gr =Entry->GetGroup();
1943 guint16 el =Entry->GetElement();
1945 if (FoundLength%2) {
1946 std::ostringstream s;
1947 s << "Warning : Tag with uneven length " << FoundLength
1948 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1949 dbg.Verbose(0,s.str().c_str());
1952 // Sorry for the patch!
1953 // XMedCom did the trick to read some naughty GE images ...
1954 if (FoundLength == 13) {
1955 // The following 'if' will be removed when there is no more
1956 // images on Creatis HDs with a 13 length for Manufacturer...
1957 if ( (Entry->GetGroup() != 0x0008) ||
1958 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1959 // end of remove area
1961 Entry->SetReadLength(10); // a bug is to be fixed
1965 // to fix some garbage 'Leonardo' Siemens images
1966 // May be commented out to avoid overhead
1967 else if ( (Entry->GetGroup() == 0x0009) &&
1968 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1970 Entry->SetReadLength(4); // a bug is to be fixed
1974 // to try to 'go inside' SeQuences (with length), and not to skip them
1975 else if ( Entry->GetVR() == "SQ")
1977 if (enableSequences) // only if the user does want to !
1978 FoundLength =0; // ReadLength is unchanged
1981 // we found a 'delimiter' element
1982 // fffe|xxxx is just a marker, we don't take its length into account
1983 else if(Entry->GetGroup() == 0xfffe)
1985 // *normally, fffe|0000 doesn't exist !
1986 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1987 // causes extra troubles :-(
1991 Entry->SetUsableLength(FoundLength);
1995 * \ingroup gdcmParser
1996 * \brief Apply some heuristics to predict whether the considered
1997 * element value contains/represents an integer or not.
1998 * @param Entry The element value on which to apply the predicate.
1999 * @return The result of the heuristical predicate.
2001 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
2002 guint16 element = Entry->GetElement();
2003 guint16 group = Entry->GetGroup();
2004 std::string vr = Entry->GetVR();
2005 guint32 length = Entry->GetLength();
2006 // When we have some semantics on the element we just read, and if we
2007 // a priori know we are dealing with an integer, then we shall be
2008 // able to swap it's element value properly.
2009 if ( element == 0 ) // This is the group length of the group
2015 std::ostringstream s;
2016 int filePosition = ftell(fp);
2017 s << "Erroneous Group Length element length on : (" \
2018 << std::hex << group << " , " << element
2019 << ") -before- position x(" << filePosition << ")"
2020 << "lgt : " << length;
2021 // These 2 lines commented out : a *very dirty* patch
2022 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
2023 // have a glance at offset x(8336) ...
2024 // For *regular* headers, the test is useless..
2025 // lets's print a warning message and go on,
2026 // instead of giving up with an error message
2028 //std::cout << s.str().c_str() << std::endl;
2029 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
2030 // s.str().c_str());
2033 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2039 * \ingroup gdcmParser
2040 * \brief Find the Length till the next sequence delimiter
2041 * \warning NOT end user intended method !
2045 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
2046 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2049 long PositionOnEntry = ftell(fp);
2050 bool FoundSequenceDelimiter = false;
2051 guint32 TotalLength = 0;
2054 while ( ! FoundSequenceDelimiter)
2060 TotalLength += 4; // We even have to decount the group and element
2062 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2064 char msg[100]; // for sprintf. Sorry
2065 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2066 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
2070 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2071 FoundSequenceDelimiter = true;
2072 else if ( n != 0xe000 )
2074 char msg[100]; // for sprintf. Sorry
2075 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2077 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
2081 ItemLength = ReadInt32();
2082 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2083 // the ItemLength with ReadInt32
2084 SkipBytes(ItemLength);
2086 fseek(fp, PositionOnEntry, SEEK_SET);
2091 * \ingroup gdcmParser
2092 * \brief Reads a supposed to be 16 Bits integer
2093 * (swaps it depending on processor endianity)
2094 * @return read value
2096 guint16 gdcmParser::ReadInt16(void) {
2099 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2100 if ( item_read != 1 ) {
2102 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
2112 * \ingroup gdcmParser
2113 * \brief Reads a supposed to be 32 Bits integer
2114 * (swaps it depending on processor endianity)
2115 * @return read value
2117 guint32 gdcmParser::ReadInt32(void) {
2120 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2121 if ( item_read != 1 ) {
2123 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
2133 * \ingroup gdcmParser
2134 * \brief skips bytes inside the source file
2135 * \warning NOT end user intended method !
2138 void gdcmParser::SkipBytes(guint32 NBytes) {
2139 //FIXME don't dump the returned value
2140 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2144 * \ingroup gdcmParser
2145 * \brief Loads all the needed Dictionaries
2146 * \warning NOT end user intended method !
2148 void gdcmParser::Initialise(void)
2150 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2151 RefShaDict = (gdcmDict*)0;
2155 * \ingroup gdcmParser
2156 * \brief Discover what the swap code is (among little endian, big endian,
2157 * bad little endian, bad big endian).
2159 * @return false when we are absolutely sure
2160 * it's neither ACR-NEMA nor DICOM
2161 * true when we hope ours assuptions are OK
2163 bool gdcmParser::CheckSwap() {
2165 // The only guaranted way of finding the swap code is to find a
2166 // group tag since we know it's length has to be of four bytes i.e.
2167 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2168 // occurs when we can't find such group...
2170 guint32 x=4; // x : for ntohs
2171 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2177 char deb[HEADER_LENGTH_TO_READ];
2179 // First, compare HostByteOrder and NetworkByteOrder in order to
2180 // determine if we shall need to swap bytes (i.e. the Endian type).
2186 // The easiest case is the one of a DICOM header, since it possesses a
2187 // file preamble where it suffice to look for the string "DICM".
2188 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2191 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2192 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2194 // Next, determine the value representation (VR). Let's skip to the
2195 // first element (0002, 0000) and check there if we find "UL"
2196 // - or "OB" if the 1st one is (0002,0001) -,
2197 // in which case we (almost) know it is explicit VR.
2198 // WARNING: if it happens to be implicit VR then what we will read
2199 // is the length of the group. If this ascii representation of this
2200 // length happens to be "UL" then we shall believe it is explicit VR.
2201 // FIXME: in order to fix the above warning, we could read the next
2202 // element value (or a couple of elements values) in order to make
2203 // sure we are not commiting a big mistake.
2204 // We need to skip :
2205 // * the 128 bytes of File Preamble (often padded with zeroes),
2206 // * the 4 bytes of "DICM" string,
2207 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2208 // i.e. a total of 136 bytes.
2212 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2213 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2214 // *Implicit* VR. -and it is !-
2216 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2217 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2218 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2219 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2220 // when Write DCM *adds*
2222 // Use gdcmParser::dicom_vr to test all the possibilities
2223 // instead of just checking for UL, OB and UI !? group 0000
2225 filetype = ExplicitVR;
2226 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2227 "explicit Value Representation");
2231 filetype = ImplicitVR;
2232 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2233 "not an explicit Value Representation");
2239 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2240 "HostByteOrder != NetworkByteOrder");
2245 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2246 "HostByteOrder = NetworkByteOrder");
2249 // Position the file position indicator at first tag (i.e.
2250 // after the file preamble and the "DICM" string).
2252 fseek (fp, 132L, SEEK_SET);
2256 // Alas, this is not a DicomV3 file and whatever happens there is no file
2257 // preamble. We can reset the file position indicator to where the data
2258 // is (i.e. the beginning of the file).
2259 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2262 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2263 // By clean we mean that the length of the first tag is written down.
2264 // If this is the case and since the length of the first group HAS to be
2265 // four (bytes), then determining the proper swap code is straightforward.
2268 // We assume the array of char we are considering contains the binary
2269 // representation of a 32 bits integer. Hence the following dirty
2271 s32 = *((guint32 *)(entCur));
2292 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2293 // It is time for despaired wild guesses.
2294 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2295 // i.e. the 'group length' element is not present :
2297 // check the supposed to be 'group number'
2298 // 0x0002 or 0x0004 or 0x0008
2299 // to determine ' sw' value .
2300 // Only 0 or 4321 will be possible
2301 // (no oportunity to check for the formerly well known
2302 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2303 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2304 // the file IS NOT ACR-NEMA nor DICOM V3
2305 // Find a trick to tell it the caller...
2307 s16 = *((guint16 *)(deb));
2323 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2324 "ACR/NEMA unfound swap info (Really hopeless !)");
2329 // Then the only info we have is the net2host one.
2339 * \ingroup gdcmParser
2340 * \brief Restore the unproperly loaded values i.e. the group, the element
2341 * and the dictionary entry depending on them.
2343 void gdcmParser::SwitchSwapToBigEndian(void)
2345 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2346 "Switching to BigEndian mode.");
2367 * \ingroup gdcmParser
2368 * \brief during parsing, Header Elements too long are not loaded in memory
2371 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2375 if ((guint32)NewSize >= (guint32)0xffffffff)
2377 MaxSizeLoadEntry = 0xffffffff;
2380 MaxSizeLoadEntry = NewSize;
2385 * \ingroup gdcmParser
2386 * \brief Header Elements too long will not be printed
2388 * \todo : not yet usable
2389 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2390 * in gdcmHeaderEntry gdcmLoadEntry)
2394 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2398 if ((guint32)NewSize >= (guint32)0xffffffff)
2400 MaxSizePrintEntry = 0xffffffff;
2403 MaxSizePrintEntry = NewSize;
2407 * \ingroup gdcmParser
2408 * \brief Searches both the public and the shadow dictionary (when they
2409 * exist) for the presence of the DictEntry with given name.
2410 * The public dictionary has precedence on the shadow one.
2411 * @param Name name of the searched DictEntry
2412 * @return Corresponding DictEntry when it exists, NULL otherwise.
2414 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2416 gdcmDictEntry *found = (gdcmDictEntry *)0;
2417 if (!RefPubDict && !RefShaDict)
2419 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2420 "we SHOULD have a default dictionary");
2424 found = RefPubDict->GetDictEntryByName(Name);
2430 found = RefShaDict->GetDictEntryByName(Name);
2438 * \ingroup gdcmParser
2439 * \brief Searches both the public and the shadow dictionary (when they
2440 * exist) for the presence of the DictEntry with given
2441 * group and element. The public dictionary has precedence on the
2443 * @param group group of the searched DictEntry
2444 * @param element element of the searched DictEntry
2445 * @return Corresponding DictEntry when it exists, NULL otherwise.
2447 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2449 gdcmDictEntry *found = (gdcmDictEntry *)0;
2450 if (!RefPubDict && !RefShaDict)
2452 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2453 "we SHOULD have a default dictionary");
2457 found = RefPubDict->GetDictEntryByNumber(group, element);
2463 found = RefShaDict->GetDictEntryByNumber(group, element);
2471 * \ingroup gdcmParser
2472 * \brief Read the next tag but WITHOUT loading it's value
2473 * @return On succes the newly created HeaderEntry, NULL on failure.
2475 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2477 gdcmHeaderEntry *NewEntry;
2482 // We reached the EOF (or an error occured) therefore
2483 // header parsing has to be considered as finished.
2484 return (gdcmHeaderEntry *)0;
2486 // Pb : how to propagate the element length (used in SkipHeaderEntry)
2487 // direct call to SkipBytes ?
2489 // if (ignoreShadow == 1 && g%2 ==1)
2490 // if user wants to skip shadow groups
2491 // and current element *is* a shadow element
2492 // we don't create anything
2493 // return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2495 NewEntry = NewHeaderEntryByNumber(g, n);
2496 FindHeaderEntryVR(NewEntry);
2497 FindHeaderEntryLength(NewEntry);
2503 NewEntry->SetOffset(ftell(fp));
2508 * \ingroup gdcmParser
2509 * \brief Build a new Element Value from all the low level arguments.
2510 * Check for existence of dictionary entry, and build
2511 * a default one when absent.
2512 * @param Name Name of the underlying DictEntry
2514 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2516 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2518 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2520 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2523 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2524 "failed to allocate gdcmHeaderEntry");
2525 return (gdcmHeaderEntry *)0;
2531 * \ingroup gdcmParser
2532 * \brief Request a new virtual dict entry to the dict set
2533 * @param group group of the underlying DictEntry
2534 * @param element element of the underlying DictEntry
2535 * @param vr VR of the underlying DictEntry
2536 * @param fourth owner group
2537 * @param name english name
2539 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2544 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2548 * \ingroup gdcmParser
2549 * \brief Build a new Element Value from all the low level arguments.
2550 * Check for existence of dictionary entry, and build
2551 * a default one when absent.
2552 * @param Group group of the underlying DictEntry
2553 * @param Elem element of the underlying DictEntry
2555 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2557 // Find out if the tag we encountered is in the dictionaries:
2558 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2560 DictEntry = NewVirtualDictEntry(Group, Elem);
2562 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2565 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2566 "failed to allocate gdcmHeaderEntry");
2572 // Never used; commented out, waiting for removal.
2574 * \ingroup gdcmParser
2575 * \brief Small utility function that creates a new manually crafted
2576 * (as opposed as read from the file) gdcmHeaderEntry with user
2577 * specified name and adds it to the public tag hash table.
2578 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2579 * @param NewTagName The name to be given to this new tag.
2580 * @param VR The Value Representation to be given to this new tag.
2581 * @return The newly hand crafted Element Value.
2583 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2586 // gdcmHeaderEntry *NewEntry = NULL;
2587 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2588 // guint32 FreeElem = 0;
2589 // gdcmDictEntry *DictEntry = NULL;
2591 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2592 // if (FreeElem == UINT32_MAX)
2594 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2595 // "Group 0xffff in Public Dict is full");
2599 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2600 // VR, "GDCM", NewTagName);
2601 // NewEntry = new gdcmHeaderEntry(DictEntry);
2602 // AddHeaderEntry(NewEntry);
2607 * \ingroup gdcmParser
2608 * \brief Generate a free TagKey i.e. a TagKey that is not present
2609 * in the TagHt dictionary.
2610 * @param group The generated tag must belong to this group.
2611 * @return The element of tag with given group which is fee.
2613 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2615 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2617 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2618 if (tagHT.count(key) == 0)
2624 //-----------------------------------------------------------------------------