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"
31 //-----------------------------------------------------------------------------
32 // Refer to gdcmParser::CheckSwap()
33 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
35 // Refer to gdcmParser::SetMaxSizeLoadEntry()
36 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
38 // Refer to gdcmParser::SetMaxSizePrintEntry()
39 // TODO : Right now, better see "define, in gdcmHederEntry.cxx
40 const unsigned int gdcmParser::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
42 //-----------------------------------------------------------------------------
43 // Constructor / Destructor
48 * @param exception_on_error whether we throw an exception or not
49 * @param enable_sequences = true to allow the header
50 * to be parsed *inside* the SeQuences,
51 * when they have an actual length
52 * @param ignore_shadow to allow skipping the shadow elements,
53 * to save memory space.
54 * \warning The TRUE value for this param has to be used
55 * with a FALSE value for the 'enable_sequence' param.
56 * ('public elements' may be embedded in 'shadow Sequences')
58 gdcmParser::gdcmParser(const char *inFilename,
59 bool exception_on_error,
60 bool enable_sequences,
62 enableSequences=enable_sequences;
63 ignoreShadow =ignore_shadow;
65 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
66 filename = inFilename;
69 if ( !OpenFile(exception_on_error))
76 wasUpdated = 0; // will be set to 1 if user adds an entry
77 printLevel = 1; // 'Medium' print level by default
83 * @param exception_on_error
85 gdcmParser::gdcmParser(bool exception_on_error) {
88 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
91 wasUpdated = 0; // will be set to 1 if user adds an entry
92 printLevel = 1; // 'Medium' print level by default
97 * \brief Canonical destructor.
99 gdcmParser::~gdcmParser (void) {
104 //-----------------------------------------------------------------------------
107 * \ingroup gdcmParser
108 * \brief Prints the Header Entries (Dicom Elements)
109 * both from the H Table and the chained list
112 void gdcmParser::PrintEntry(std::ostream & os) {
113 std::ostringstream s;
115 for (ListTag::iterator i = listEntries.begin();
116 i != listEntries.end();
119 (*i)->SetPrintLevel(printLevel);
126 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
129 void gdcmParser::PrintPubDict(std::ostream & os) {
130 RefPubDict->Print(os);
134 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnary
137 void gdcmParser::PrintShaDict(std::ostream & os) {
138 RefShaDict->Print(os);
141 //-----------------------------------------------------------------------------
144 * \brief Get the public dictionary used
146 gdcmDict *gdcmParser::GetPubDict(void) {
151 * \brief Get the shadow dictionary used
153 gdcmDict *gdcmParser::GetShaDict(void) {
158 * \brief Set the shadow dictionary used
159 * \param dict dictionary to use in shadow
161 bool gdcmParser::SetShaDict(gdcmDict *dict){
167 * \brief Set the shadow dictionary used
168 * \param dictName name of the dictionary to use in shadow
170 bool gdcmParser::SetShaDict(DictKey dictName){
171 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
176 * \brief This predicate, based on hopefully reasonable heuristics,
177 * decides whether or not the current gdcmParser was properly parsed
178 * and contains the mandatory information for being considered as
179 * a well formed and usable Dicom/Acr File.
180 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
183 bool gdcmParser::IsReadable(void) {
184 if(filetype==Unknown) {
187 if(listEntries.size()<=0) {
195 * \brief Determines if the Transfer Syntax was already encountered
196 * and if it corresponds to a ImplicitVRLittleEndian one.
197 * @return True when ImplicitVRLittleEndian found. False in all other cases.
199 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
200 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
203 LoadHeaderEntrySafe(Element);
205 std::string Transfer = Element->GetValue();
206 if ( Transfer == UI1_2_840_10008_1_2 )
212 * \ingroup gdcmParser
213 * \brief Determines if the Transfer Syntax was already encountered
214 * and if it corresponds to a ExplicitVRLittleEndian one.
215 * @return True when ExplicitVRLittleEndian found. False in all other cases.
217 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
218 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
221 LoadHeaderEntrySafe(Element);
223 std::string Transfer = Element->GetValue();
224 if ( Transfer == UI1_2_840_10008_1_2_1 )
230 * \brief Determines if the Transfer Syntax was already encountered
231 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
232 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
234 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
235 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
238 LoadHeaderEntrySafe(Element);
240 std::string Transfer = Element->GetValue();
241 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
247 * \brief Determines if the Transfer Syntax was already encountered
248 * and if it corresponds to a Explicit VR Big Endian one.
249 * @return True when big endian found. False in all other cases.
251 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
252 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
255 LoadHeaderEntrySafe(Element);
257 std::string Transfer = Element->GetValue();
258 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
264 * \brief returns the File Type
265 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
266 * @return the FileType code
268 FileType gdcmParser::GetFileType(void) {
273 * \brief opens the file
274 * @param exception_on_error
277 FILE *gdcmParser::OpenFile(bool exception_on_error)
280 fp=fopen(filename.c_str(),"rb");
281 if(exception_on_error)
284 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
290 fread(&zero, (size_t)2, (size_t)1, fp);
292 //ACR -- or DICOM with no Preamble --
293 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
297 fseek(fp, 126L, SEEK_CUR);
299 fread(dicm, (size_t)4, (size_t)1, fp);
300 if( memcmp(dicm, "DICM", 4) == 0 )
304 dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
307 dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
313 * \brief closes the file
314 * @return TRUE if the close was successfull
316 bool gdcmParser::CloseFile(void) {
317 int closed = fclose(fp);
325 * \brief Writes in a file all the Header Entries (Dicom Elements)
326 * of the Chained List
327 * @param fp file pointer on an already open file
328 * @param type Type of the File to be written
329 * (ACR-NEMA, ExplicitVR, ImplicitVR)
330 * \return Always true.
332 bool gdcmParser::Write(FILE *fp, FileType type) {
334 // TODO The stuff was rewritten using the chained list instead
336 // so we could remove the GroupHT from the gdcmParser
340 // TODO : move the following lines (and a lot of others, to be written)
341 // to a future function CheckAndCorrectHeader
344 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier
345 // DicomV3 ou non (FileType est un champ de gdcmParser ...)
346 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
348 // a moins de se livrer a un tres complique ajout des champs manquants.
349 // faire un CheckAndCorrectHeader (?)
351 if (type == ImplicitVR)
353 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
354 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
356 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
357 // values with a VR of UI shall be padded with a single trailing null
358 // Dans le cas suivant on doit pader manuellement avec un 0
360 SetEntryLengthByNumber(18, 0x0002, 0x0010);
363 if (type == ExplicitVR)
365 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
366 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
368 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
369 // values with a VR of UI shall be padded with a single trailing null
370 // Dans le cas suivant on doit pader manuellement avec un 0
372 SetEntryLengthByNumber(20, 0x0002, 0x0010);
375 /* TODO : rewrite later, if really usefull
377 --> Warning : un-updated odd groups lengths can causes pb
379 --> to be re- written with future org.
381 if ( (type == ImplicitVR) || (type == ExplicitVR) )
382 UpdateGroupLength(false,type);
384 UpdateGroupLength(true,ACR);
387 WriteEntries(fp,type);
392 * \brief Modifies the value of a given Header Entry (Dicom Element)
393 * when it exists. Create it with the given value when unexistant.
394 * \warning Adds the Header Entry to the HTable, NOT to the chained List
395 * @param Value Value to be set
396 * @param Group Group of the Entry
397 * @param Elem Element of the Entry
398 * \return pointer to the modified/created Header Entry (NULL when creation
401 gdcmHeaderEntry * gdcmParser::ReplaceOrCreateByNumber(
406 a = GetHeaderEntryByNumber( Group, Elem);
408 a =NewHeaderEntryByNumber(Group, Elem);
413 //CLEANME SetEntryByNumber(Value, Group, Elem);
419 * \brief Set a new value if the invoked element exists
420 * Seems to be useless !!!
421 * @param Value new element value
422 * @param Group group of the Entry
423 * @param Elem element of the Entry
426 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
428 std::string v = Value;
429 SetEntryByNumber(v, Group, Elem);
433 //-----------------------------------------------------------------------------
437 * \brief Checks if a given Dicom Element exists
439 * @param group Group number of the searched Dicom Element
440 * @param element Element number of the searched Dicom Element
441 * @return number of occurences
443 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
444 std::string key = gdcmDictEntry::TranslateToKey(group, element );
445 return (tagHT.count(key));
449 * \ingroup gdcmParser
450 * \brief Searches within Header Entries (Dicom Elements) parsed with
451 * the public and private dictionaries
452 * for the element value of a given tag.
453 * \warning Don't use any longer : use GetPubEntryByName
454 * @param tagName name of the searched element.
455 * @return Corresponding element value when it exists,
456 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
458 std::string gdcmParser::GetEntryByName(std::string tagName) {
459 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
460 if( dictEntry == NULL)
463 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
467 * \ingroup gdcmParser
468 * \brief Searches within Header Entries (Dicom Elements) parsed with
469 * the public and private dictionaries
470 * for the element value representation of a given tag.
472 * Obtaining the VR (Value Representation) might be needed by caller
473 * to convert the string typed content to caller's native type
474 * (think of C++ vs Python). The VR is actually of a higher level
475 * of semantics than just the native C++ type.
476 * @param tagName name of the searched element.
477 * @return Corresponding element value representation when it exists,
478 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
480 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
481 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
482 if( dictEntry == NULL)
485 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
486 dictEntry->GetElement());
487 return elem->GetVR();
492 * \ingroup gdcmParser
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.
496 * @param group Group of the searched tag.
497 * @param element Element of the searched tag.
498 * @return Corresponding element value representation when it exists,
499 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
501 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
502 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
503 if ( ! tagHT.count(key))
505 return tagHT.find(key)->second->GetValue();
509 * \ingroup gdcmParser
510 * \brief Searches within Header Entries (Dicom Elements) parsed with
511 * the public and private dictionaries
512 * for the element value representation of a given tag..
514 * Obtaining the VR (Value Representation) might be needed by caller
515 * to convert the string typed content to caller's native type
516 * (think of C++ vs Python). The VR is actually of a higher level
517 * of semantics than just the native C++ type.
518 * @param group Group of the searched tag.
519 * @param element Element of the searched tag.
520 * @return Corresponding element value representation when it exists,
521 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
523 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
524 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
527 return elem->GetVR();
531 * \ingroup gdcmParser
532 * \brief Searches within Header Entries (Dicom Elements) parsed with
533 * the public and private dictionaries
534 * for the value length of a given tag..
535 * @param group Group of the searched tag.
536 * @param element Element of the searched tag.
537 * @return Corresponding element length; -2 if not found
539 int gdcmParser::GetEntryLengthByNumber(guint16 group, guint16 element) {
540 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
543 return elem->GetLength();
546 * \ingroup gdcmParser
547 * \brief Sets the value (string) of the Header Entry (Dicom Element)
548 * @param content string value of the Dicom Element
549 * @param tagName name of the searched Dicom Element.
550 * @return true when found
552 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
553 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
554 if( dictEntry == NULL)
557 return(SetEntryByNumber(content,dictEntry->GetGroup(),
558 dictEntry->GetElement()));
562 * \ingroup gdcmParser
563 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
564 * through it's (group, element) and modifies it's content with
566 * \warning Don't use any longer : use SetPubEntryByNumber
567 * @param content new value to substitute with
568 * @param group group of the Dicom Element to modify
569 * @param element element of the Dicom Element to modify
571 bool gdcmParser::SetEntryByNumber(std::string content,
575 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
576 if ( ! tagHT.count(key))
578 int l = content.length();
579 if(l%2) // Non even length are padded with a space (020H).
582 content = content + '\0';
587 TagHeaderEntryHT::iterator p2;
588 // DO NOT remove the following lines : they explain the stuff
589 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
590 //p2=p.first; // iterator on the first synonym
591 //a=p2->second; // H Table target column (2-nd col)
594 a = ((tagHT.equal_range(key)).first)->second;
596 a-> SetValue(content);
598 std::string vr = a->GetVR();
601 if( (vr == "US") || (vr == "SS") )
603 else if( (vr == "UL") || (vr == "SL") )
613 * \ingroup gdcmParser
614 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
615 * in the PubHeaderEntrySet of this instance
616 * through it's (group, element) and modifies it's length with
618 * \warning Use with extreme caution.
619 * @param l new length to substitute with
620 * @param group group of the Entry to modify
621 * @param element element of the Entry to modify
622 * @return true on success, false otherwise.
624 bool gdcmParser::SetEntryLengthByNumber(guint32 l,
628 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
629 if ( ! tagHT.count(key))
631 if (l%2) l++; // length must be even
632 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
638 * \ingroup gdcmParser
639 * \brief Gets (from Header) the offset of a 'non string' element value
640 * (LoadElementValues has already be executed)
641 * @param Group group of the Entry
642 * @param Elem element of the Entry
643 * @return File Offset of the Element Value
645 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
647 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
650 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
651 "failed to Locate gdcmHeaderEntry");
654 return Entry->GetOffset();
658 * \ingroup gdcmParser
659 * \brief Gets (from Header) a 'non string' element value
660 * (LoadElementValues has already be executed)
661 * @param Group group of the Entry
662 * @param Elem element of the Entry
663 * @return Pointer to the 'non string' area
665 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
667 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
670 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
671 "failed to Locate gdcmHeaderEntry");
674 return Entry->GetVoidArea();
678 * \brief Loads (from disk) the element content
679 * when a string is not suitable
680 * @param Group group of the Entry
681 * @param Elem element of the Entry
683 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
685 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
688 size_t o =(size_t)Element->GetOffset();
689 fseek(fp, o, SEEK_SET);
690 int l=Element->GetLength();
691 void * a = malloc(l);
695 SetEntryVoidAreaByNumber(a, Group, Elem);
696 // TODO check the result
697 size_t l2 = fread(a, 1, l ,fp);
708 * \ingroup gdcmParser
709 * \brief Sets a 'non string' value to a given Dicom Element
711 * @param group Group number of the searched Dicom Element
712 * @param element Element number of the searched Dicom Element
715 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
719 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
720 if ( ! tagHT.count(key))
722 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
727 * \ingroup gdcmParser
728 * \brief Update the entries with the shadow dictionary.
729 * Only non even entries are analyzed
731 void gdcmParser::UpdateShaEntries(void) {
732 gdcmDictEntry *entry;
735 for(ListTag::iterator it=listEntries.begin();
736 it!=listEntries.end();
739 // Odd group => from public dictionary
740 if((*it)->GetGroup()%2==0)
743 // Peer group => search the corresponding dict entry
745 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
749 if((*it)->IsImplicitVR())
754 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
756 // Set the new entry and the new value
757 (*it)->SetDictEntry(entry);
758 CheckHeaderEntryVR(*it,vr);
760 (*it)->SetValue(GetHeaderEntryValue(*it));
764 // Remove precedent value transformation
765 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
771 * \ingroup gdcmParser
772 * \brief Searches within the Header Entries for a Dicom Element of
774 * @param tagName name of the searched Dicom Element.
775 * @return Corresponding Dicom Element when it exists, and NULL
778 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
779 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
780 if( dictEntry == NULL)
783 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
787 * \ingroup gdcmParser
788 * \brief retrieves a Dicom Element (the first one) using (group, element)
789 * \warning (group, element) IS NOT an identifier inside the Dicom Header
790 * if you think it's NOT UNIQUE, check the count number
791 * and use iterators to retrieve ALL the Dicoms Elements within
792 * a given couple (group, element)
793 * @param group Group number of the searched Dicom Element
794 * @param element Element number of the searched Dicom Element
797 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
799 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
800 if ( ! tagHT.count(key))
802 return tagHT.find(key)->second;
806 * \ingroup gdcmParser
807 * \brief retrieves the Dicom Elements (all of them) using (group, element)
808 * @param group Group number of the searched Dicom Element.
809 * @param element Element number of the searched Dicom Element.
810 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
813 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
814 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
815 return (tagHT.equal_range(key));
819 * \ingroup gdcmParser
820 * \brief Loads the element while preserving the current
821 * underlying file position indicator as opposed to
822 * to LoadHeaderEntry that modifies it.
823 * @param entry Header Entry whose value shall be loaded.
826 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
827 long PositionOnEntry = ftell(fp);
828 LoadHeaderEntry(entry);
829 fseek(fp, PositionOnEntry, SEEK_SET);
833 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
834 * \warning : to be re-written using the chained list instead of the H table.
835 * \warning : DO NOT use (doesn't work any longer because of the multimap)
836 * \todo : to be re-written using the chained list instead of the H table
837 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
838 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
840 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
844 gdcmHeaderEntry *elem;
846 std::string str_trash;
849 GroupHT groupHt; // to hold the length of each group
852 // typedef std::map<GroupKey, int> GroupHT;
854 gdcmHeaderEntry *elemZ;
856 // for each Tag in the DCM Header
858 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
863 gr = elem->GetGroup();
864 el = elem->GetElement();
867 sprintf(trash, "%04x", gr);
868 key = trash; // generate 'group tag'
870 // if the caller decided not to take SEQUENCEs into account
871 // e.g : he wants to write an ACR-NEMA File
873 if (SkipSequence && vr == "SQ")
876 // Still unsolved problem :
877 // we cannot find the 'Sequence Delimitation Item'
878 // since it's at the end of the Hash Table
881 // pas SEQUENCE en ACR-NEMA
883 // --> la descente a l'interieur' des SQ
884 // devrait etre faite avec une liste chainee, pas avec une HTable...
886 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
888 if (el == 0x0000) // the first elem is 0x0000
890 groupHt[key] = 0; // initialize group length
894 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
897 else // any elem but the first
899 if (type == ExplicitVR)
901 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
903 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
906 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
910 unsigned short int gr_bid;
912 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
916 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
917 // warning: unsigned int format, different type arg
918 sscanf(g->first.c_str(),"%x",&gr_bid);
919 tk = g->first + "|0000"; // generate the element full tag
921 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
923 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
924 elemZ = new gdcmHeaderEntry(tagZ);
926 AddHeaderEntry(elemZ); // create it
930 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
932 sprintf(trash ,"%d",g->second);
934 elemZ->SetValue(str_trash);
939 * \brief Writes in a file (according to the requested format)
940 * the group, the element, the value representation and the length
941 * of a single gdcmHeaderEntry passed as argument.
942 * @param tag pointer on the gdcmHeaderEntry to be written
943 * @param _fp already open file pointer
944 * @param type type of the File to be written
946 void gdcmParser::WriteEntryTagVRLength(gdcmHeaderEntry *tag,
950 guint16 group = tag->GetGroup();
951 std::string vr = tag->GetVR();
952 guint16 el = tag->GetElement();
953 guint32 lgr = tag->GetReadLength();
955 if ( (group == 0xfffe) && (el == 0x0000) )
956 // Fix in order to make some MR PHILIPS images e-film readable
957 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
958 // we just *always* ignore spurious fffe|0000 tag !
961 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
962 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
964 if ( type == ExplicitVR ) {
966 // Special case of delimiters:
967 if (group == 0xfffe) {
968 // Delimiters have NO Value Representation and have NO length.
969 // Hence we skip writing the VR and length and we pad by writing
973 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
978 guint16 shortLgr = lgr;
979 if (vr == "unkn") { // Unknown was 'written'
980 // deal with Little Endian
981 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
982 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
984 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
985 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
987 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
988 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
990 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
996 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1001 * \brief Writes in a file (according to the requested format)
1002 * the value of a single gdcmHeaderEntry passed as argument.
1003 * @param tag Pointer on the gdcmHeaderEntry to be written
1004 * @param _fp Already open file pointer
1005 * @param type type of the File to be written
1007 void gdcmParser::WriteEntryValue(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1009 guint16 group = tag->GetGroup();
1010 std::string vr = tag->GetVR();
1011 guint32 lgr = tag->GetReadLength();
1014 // SeQuences have no value:
1016 if (group == 0xfffe)
1017 // Delimiters have no associated value:
1021 voidArea = tag->GetVoidArea();
1022 if (voidArea != NULL)
1023 { // there is a 'non string' LUT, overlay, etc
1024 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1028 if (vr == "US" || vr == "SS")
1030 // some 'Short integer' fields may be mulivaluated
1031 // each single value is separated from the next one by \
1032 // we split the string and write each value as a short int
1033 std::vector<std::string> tokens;
1034 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1035 Tokenize (tag->GetValue(), tokens, "\\");
1036 for (unsigned int i=0; i<tokens.size();i++)
1038 guint16 val_uint16 = atoi(tokens[i].c_str());
1039 void *ptr = &val_uint16;
1040 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1045 // some 'Integer' fields may be mulivaluated
1046 // each single value is separated from the next one by \
1047 // we split the string and write each value as an int
1048 if (vr == "UL" || vr == "SL")
1050 std::vector<std::string> tokens;
1051 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1052 Tokenize (tag->GetValue(), tokens, "\\");
1053 for (unsigned int i=0; i<tokens.size();i++)
1055 guint32 val_uint32 = atoi(tokens[i].c_str());
1056 void *ptr = &val_uint32;
1057 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1062 fwrite (tag->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1066 * \brief Writes in a file (according to the requested format)
1067 * a single gdcmHeaderEntry passed as argument.
1068 * \sa WriteEntryValue, WriteEntryTagVRLength.
1069 * @param tag Pointer on the gdcmHeaderEntry to be written
1070 * @param _fp Already open file pointer
1071 * @param type type of the File to be written
1074 bool gdcmParser::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1076 guint32 length = tag->GetLength();
1078 // The value of a tag MUST (see the DICOM norm) be an odd number of
1079 // bytes. When this is not the case, pad with an additional byte:
1082 tag->SetValue(tag->GetValue()+"\0");
1083 tag->SetLength(tag->GetReadLength()+1);
1086 WriteEntryTagVRLength(tag, _fp, type);
1087 WriteEntryValue(tag, _fp, type);
1092 * \brief writes on disc according to the requested format
1093 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1094 * using the Chained List
1095 * \warning does NOT add the missing elements in the header :
1096 * it's up to the user doing it !
1097 * (function CheckHeaderCoherence to be written)
1098 * \warning DON'T try, right now, to write a DICOM image
1099 * from an ACR Header (meta elements will be missing!)
1100 * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1101 * @param type type of the File to be written
1102 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1103 * @param _fp already open file pointer
1106 bool gdcmParser::WriteEntries(FILE *_fp,FileType type)
1108 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1110 for (ListTag::iterator tag2=listEntries.begin();
1111 tag2 != listEntries.end();
1115 if ((*tag2)->GetGroup() < 0x0008)
1116 // Ignore pure DICOM V3 groups
1118 if ((*tag2)->GetElement() %2)
1119 // Ignore the "shadow" groups
1121 if ((*tag2)->GetVR() == "SQ" )
1122 // For the time being sequences are simply ignored
1123 // TODO : find a trick not to *skip* the SeQuences !
1125 if ((*tag2)->GetGroup() == 0xfffe )
1126 // Ignore the documented delimiter
1129 if (! WriteEntry(*tag2,_fp,type) )
1136 * \ingroup gdcmParser
1137 * \brief writes on disc according to the requested format
1138 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1139 * using only the last synonym of each mutimap H Table post.
1140 * \warning Uses the H Table, instead of the Chained List
1141 * in order to be compliant with the old way to proceed
1142 * (added elements taken in to account)
1143 * Only THERALYS, during a transitory phase is supposed
1144 * to use this method !!!
1145 * \warning DON'T try, right now, to write a DICOM image
1146 * from an ACR Header (meta elements will be missing!)
1148 * @param _fp already open file pointer
1149 * @param type type of the File to be written
1150 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1152 void gdcmParser::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1154 // restent a tester les echecs en ecriture (apres chaque fwrite)
1156 for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1157 tag2 != tagHT.end();
1160 if ((*tag2->second).GetGroup() < 0x0008) continue; // ignore pure DICOM V3 groups
1161 if ((*tag2->second).GetElement() %2) continue; // ignore shadow groups
1162 if ((*tag2->second).GetVR() == "SQ" ) continue; // ignore Sequences
1163 // TODO : find a trick to *skip* the SeQuences !
1164 // Not only ignore the SQ element
1165 // --> will be done with the next organization
1166 if ((*tag2->second).GetGroup() == 0xfffe ) continue; // ignore delimiters
1168 if ( ! WriteEntry(tag2->second,_fp,type))
1174 * \ingroup gdcmParser
1175 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1177 * @return The properly swaped 32 bits integer.
1179 guint32 gdcmParser::SwapLong(guint32 a) {
1184 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1185 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1189 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1193 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1196 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1203 * \ingroup gdcmParser
1204 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1206 * @return The properly unswaped 32 bits integer.
1208 guint32 gdcmParser::UnswapLong(guint32 a) {
1209 return (SwapLong(a));
1213 * \ingroup gdcmParser
1214 * \brief Swaps the bytes so they agree with the processor order
1215 * @return The properly swaped 16 bits integer.
1217 guint16 gdcmParser::SwapShort(guint16 a) {
1218 if ( (sw==4321) || (sw==2143) )
1219 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1224 * \ingroup gdcmParser
1225 * \brief Unswaps the bytes so they agree with the processor order
1226 * @return The properly unswaped 16 bits integer.
1228 guint16 gdcmParser::UnswapShort(guint16 a) {
1229 return (SwapShort(a));
1232 //-----------------------------------------------------------------------------
1235 * \ingroup gdcmParser
1236 * \brief Parses the header of the file but WITHOUT loading element values.
1237 * @return false if file is not ACR-NEMA / DICOM
1239 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1245 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1246 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1247 SkipHeaderEntry(newHeaderEntry);
1248 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1249 AddHeaderEntry(newHeaderEntry);
1256 * \ingroup gdcmParser
1257 * \brief Loads the element values of all the Header Entries pointed in the
1258 * public Chained List.
1260 void gdcmParser::LoadHeaderEntries(void) {
1262 for (ListTag::iterator i = GetListEntry().begin();
1263 i != GetListEntry().end();
1266 LoadHeaderEntry(*i);
1271 // Load 'non string' values
1272 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1273 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1274 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1275 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1276 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1277 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1279 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1280 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1281 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1283 //FIXME : how to use it?
1284 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1286 // --------------------------------------------------------------
1287 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1289 // if recognition code tells us we deal with a LibIDO image
1290 // we switch lineNumber and columnNumber
1292 std::string RecCode;
1293 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1294 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1295 RecCode == "CANRME_AILIBOD1_1." )
1297 filetype = ACR_LIBIDO;
1298 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1299 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1300 SetEntryByNumber(columns, 0x0028, 0x0010);
1301 SetEntryByNumber(rows , 0x0028, 0x0011);
1303 // ----------------- End of Special Patch ----------------
1307 * \ingroup gdcmParser
1308 * \brief Loads the element content if its length doesn't exceed
1309 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1310 * @param Entry Header Entry (Dicom Element) to be dealt with
1312 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1314 guint16 group = Entry->GetGroup();
1315 std::string vr= Entry->GetVR();
1316 guint32 length = Entry->GetLength();
1317 bool SkipLoad = false;
1319 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1321 // the test was commented out to 'go inside' the SeQuences
1322 // we don't any longer skip them !
1324 // if( vr == "SQ" ) // (DO NOT remove this comment)
1327 // A SeQuence "contains" a set of Elements.
1328 // (fffe e000) tells us an Element is beginning
1329 // (fffe e00d) tells us an Element just ended
1330 // (fffe e0dd) tells us the current SeQuence just ended
1331 if( group == 0xfffe )
1335 Entry->SetLength(0);
1336 Entry->SetValue("gdcm::Skipped");
1340 // When the length is zero things are easy:
1341 if ( length == 0 ) {
1342 Entry->SetValue("");
1346 // The elements whose length is bigger than the specified upper bound
1347 // are not loaded. Instead we leave a short notice of the offset of
1348 // the element content and it's length.
1349 if (length > MaxSizeLoadEntry) {
1350 std::ostringstream s;
1351 s << "gdcm::NotLoaded.";
1352 s << " Address:" << (long)Entry->GetOffset();
1353 s << " Length:" << Entry->GetLength();
1354 s << " x(" << std::hex << Entry->GetLength() << ")";
1355 Entry->SetValue(s.str());
1359 // Any compacter code suggested (?)
1360 if ( IsHeaderEntryAnInteger(Entry) ) {
1362 std::ostringstream s;
1364 // When short integer(s) are expected, read and convert the following
1365 // n *two characters properly i.e. as short integers as opposed to strings.
1366 // Elements with Value Multiplicity > 1
1367 // contain a set of integers (not a single one)
1368 if (vr == "US" || vr == "SS") {
1370 NewInt = ReadInt16();
1373 for (int i=1; i < nbInt; i++) {
1375 NewInt = ReadInt16();
1380 // When integer(s) are expected, read and convert the following
1381 // n * four characters properly i.e. as integers as opposed to strings.
1382 // Elements with Value Multiplicity > 1
1383 // contain a set of integers (not a single one)
1384 else if (vr == "UL" || vr == "SL") {
1386 NewInt = ReadInt32();
1389 for (int i=1; i < nbInt; i++) {
1391 NewInt = ReadInt32();
1396 #ifdef GDCM_NO_ANSI_STRING_STREAM
1397 s << std::ends; // to avoid oddities on Solaris
1398 #endif //GDCM_NO_ANSI_STRING_STREAM
1400 Entry->SetValue(s.str());
1404 // We need an additional byte for storing \0 that is not on disk
1405 std::string NewValue(length,0);
1406 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1407 if ( item_read != 1 ) {
1408 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1409 Entry->SetValue("gdcm::UnRead");
1413 if( (vr == "UI") ) // Because of correspondance with the VR dic
1414 Entry->SetValue(NewValue.c_str());
1416 Entry->SetValue(NewValue);
1420 * \ingroup gdcmParser
1421 * \brief add a new Dicom Element pointer to
1422 * the H Table and at the end of the chained List
1423 * \warning push_bash in listEntries ONLY during ParseHeader
1424 * \todo something to allow further Elements addition,
1425 * (at their right place in the chained list)
1426 * when position to be taken care of
1427 * @param newHeaderEntry
1429 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1430 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1431 listEntries.push_back(newHeaderEntry);
1436 * \ingroup gdcmParser
1437 * \brief Find the value Length of the passed Header Entry
1438 * @param Entry Header Entry whose length of the value shall be loaded.
1440 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1441 guint16 element = Entry->GetElement();
1442 guint16 group = Entry->GetGroup();
1443 std::string vr = Entry->GetVR();
1446 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1448 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1450 // The following reserved two bytes (see PS 3.5-2001, section
1451 // 7.1.2 Data element structure with explicit vr p27) must be
1452 // skipped before proceeding on reading the length on 4 bytes.
1453 fseek(fp, 2L, SEEK_CUR);
1454 guint32 length32 = ReadInt32();
1456 if ( (vr == "OB") && (length32 == 0xffffffff) )
1458 Entry->SetLength(FindHeaderEntryLengthOB());
1461 FixHeaderEntryFoundLength(Entry, length32);
1465 // Length is encoded on 2 bytes.
1466 length16 = ReadInt16();
1468 // We can tell the current file is encoded in big endian (like
1469 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1470 // and it's value is the one of the encoding of a big endian file.
1471 // In order to deal with such big endian encoded files, we have
1472 // (at least) two strategies:
1473 // * when we load the "Transfer Syntax" tag with value of big endian
1474 // encoding, we raise the proper flags. Then we wait for the end
1475 // of the META group (0x0002) among which is "Transfer Syntax",
1476 // before switching the swap code to big endian. We have to postpone
1477 // the switching of the swap code since the META group is fully encoded
1478 // in little endian, and big endian coding only starts at the next
1479 // group. The corresponding code can be hard to analyse and adds
1480 // many additional unnecessary tests for regular tags.
1481 // * the second strategy consists in waiting for trouble, that shall
1482 // appear when we find the first group with big endian encoding. This
1483 // is easy to detect since the length of a "Group Length" tag (the
1484 // ones with zero as element number) has to be of 4 (0x0004). When we
1485 // encounter 1024 (0x0400) chances are the encoding changed and we
1486 // found a group with big endian encoding.
1487 // We shall use this second strategy. In order to make sure that we
1488 // can interpret the presence of an apparently big endian encoded
1489 // length of a "Group Length" without committing a big mistake, we
1490 // add an additional check: we look in the already parsed elements
1491 // for the presence of a "Transfer Syntax" whose value has to be "big
1492 // endian encoding". When this is the case, chances are we have got our
1493 // hands on a big endian encoded file: we switch the swap code to
1494 // big endian and proceed...
1495 if ( (element == 0x0000) && (length16 == 0x0400) )
1497 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1499 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1504 SwitchSwapToBigEndian();
1505 // Restore the unproperly loaded values i.e. the group, the element
1506 // and the dictionary entry depending on them.
1507 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1508 guint16 CorrectElem = SwapShort(Entry->GetElement());
1509 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1513 // This correct tag is not in the dictionary. Create a new one.
1514 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1516 // FIXME this can create a memory leaks on the old entry that be
1517 // left unreferenced.
1518 Entry->SetDictEntry(NewTag);
1521 // Heuristic: well some files are really ill-formed.
1522 if ( length16 == 0xffff)
1525 //dbg.Verbose(0, "gdcmParser::FindLength",
1526 // "Erroneous element length fixed.");
1527 // Actually, length= 0xffff means that we deal with
1528 // Unknown Sequence Length
1530 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1535 // Either implicit VR or a non DICOM conformal (see note below) explicit
1536 // VR that ommited the VR of (at least) this element. Farts happen.
1537 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1538 // on Data elements "Implicit and Explicit VR Data Elements shall
1539 // not coexist in a Data Set and Data Sets nested within it".]
1540 // Length is on 4 bytes.
1542 FixHeaderEntryFoundLength(Entry, ReadInt32());
1548 * \ingroup gdcmParser
1549 * \brief Find the Value Representation of the current Dicom Element.
1552 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1554 if (filetype != ExplicitVR)
1559 long PositionOnEntry = ftell(fp);
1560 // Warning: we believe this is explicit VR (Value Representation) because
1561 // we used a heuristic that found "UL" in the first tag. Alas this
1562 // doesn't guarantee that all the tags will be in explicit VR. In some
1563 // cases (see e-film filtered files) one finds implicit VR tags mixed
1564 // within an explicit VR file. Hence we make sure the present tag
1565 // is in explicit VR and try to fix things if it happens not to be
1568 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1570 if(!CheckHeaderEntryVR(Entry,VR))
1572 fseek(fp, PositionOnEntry, SEEK_SET);
1573 // When this element is known in the dictionary we shall use, e.g. for
1574 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1575 // dictionary entry. Still we have to flag the element as implicit since
1576 // we know now our assumption on expliciteness is not furfilled.
1578 if ( Entry->IsVRUnknown() )
1579 Entry->SetVR("Implicit");
1580 Entry->SetImplicitVR();
1585 * \ingroup gdcmParser
1586 * \brief Check the correspondance between the VR of the header entry
1587 * and the taken VR. If they are different, the header entry is
1588 * updated with the new VR.
1589 * @param Entry Header Entry to check
1590 * @param vr Dicom Value Representation
1591 * @return false if the VR is incorrect of if the VR isn't referenced
1592 * otherwise, it returns true
1594 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1596 char msg[100]; // for sprintf
1597 bool RealExplicit = true;
1599 // Assume we are reading a falsely explicit VR file i.e. we reached
1600 // a tag where we expect reading a VR but are in fact we read the
1601 // first to bytes of the length. Then we will interogate (through find)
1602 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1603 // both GCC and VC++ implementations of the STL map. Hence when the
1604 // expected VR read happens to be non-ascii characters we consider
1605 // we hit falsely explicit VR tag.
1607 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1608 RealExplicit = false;
1610 // CLEANME searching the dicom_vr at each occurence is expensive.
1611 // PostPone this test in an optional integrity check at the end
1612 // of parsing or only in debug mode.
1613 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1614 RealExplicit= false;
1616 if ( !RealExplicit )
1618 // We thought this was explicit VR, but we end up with an
1619 // implicit VR tag. Let's backtrack.
1620 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1621 Entry->GetGroup(),Entry->GetElement());
1622 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1623 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1624 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1625 Entry->GetGroup(),Entry->GetElement(),
1626 "UL","FIXME","Group Length");
1627 Entry->SetDictEntry(NewEntry);
1632 if ( Entry->IsVRUnknown() )
1634 // When not a dictionary entry, we can safely overwrite the VR.
1635 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1641 else if ( Entry->GetVR() != vr )
1643 // The VR present in the file and the dictionary disagree. We assume
1644 // the file writer knew best and use the VR of the file. Since it would
1645 // be unwise to overwrite the VR of a dictionary (since it would
1646 // compromise it's next user), we need to clone the actual DictEntry
1647 // and change the VR for the read one.
1648 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1649 Entry->GetGroup(),Entry->GetElement(),
1650 vr,"FIXME",Entry->GetName());
1651 Entry->SetDictEntry(NewEntry);
1657 * \ingroup gdcmParser
1658 * \brief Get the transformed value of the header entry. The VR value
1659 * is used to define the transformation to operate on the value
1660 * \warning NOT end user intended method !
1662 * @return Transformed entry value
1664 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1666 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1668 std::string val=Entry->GetValue();
1669 std::string vr=Entry->GetVR();
1670 guint32 length = Entry->GetLength();
1671 std::ostringstream s;
1674 // When short integer(s) are expected, read and convert the following
1675 // n * 2 bytes properly i.e. as a multivaluated strings
1676 // (each single value is separated fromthe next one by \
1677 // as usual for standard multivaluated filels
1678 // Elements with Value Multiplicity > 1
1679 // contain a set of short integers (not a single one)
1681 if (vr == "US" || vr == "SS")
1686 for (int i=0; i < nbInt; i++)
1690 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1691 NewInt16 = SwapShort(NewInt16);
1696 // When integer(s) are expected, read and convert the following
1697 // n * 4 bytes properly i.e. as a multivaluated strings
1698 // (each single value is separated fromthe next one by \
1699 // as usual for standard multivaluated filels
1700 // Elements with Value Multiplicity > 1
1701 // contain a set of integers (not a single one)
1702 else if (vr == "UL" || vr == "SL")
1707 for (int i=0; i < nbInt; i++)
1711 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1712 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1713 NewInt32=SwapLong(NewInt32);
1717 #ifdef GDCM_NO_ANSI_STRING_STREAM
1718 s << std::ends; // to avoid oddities on Solaris
1719 #endif //GDCM_NO_ANSI_STRING_STREAM
1723 return(Entry->GetValue());
1727 * \ingroup gdcmParser
1728 * \brief Get the reverse transformed value of the header entry. The VR
1729 * value is used to define the reverse transformation to operate on
1731 * \warning NOT end user intended method !
1733 * @return Reverse transformed entry value
1735 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1737 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1739 std::string vr=Entry->GetVR();
1740 std::ostringstream s;
1741 std::vector<std::string> tokens;
1743 if (vr == "US" || vr == "SS")
1747 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1748 Tokenize (Entry->GetValue(), tokens, "\\");
1749 for (unsigned int i=0; i<tokens.size();i++)
1751 NewInt16 = atoi(tokens[i].c_str());
1752 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1756 if (vr == "UL" || vr == "SL")
1760 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1761 Tokenize (Entry->GetValue(), tokens, "\\");
1762 for (unsigned int i=0; i<tokens.size();i++)
1764 NewInt32 = atoi(tokens[i].c_str());
1765 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1766 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1771 #ifdef GDCM_NO_ANSI_STRING_STREAM
1772 s << std::ends; // to avoid oddities on Solaris
1773 #endif //GDCM_NO_ANSI_STRING_STREAM
1777 return(Entry->GetValue());
1781 * \ingroup gdcmParser
1782 * \brief Skip a given Header Entry
1783 * \warning NOT end user intended method !
1786 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1788 SkipBytes(entry->GetLength());
1792 * \ingroup gdcmParser
1793 * \brief When the length of an element value is obviously wrong (because
1794 * the parser went Jabberwocky) one can hope improving things by
1795 * applying this heuristic.
1797 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1799 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1801 if ( FoundLength == 0xffffffff) {
1805 guint16 gr =Entry->GetGroup();
1806 guint16 el =Entry->GetElement();
1808 if (FoundLength%2) {
1809 std::ostringstream s;
1810 s << "Warning : Tag with uneven length " << FoundLength
1811 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1812 dbg.Verbose(0,s.str().c_str());
1815 // Sorry for the patch!
1816 // XMedCom did the trick to read some nasty GE images ...
1817 if (FoundLength == 13) {
1818 // The following 'if' will be removed when there is no more
1819 // images on Creatis HDs with a 13 length for Manufacturer...
1820 if ( (Entry->GetGroup() != 0x0008) ||
1821 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1822 // end of remove area
1824 Entry->SetReadLength(10); // a bug is to be fixed
1828 // to fix some garbage 'Leonardo' Siemens images
1829 // May be commented out to avoid overhead
1830 else if ( (Entry->GetGroup() == 0x0009) &&
1831 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1833 Entry->SetReadLength(4); // a bug is to be fixed
1837 // to try to 'go inside' SeQuences (with length), and not to skip them
1838 else if ( Entry->GetVR() == "SQ")
1840 if (enableSequences) // only if the user does want to !
1841 FoundLength =0; // ReadLength is unchanged
1844 // a SeQuence Element is beginning
1845 // fffe|e000 is just a marker, its length *should be* zero
1846 else if(Entry->GetGroup() == 0xfffe)
1848 // *normally, fffe|0000 doesn't exist !
1849 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1850 // causes extra troubles :-(
1853 Entry->SetUsableLength(FoundLength);
1857 * \ingroup gdcmParser
1858 * \brief Apply some heuristics to predict whether the considered
1859 * element value contains/represents an integer or not.
1860 * @param Entry The element value on which to apply the predicate.
1861 * @return The result of the heuristical predicate.
1863 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1864 guint16 element = Entry->GetElement();
1865 guint16 group = Entry->GetGroup();
1866 std::string vr = Entry->GetVR();
1867 guint32 length = Entry->GetLength();
1868 // When we have some semantics on the element we just read, and if we
1869 // a priori know we are dealing with an integer, then we shall be
1870 // able to swap it's element value properly.
1871 if ( element == 0 ) // This is the group length of the group
1877 std::ostringstream s;
1878 int filePosition = ftell(fp);
1879 s << "Erroneous Group Length element length on : (" \
1880 << std::hex << group << " , " << element
1881 << ") -before- position x(" << filePosition << ")"
1882 << "lgt : " << length;
1883 // These 2 lines commented out : a *very dirty* patch
1884 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1885 // have a glance at offset x(8336) ...
1886 // For *regular* headers, the test is useless..
1887 // lets's print a warning message and go on,
1888 // instead of giving up with an error message
1890 //std::cout << s.str().c_str() << std::endl;
1891 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1892 // s.str().c_str());
1895 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1901 * \ingroup gdcmParser
1902 * \brief Find the Length till the next sequence delimiter
1903 * \warning NOT end user intended method !
1907 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1908 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1911 long PositionOnEntry = ftell(fp);
1912 bool FoundSequenceDelimiter = false;
1913 guint32 TotalLength = 0;
1916 while ( ! FoundSequenceDelimiter)
1922 TotalLength += 4; // We even have to decount the group and element
1924 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1926 char msg[100]; // for sprintf. Sorry
1927 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1928 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1932 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1933 FoundSequenceDelimiter = true;
1934 else if ( n != 0xe000 )
1936 char msg[100]; // for sprintf. Sorry
1937 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1939 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1943 ItemLength = ReadInt32();
1944 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1945 // the ItemLength with ReadInt32
1946 SkipBytes(ItemLength);
1948 fseek(fp, PositionOnEntry, SEEK_SET);
1953 * \ingroup gdcmParser
1954 * \brief Reads a supposed to be 16 Bits integer
1955 * (swaps it depending on processor endianity)
1956 * @return read value
1958 guint16 gdcmParser::ReadInt16(void) {
1961 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1962 if ( item_read != 1 ) {
1964 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1974 * \ingroup gdcmParser
1975 * \brief Reads a supposed to be 32 Bits integer
1976 * (swaps it depending on processor endianity)
1977 * @return read value
1979 guint32 gdcmParser::ReadInt32(void) {
1982 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1983 if ( item_read != 1 ) {
1985 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1995 * \ingroup gdcmParser
1996 * \brief skips bytes inside the source file
1997 * \warning NOT end user intended method !
2000 void gdcmParser::SkipBytes(guint32 NBytes) {
2001 //FIXME don't dump the returned value
2002 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2006 * \ingroup gdcmParser
2007 * \brief Loads all the needed Dictionaries
2008 * \warning NOT end user intended method !
2010 void gdcmParser::Initialise(void)
2012 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2013 RefShaDict = (gdcmDict*)0;
2017 * \ingroup gdcmParser
2018 * \brief Discover what the swap code is (among little endian, big endian,
2019 * bad little endian, bad big endian).
2021 * @return false when we are absolutely sure
2022 * it's neither ACR-NEMA nor DICOM
2023 * true when we hope ours assuptions are OK
2025 bool gdcmParser::CheckSwap() {
2027 // The only guaranted way of finding the swap code is to find a
2028 // group tag since we know it's length has to be of four bytes i.e.
2029 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2030 // occurs when we can't find such group...
2032 guint32 x=4; // x : for ntohs
2033 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2039 char deb[HEADER_LENGTH_TO_READ];
2041 // First, compare HostByteOrder and NetworkByteOrder in order to
2042 // determine if we shall need to swap bytes (i.e. the Endian type).
2048 // The easiest case is the one of a DICOM header, since it possesses a
2049 // file preamble where it suffice to look for the string "DICM".
2050 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2053 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2054 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2056 // Next, determine the value representation (VR). Let's skip to the
2057 // first element (0002, 0000) and check there if we find "UL"
2058 // - or "OB" if the 1st one is (0002,0001) -,
2059 // in which case we (almost) know it is explicit VR.
2060 // WARNING: if it happens to be implicit VR then what we will read
2061 // is the length of the group. If this ascii representation of this
2062 // length happens to be "UL" then we shall believe it is explicit VR.
2063 // FIXME: in order to fix the above warning, we could read the next
2064 // element value (or a couple of elements values) in order to make
2065 // sure we are not commiting a big mistake.
2066 // We need to skip :
2067 // * the 128 bytes of File Preamble (often padded with zeroes),
2068 // * the 4 bytes of "DICM" string,
2069 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2070 // i.e. a total of 136 bytes.
2074 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2075 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2076 // *Implicit* VR. -and it is !-
2078 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2079 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2080 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2081 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2082 // when Write DCM *adds*
2084 // Use gdcmParser::dicom_vr to test all the possibilities
2085 // instead of just checking for UL, OB and UI !? group 0000
2087 filetype = ExplicitVR;
2088 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2089 "explicit Value Representation");
2093 filetype = ImplicitVR;
2094 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2095 "not an explicit Value Representation");
2101 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2102 "HostByteOrder != NetworkByteOrder");
2107 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2108 "HostByteOrder = NetworkByteOrder");
2111 // Position the file position indicator at first tag (i.e.
2112 // after the file preamble and the "DICM" string).
2114 fseek (fp, 132L, SEEK_SET);
2118 // Alas, this is not a DicomV3 file and whatever happens there is no file
2119 // preamble. We can reset the file position indicator to where the data
2120 // is (i.e. the beginning of the file).
2121 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2124 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2125 // By clean we mean that the length of the first tag is written down.
2126 // If this is the case and since the length of the first group HAS to be
2127 // four (bytes), then determining the proper swap code is straightforward.
2130 // We assume the array of char we are considering contains the binary
2131 // representation of a 32 bits integer. Hence the following dirty
2133 s32 = *((guint32 *)(entCur));
2154 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2155 // It is time for despaired wild guesses.
2156 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2157 // i.e. the 'group length' element is not present :
2159 // check the supposed to be 'group number'
2160 // 0x0002 or 0x0004 or 0x0008
2161 // to determine ' sw' value .
2162 // Only 0 or 4321 will be possible
2163 // (no oportunity to check for the formerly well known
2164 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2165 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2166 // the file IS NOT ACR-NEMA nor DICOM V3
2167 // Find a trick to tell it the caller...
2169 s16 = *((guint16 *)(deb));
2185 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2186 "ACR/NEMA unfound swap info (Really hopeless !)");
2191 // Then the only info we have is the net2host one.
2201 * \ingroup gdcmParser
2202 * \brief Restore the unproperly loaded values i.e. the group, the element
2203 * and the dictionary entry depending on them.
2205 void gdcmParser::SwitchSwapToBigEndian(void)
2207 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2208 "Switching to BigEndian mode.");
2229 * \ingroup gdcmParser
2230 * \brief during parsing, Header Elements too long are not loaded in memory
2233 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2237 if ((guint32)NewSize >= (guint32)0xffffffff)
2239 MaxSizeLoadEntry = 0xffffffff;
2242 MaxSizeLoadEntry = NewSize;
2247 * \ingroup gdcmParser
2248 * \brief Header Elements too long will not be printed
2250 * \todo : not yet usable
2251 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2252 * in gdcmHeaderEntry gdcmLoadEntry)
2256 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2260 if ((guint32)NewSize >= (guint32)0xffffffff)
2262 MaxSizePrintEntry = 0xffffffff;
2265 MaxSizePrintEntry = NewSize;
2269 * \ingroup gdcmParser
2270 * \brief Searches both the public and the shadow dictionary (when they
2271 * exist) for the presence of the DictEntry with given name.
2272 * The public dictionary has precedence on the shadow one.
2273 * @param Name name of the searched DictEntry
2274 * @return Corresponding DictEntry when it exists, NULL otherwise.
2276 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2278 gdcmDictEntry *found = (gdcmDictEntry *)0;
2279 if (!RefPubDict && !RefShaDict)
2281 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2282 "we SHOULD have a default dictionary");
2286 found = RefPubDict->GetDictEntryByName(Name);
2292 found = RefShaDict->GetDictEntryByName(Name);
2300 * \ingroup gdcmParser
2301 * \brief Searches both the public and the shadow dictionary (when they
2302 * exist) for the presence of the DictEntry with given
2303 * group and element. The public dictionary has precedence on the
2305 * @param group group of the searched DictEntry
2306 * @param element element of the searched DictEntry
2307 * @return Corresponding DictEntry when it exists, NULL otherwise.
2309 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2311 gdcmDictEntry *found = (gdcmDictEntry *)0;
2312 if (!RefPubDict && !RefShaDict)
2314 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2315 "we SHOULD have a default dictionary");
2319 found = RefPubDict->GetDictEntryByNumber(group, element);
2325 found = RefShaDict->GetDictEntryByNumber(group, element);
2333 * \ingroup gdcmParser
2334 * \brief Read the next tag but WITHOUT loading it's value
2335 * @return On succes the newly created HeaderEntry, NULL on failure.
2337 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2339 gdcmHeaderEntry *NewEntry;
2344 // We reached the EOF (or an error occured) therefore
2345 // header parsing has to be considered as finished.
2346 return (gdcmHeaderEntry *)0;
2348 // Pb : how to propagate the element length (used in SkipHeaderEntry)
2349 // direct call to SkipBytes ?
2351 // if (ignoreShadow == 1 && g%2 ==1)
2352 // if user wants to skip shadow groups
2353 // and current element *is* a shadow element
2354 // we don't create anything
2355 // return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2357 NewEntry = NewHeaderEntryByNumber(g, n);
2358 FindHeaderEntryVR(NewEntry);
2359 FindHeaderEntryLength(NewEntry);
2365 NewEntry->SetOffset(ftell(fp));
2370 * \ingroup gdcmParser
2371 * \brief Build a new Element Value from all the low level arguments.
2372 * Check for existence of dictionary entry, and build
2373 * a default one when absent.
2374 * @param Name Name of the underlying DictEntry
2376 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2378 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2380 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2382 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2385 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2386 "failed to allocate gdcmHeaderEntry");
2387 return (gdcmHeaderEntry *)0;
2393 * \ingroup gdcmParser
2394 * \brief Request a new virtual dict entry to the dict set
2395 * @param group group of the underlying DictEntry
2396 * @param element element of the underlying DictEntry
2397 * @param vr VR of the underlying DictEntry
2398 * @param fourth owner group
2399 * @param name english name
2401 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2406 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2410 * \ingroup gdcmParser
2411 * \brief Build a new Element Value from all the low level arguments.
2412 * Check for existence of dictionary entry, and build
2413 * a default one when absent.
2414 * @param Group group of the underlying DictEntry
2415 * @param Elem element of the underlying DictEntry
2417 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2419 // Find out if the tag we encountered is in the dictionaries:
2420 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2422 DictEntry = NewVirtualDictEntry(Group, Elem);
2424 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2427 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2428 "failed to allocate gdcmHeaderEntry");
2434 // Never used; commented out, waiting for removal.
2436 * \ingroup gdcmParser
2437 * \brief Small utility function that creates a new manually crafted
2438 * (as opposed as read from the file) gdcmHeaderEntry with user
2439 * specified name and adds it to the public tag hash table.
2440 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2441 * @param NewTagName The name to be given to this new tag.
2442 * @param VR The Value Representation to be given to this new tag.
2443 * @return The newly hand crafted Element Value.
2445 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2448 // gdcmHeaderEntry *NewEntry = NULL;
2449 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2450 // guint32 FreeElem = 0;
2451 // gdcmDictEntry *DictEntry = NULL;
2453 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2454 // if (FreeElem == UINT32_MAX)
2456 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2457 // "Group 0xffff in Public Dict is full");
2461 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2462 // VR, "GDCM", NewTagName);
2463 // NewEntry = new gdcmHeaderEntry(DictEntry);
2464 // AddHeaderEntry(NewEntry);
2469 * \ingroup gdcmParser
2470 * \brief Generate a free TagKey i.e. a TagKey that is not present
2471 * in the TagHt dictionary.
2472 * @param group The generated tag must belong to this group.
2473 * @return The element of tag with given group which is fee.
2475 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2477 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2479 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2480 if (tagHT.count(key) == 0)
2486 //-----------------------------------------------------------------------------