2 //-----------------------------------------------------------------------------
3 #include "gdcmParser.h"
12 #include <netinet/in.h>
15 #ifdef GDCM_NO_ANSI_STRING_STREAM
17 # define ostringstream ostrstream
23 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
24 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
25 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
26 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
30 // ---> Warning : This fourth field is NOT part
31 // of the 'official' Dicom Dictionnary
32 // and should NOT be used.
33 // (Not defined for all the groups
34 // may be removed in a future release)
37 // META Meta Information
49 // NMI Nuclear Medicine
51 // BFS Basic Film Session
53 // BIB Basic Image Box
68 // Other usefull abreviations :
69 // Radiographic view associated with Patient Position (0018,5100).
72 // AP = Anterior/Posterior
73 // PA = Posterior/Anterior
76 // RLD = Right Lateral Decubitus
77 // LLD = Left Lateral Decubitus
78 // RLO = Right Lateral Oblique
79 // LLO = Left Lateral Oblique
81 //-----------------------------------------------------------------------------
82 // Refer to gdcmParser::CheckSwap()
83 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
85 // Refer to gdcmParser::SetMaxSizeLoadEntry()
86 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
88 // Refer to gdcmParser::SetMaxSizePrintEntry()
89 // TODO : Right now, better see "define, in gdcmHederEntry.cxx
90 const unsigned int gdcmParser::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
92 //-----------------------------------------------------------------------------
93 // Constructor / Destructor
99 * @param exception_on_error whether we throw an exception or not
100 * @param enable_sequences = true to allow the header
101 * to be parsed *inside* the SeQuences,
102 * when they have an actual length
103 * @param ignore_shadow to allow skipping the shadow elements,
104 * to save memory space.
105 * \warning The TRUE value for this param has to be used
106 * with a FALSE value for the 'enable_sequence' param.
107 * ('public elements' may be embedded in 'shadow Sequences')
109 gdcmParser::gdcmParser(const char *inFilename,
110 bool exception_on_error,
111 bool enable_sequences,
112 bool ignore_shadow) {
113 enableSequences=enable_sequences;
114 ignoreShadow =ignore_shadow;
116 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
117 filename = inFilename;
120 if ( !OpenFile(exception_on_error))
127 wasUpdated = 0; // will be set to 1 if user adds an entry
128 printLevel = 1; // 'Medium' print level by default
132 * \ingroup gdcmParser
134 * @param exception_on_error
136 gdcmParser::gdcmParser(bool exception_on_error) {
139 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
142 wasUpdated = 0; // will be set to 1 if user adds an entry
143 printLevel = 1; // 'Medium' print level by default
147 * \ingroup gdcmParser
148 * \brief Canonical destructor.
150 gdcmParser::~gdcmParser (void) {
155 //-----------------------------------------------------------------------------
158 * \ingroup gdcmParser
159 * \brief Prints the Header Entries (Dicom Elements)
160 * both from the H Table and the chained list
163 void gdcmParser::PrintEntry(std::ostream & os) {
164 std::ostringstream s;
166 for (ListTag::iterator i = listEntries.begin();
167 i != listEntries.end();
170 (*i)->SetPrintLevel(printLevel);
177 * \ingroup gdcmParser
178 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
181 void gdcmParser::PrintPubDict(std::ostream & os) {
182 RefPubDict->Print(os);
186 * \ingroup gdcmParser
187 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnary
190 void gdcmParser::PrintShaDict(std::ostream & os) {
191 RefShaDict->Print(os);
194 //-----------------------------------------------------------------------------
197 * \ingroup gdcmParser
198 * \brief Get the public dictionary used
200 gdcmDict *gdcmParser::GetPubDict(void) {
205 * \ingroup gdcmParser
206 * \brief Get the shadow dictionary used
208 gdcmDict *gdcmParser::GetShaDict(void) {
213 * \ingroup gdcmParser
214 * \brief Set the shadow dictionary used
215 * \param dict dictionary to use in shadow
217 bool gdcmParser::SetShaDict(gdcmDict *dict){
223 * \ingroup gdcmParser
224 * \brief Set the shadow dictionary used
225 * \param dictName name of the dictionary to use in shadow
227 bool gdcmParser::SetShaDict(DictKey dictName){
228 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
233 * \ingroup gdcmParser
234 * \brief This predicate, based on hopefully reasonable heuristics,
235 * decides whether or not the current gdcmParser was properly parsed
236 * and contains the mandatory information for being considered as
237 * a well formed and usable Dicom/Acr File.
238 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
241 bool gdcmParser::IsReadable(void) {
242 if(filetype==Unknown) {
245 if(listEntries.size()<=0) {
253 * \ingroup gdcmParser
254 * \brief Determines if the Transfer Syntax was already encountered
255 * and if it corresponds to a ImplicitVRLittleEndian one.
256 * @return True when ImplicitVRLittleEndian found. False in all other cases.
258 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
259 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
262 LoadHeaderEntrySafe(Element);
264 std::string Transfer = Element->GetValue();
265 if ( Transfer == UI1_2_840_10008_1_2 )
271 * \ingroup gdcmParser
272 * \brief Determines if the Transfer Syntax was already encountered
273 * and if it corresponds to a ExplicitVRLittleEndian one.
274 * @return True when ExplicitVRLittleEndian found. False in all other cases.
276 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
277 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
280 LoadHeaderEntrySafe(Element);
282 std::string Transfer = Element->GetValue();
283 if ( Transfer == UI1_2_840_10008_1_2_1 )
289 * \ingroup gdcmParser
290 * \brief Determines if the Transfer Syntax was already encountered
291 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
292 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
294 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
295 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
298 LoadHeaderEntrySafe(Element);
300 std::string Transfer = Element->GetValue();
301 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
307 * \ingroup gdcmParser
308 * \brief Determines if the Transfer Syntax was already encountered
309 * and if it corresponds to a Explicit VR Big Endian one.
310 * @return True when big endian found. False in all other cases.
312 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
313 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
316 LoadHeaderEntrySafe(Element);
318 std::string Transfer = Element->GetValue();
319 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
325 * \ingroup gdcmParser
326 * \brief returns the File Type
327 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
328 * @return the FileType code
330 FileType gdcmParser::GetFileType(void) {
335 * \ingroup gdcmParser
336 * \brief opens the file
337 * @param exception_on_error
340 FILE *gdcmParser::OpenFile(bool exception_on_error)
343 fp=fopen(filename.c_str(),"rb");
344 if(exception_on_error)
347 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
353 fread(&zero, (size_t)2, (size_t)1, fp);
355 //ACR -- or DICOM with no Preamble --
356 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
360 fseek(fp, 126L, SEEK_CUR);
362 fread(dicm, (size_t)4, (size_t)1, fp);
363 if( memcmp(dicm, "DICM", 4) == 0 )
367 dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
370 dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
376 * \ingroup gdcmParser
377 * \brief closes the file
378 * @return TRUE if the close was successfull
380 bool gdcmParser::CloseFile(void) {
381 int closed = fclose(fp);
389 * \ingroup gdcmParser
390 * \brief writes on disc all the Header Entries (Dicom Elements)
391 * of the Chained List
392 * @param fp file pointer on an already open file
393 * @param type type of the File to be written
394 * (ACR-NEMA, ExplicitVR, ImplicitVR)
395 * @return always "True" ?!
397 bool gdcmParser::Write(FILE *fp, FileType type) {
399 // TODO The stuff was rewritten using the chained list instead
401 // so we could remove the GroupHT from the gdcmParser
405 // TODO : move the following lines (and a lot of others, to be written)
406 // to a future function CheckAndCorrectHeader
409 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
410 // (FileType est un champ de gdcmParser ...)
411 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
413 // a moins de se livrer a un tres complique ajout des champs manquants.
414 // faire un CheckAndCorrectHeader (?)
417 if (type == ImplicitVR)
419 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
420 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
422 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
423 // values with a VR of UI shall be padded with a single trailing null
424 // Dans le cas suivant on doit pader manuellement avec un 0
426 SetEntryLengthByNumber(18, 0x0002, 0x0010);
429 if (type == ExplicitVR)
431 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
432 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
434 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
435 // values with a VR of UI shall be padded with a single trailing null
436 // Dans le cas suivant on doit pader manuellement avec un 0
438 SetEntryLengthByNumber(20, 0x0002, 0x0010);
441 /* TODO : rewrite later, if really usefull
443 if ( (type == ImplicitVR) || (type == ExplicitVR) )
444 UpdateGroupLength(false,type);
446 UpdateGroupLength(true,ACR);
449 WriteEntries(fp,type);
454 * \ingroup gdcmParser
455 * \brief Modifies the value of a given Header Entry (Dicom Element)
456 * if it exists; Creates it with the given value if it doesn't
457 * \warning : adds the Header Entry to the HTable, NOT to the chained List
458 * @param Value passed as a std::string
459 * @param Group group of the Entry
460 * @param Elem element of the Entry
461 * \return pointer to the created Header Entry
462 * NULL if creation failed
464 gdcmHeaderEntry * gdcmParser::ReplaceOrCreateByNumber(
469 a = GetHeaderEntryByNumber( Group, Elem);
471 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
476 //SetEntryByNumber(Value, Group, Elem);
482 * \ingroup gdcmParser
483 * \brief Modifies the value of a given Header Entry (Dicom Element)
484 * if it exists; Creates it with the given value if it doesn't
485 * @param Value passed as a char*
486 * @param Group group of the Entry
487 * @param Elem element of the Entry
488 * \return pointer to the created Header Entry
489 * NULL if creation failed
492 gdcmHeaderEntry * gdcmParser::ReplaceOrCreateByNumber(
496 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
501 AddHeaderEntry(nvHeaderEntry);
503 std::string v = Value;
504 SetEntryByNumber(v, Group, Elem);
505 return(nvHeaderEntry);
509 * \ingroup gdcmParser
510 * \brief Set a new value if the invoked element exists
511 * Seems to be useless !!!
512 * @param Value new element value
513 * @param Group group of the Entry
514 * @param Elem element of the Entry
517 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
519 std::string v = Value;
520 SetEntryByNumber(v, Group, Elem);
524 //-----------------------------------------------------------------------------
528 * \ingroup gdcmParser
529 * \brief Checks if a given Dicom Element exists
531 * @param group Group number of the searched Dicom Element
532 * @param element Element number of the searched Dicom Element
533 * @return number of occurences
535 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
536 std::string key = gdcmDictEntry::TranslateToKey(group, element );
537 return (tagHT.count(key));
541 * \ingroup gdcmParser
542 * \brief Searches within Header Entries (Dicom Elements) parsed with
543 * the public and private dictionaries
544 * for the element value of a given tag.
545 * \warning Don't use any longer : use GetPubEntryByName
546 * @param tagName name of the searched element.
547 * @return Corresponding element value when it exists,
548 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
550 std::string gdcmParser::GetEntryByName(std::string tagName) {
551 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
552 if( dictEntry == NULL)
555 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
559 * \ingroup gdcmParser
560 * \brief Searches within Header Entries (Dicom Elements) parsed with
561 * the public and private dictionaries
562 * for the element value representation of a given tag.
564 * Obtaining the VR (Value Representation) might be needed by caller
565 * to convert the string typed content to caller's native type
566 * (think of C++ vs Python). The VR is actually of a higher level
567 * of semantics than just the native C++ type.
568 * @param tagName name of the searched element.
569 * @return Corresponding element value representation when it exists,
570 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
572 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
573 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
574 if( dictEntry == NULL)
577 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
578 dictEntry->GetElement());
579 return elem->GetVR();
584 * \ingroup gdcmParser
585 * \brief Searches within Header Entries (Dicom Elements) parsed with
586 * the public and private dictionaries
587 * for the element value representation of a given tag.
588 * @param group Group of the searched tag.
589 * @param element Element of the searched tag.
590 * @return Corresponding element value representation when it exists,
591 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
593 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
594 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
595 if ( ! tagHT.count(key))
597 return tagHT.find(key)->second->GetValue();
601 * \ingroup gdcmParser
602 * \brief Searches within Header Entries (Dicom Elements) parsed with
603 * the public and private dictionaries
604 * for the element value representation of a given tag..
606 * Obtaining the VR (Value Representation) might be needed by caller
607 * to convert the string typed content to caller's native type
608 * (think of C++ vs Python). The VR is actually of a higher level
609 * of semantics than just the native C++ type.
610 * @param group Group of the searched tag.
611 * @param element Element of the searched tag.
612 * @return Corresponding element value representation when it exists,
613 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
615 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
616 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
619 return elem->GetVR();
623 * \ingroup gdcmParser
624 * \brief Searches within Header Entries (Dicom Elements) parsed with
625 * the public and private dictionaries
626 * for the value length of a given tag..
627 * @param group Group of the searched tag.
628 * @param element Element of the searched tag.
629 * @return Corresponding element length; -2 if not found
631 int gdcmParser::GetEntryLengthByNumber(guint16 group, guint16 element) {
632 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
635 return elem->GetLength();
638 * \ingroup gdcmParser
639 * \brief Sets the value (string) of the Header Entry (Dicom Element)
640 * @param content string value of the Dicom Element
641 * @param tagName name of the searched Dicom Element.
642 * @return true when found
644 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
645 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
646 if( dictEntry == NULL)
649 return(SetEntryByNumber(content,dictEntry->GetGroup(),
650 dictEntry->GetElement()));
654 * \ingroup gdcmParser
655 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
656 * through it's (group, element) and modifies it's content with
658 * \warning Don't use any longer : use SetPubEntryByNumber
659 * @param content new value to substitute with
660 * @param group group of the Dicom Element to modify
661 * @param element element of the Dicom Element to modify
663 bool gdcmParser::SetEntryByNumber(std::string content,
667 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
668 if ( ! tagHT.count(key))
670 int l = content.length();
671 if(l%2) // Non even length are padded with a space (020H).
674 content = content + '\0';
679 TagHeaderEntryHT::iterator p2;
680 // DO NOT remove the following lines : they explain the stuff
681 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
682 //p2=p.first; // iterator on the first synonym
683 //a=p2->second; // H Table target column (2-nd col)
686 a = ((tagHT.equal_range(key)).first)->second;
688 a-> SetValue(content);
690 std::string vr = a->GetVR();
693 if( (vr == "US") || (vr == "SS") )
695 else if( (vr == "UL") || (vr == "SL") )
705 * \ingroup gdcmParser
706 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
707 * in the PubHeaderEntrySet of this instance
708 * through it's (group, element) and modifies it's length with
710 * \warning Use with extreme caution.
711 * @param l new length to substitute with
712 * @param group group of the Entry to modify
713 * @param element element of the Entry to modify
714 * @return true on success, false otherwise.
716 bool gdcmParser::SetEntryLengthByNumber(guint32 l,
720 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
721 if ( ! tagHT.count(key))
723 if (l%2) l++; // length must be even
724 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
730 * \ingroup gdcmParser
731 * \brief Gets (from Header) the offset of a 'non string' element value
732 * (LoadElementValues has already be executed)
733 * @param Group group of the Entry
734 * @param Elem element of the Entry
735 * @return File Offset of the Element Value
737 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
739 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
742 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
743 "failed to Locate gdcmHeaderEntry");
746 return Entry->GetOffset();
750 * \ingroup gdcmParser
751 * \brief Gets (from Header) a 'non string' element value
752 * (LoadElementValues has already be executed)
753 * @param Group group of the Entry
754 * @param Elem element of the Entry
755 * @return Pointer to the 'non string' area
757 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
759 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
762 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
763 "failed to Locate gdcmHeaderEntry");
766 return Entry->GetVoidArea();
770 * \ingroup gdcmParser
771 * \brief Loads (from disk) the element content
772 * when a string is not suitable
773 * @param Group group of the Entry
774 * @param Elem element of the Entry
776 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
778 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
781 size_t o =(size_t)Element->GetOffset();
782 fseek(fp, o, SEEK_SET);
783 int l=Element->GetLength();
784 void * a = malloc(l);
788 SetEntryVoidAreaByNumber(a, Group, Elem);
789 // TODO check the result
790 size_t l2 = fread(a, 1, l ,fp);
801 * \ingroup gdcmParser
802 * \brief Sets a 'non string' value to a given Dicom Element
804 * @param group Group number of the searched Dicom Element
805 * @param element Element number of the searched Dicom Element
808 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
812 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
813 if ( ! tagHT.count(key))
815 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
820 * \ingroup gdcmParser
821 * \brief Update the entries with the shadow dictionary.
822 * Only non even entries are analyzed
824 void gdcmParser::UpdateShaEntries(void) {
825 gdcmDictEntry *entry;
828 for(ListTag::iterator it=listEntries.begin();
829 it!=listEntries.end();
832 // Odd group => from public dictionary
833 if((*it)->GetGroup()%2==0)
836 // Peer group => search the corresponding dict entry
838 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
842 if((*it)->IsImplicitVR())
847 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
849 // Set the new entry and the new value
850 (*it)->SetDictEntry(entry);
851 CheckHeaderEntryVR(*it,vr);
853 (*it)->SetValue(GetHeaderEntryValue(*it));
857 // Remove precedent value transformation
858 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
864 * \ingroup gdcmParser
865 * \brief Searches within the Header Entries for a Dicom Element of
867 * @param tagName name of the searched Dicom Element.
868 * @return Corresponding Dicom Element when it exists, and NULL
871 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
872 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
873 if( dictEntry == NULL)
876 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
880 * \ingroup gdcmParser
881 * \brief retrieves a Dicom Element (the first one) using (group, element)
882 * \warning (group, element) IS NOT an identifier inside the Dicom Header
883 * if you think it's NOT UNIQUE, check the count number
884 * and use iterators to retrieve ALL the Dicoms Elements within
885 * a given couple (group, element)
886 * @param group Group number of the searched Dicom Element
887 * @param element Element number of the searched Dicom Element
890 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
892 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
893 if ( ! tagHT.count(key))
895 return tagHT.find(key)->second;
899 * \ingroup gdcmParser
900 * \brief retrieves the Dicom Elements (all of them) using (group, element)
901 * @param group Group number of the searched Dicom Element.
902 * @param element Element number of the searched Dicom Element.
903 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
906 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
907 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
908 return (tagHT.equal_range(key));
912 * \ingroup gdcmParser
913 * \brief Loads the element while preserving the current
914 * underlying file position indicator as opposed to
915 * to LoadHeaderEntry that modifies it.
916 * @param entry Header Entry whose value shall be loaded.
919 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
920 long PositionOnEntry = ftell(fp);
921 LoadHeaderEntry(entry);
922 fseek(fp, PositionOnEntry, SEEK_SET);
926 * \ingroup gdcmParser
927 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
928 * \warning : to be re-written using the chained list instead of the H table.
929 * \warning : DO NOT use (doesn't work any longer because of the multimap)
930 * \todo : to be re-written using the chained list instead of the H table
931 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
932 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
934 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
938 gdcmHeaderEntry *elem;
940 std::string str_trash;
943 GroupHT groupHt; // to hold the length of each group
946 // typedef std::map<GroupKey, int> GroupHT;
948 gdcmHeaderEntry *elemZ;
950 // for each Tag in the DCM Header
952 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
957 gr = elem->GetGroup();
958 el = elem->GetElement();
961 sprintf(trash, "%04x", gr);
962 key = trash; // generate 'group tag'
964 // if the caller decided not to take SEQUENCEs into account
965 // e.g : he wants to write an ACR-NEMA File
967 if (SkipSequence && vr == "SQ")
970 // Still unsolved problem :
971 // we cannot find the 'Sequence Delimitation Item'
972 // since it's at the end of the Hash Table
975 // pas SEQUENCE en ACR-NEMA
977 // --> la descente a l'interieur' des SQ
978 // devrait etre faite avec une liste chainee, pas avec une HTable...
980 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
982 if (el == 0x0000) // the first elem is 0x0000
984 groupHt[key] = 0; // initialize group length
988 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
991 else // any elem but the first
993 if (type == ExplicitVR)
995 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
997 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
1000 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
1004 unsigned short int gr_bid;
1006 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
1010 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
1011 // warning: unsigned int format, different type arg
1012 sscanf(g->first.c_str(),"%x",&gr_bid);
1013 tk = g->first + "|0000"; // generate the element full tag
1015 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
1017 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
1018 elemZ = new gdcmHeaderEntry(tagZ);
1019 elemZ->SetLength(4);
1020 AddHeaderEntry(elemZ); // create it
1024 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
1026 sprintf(trash ,"%d",g->second);
1028 elemZ->SetValue(str_trash);
1033 * \ingroup gdcmParser
1034 * \brief writes on disc according to the requested format
1035 * (ACR-NEMA, ExplicitVR, ImplicitVR) ONE
1037 * @param tag pointer on the gdcmHeaderEntry to be written
1038 * @param type type of the File to be written
1039 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1040 * @param _fp already open file pointer
1042 void gdcmParser::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1053 std::vector<std::string> tokens;
1057 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1059 itsTimeToWritePixels = false;
1061 gr = tag->GetGroup();
1062 el = tag->GetElement();
1063 lgr = tag->GetReadLength();
1064 val = tag->GetValue().c_str();
1066 voidArea = tag->GetVoidArea();
1068 // === Deal with the length
1069 // --------------------
1070 if((tag->GetLength())%2==1)
1072 tag->SetValue(tag->GetValue()+"\0");
1073 tag->SetLength(tag->GetReadLength()+1);
1078 if (gr < 0x0008) return; // ignore pure DICOM V3 groups
1079 if (gr %2) return; // ignore shadow groups
1080 if (vr == "SQ" ) return; // ignore Sequences
1081 // TODO : find a trick to *skip* the SeQuences !
1082 // Not only ignore the SQ element
1083 if (gr == 0xfffe ) return; // ignore delimiters
1086 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1087 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1089 if ( (type == ExplicitVR) || (type == DICOMDIR) ) {
1091 guint16 z=0, shortLgr;
1093 if (gr == 0xfffe) { // NO Value Representation for 'delimiters'
1094 // no length : write ffffffff
1096 // special patch to make some MR PHILIPS
1097 if (el == 0x0000) return; // images e-film readable // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1098 // from Hospital Guy de Chauliac,
1100 // we just ignore spurious fffe|0000 tag !
1102 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1103 return; // NO value for 'delimiters'
1107 if (vr == "unkn") { // Unknown was 'written'
1108 // deal with Little Endian
1109 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1110 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1112 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1113 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ){
1114 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1115 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1117 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1123 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1126 // === Deal with the value
1127 // -------------------
1128 if (vr == "SQ") return; // no "value" to write for the SEQuences
1129 if (gr == 0xfffe)return; // no "value" to write for the delimiters
1131 if (voidArea != NULL)
1132 { // there is a 'non string' LUT, overlay, etc
1133 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1137 if (vr == "US" || vr == "SS")
1139 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1140 Tokenize (tag->GetValue(), tokens, "\\");
1141 for (unsigned int i=0; i<tokens.size();i++)
1143 val_uint16 = atoi(tokens[i].c_str());
1145 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1150 if (vr == "UL" || vr == "SL")
1152 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1153 Tokenize (tag->GetValue(), tokens, "\\");
1154 for (unsigned int i=0; i<tokens.size();i++)
1156 val_uint32 = atoi(tokens[i].c_str());
1158 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1164 // Pixels are never loaded in the element !
1165 // we stop writting when Pixel are processed
1166 // FIX : we loose trailing elements (RAB, right now)
1168 if ((gr == GrPixel) && (el == NumPixel) ) {
1170 if (compte == countGrPixel) {// we passed *all* the GrPixel,NumPixel
1171 itsTimeToWritePixels = true;
1175 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1179 * \ingroup gdcmParser
1180 * \brief writes on disc according to the requested format
1181 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1182 * using the Chained List
1183 * \warning does NOT add the missing elements in the header :
1184 * it's up to the user doing it !
1185 * (function CheckHeaderCoherence to be written)
1186 * \warning DON'T try, right now, to write a DICOM image
1187 * from an ACR Header (meta elements will be missing!)
1188 * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1189 * @param type type of the File to be written
1190 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1191 * @param _fp already open file pointer
1194 void gdcmParser::WriteEntries(FILE *_fp,FileType type)
1196 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1198 for (ListTag::iterator tag2=listEntries.begin();
1199 tag2 != listEntries.end();
1202 WriteEntry(*tag2,_fp,type);
1203 if (itsTimeToWritePixels)
1209 * \ingroup gdcmParser
1210 * \brief writes on disc according to the requested format
1211 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1212 * using only the last synonym of each mutimap H Table post.
1213 * \warning Uses the H Table, instead of the Chained List
1214 * in order to be compliant with the old way to proceed
1215 * (added elements taken in to account)
1216 * Only THERALYS, during a transitory phase is supposed
1217 * to use this method !!!
1218 * \warning DON'T try, right now, to write a DICOM image
1219 * from an ACR Header (meta elements will be missing!)
1221 * @param _fp already open file pointer
1222 * @param type type of the File to be written
1223 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1225 void gdcmParser::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1227 // restent a tester les echecs en ecriture (apres chaque fwrite)
1229 for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1230 tag2 != tagHT.end();
1232 WriteEntry(tag2->second,_fp,type);
1233 if (itsTimeToWritePixels)
1239 * \ingroup gdcmParser
1240 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1242 * @return The properly swaped 32 bits integer.
1244 guint32 gdcmParser::SwapLong(guint32 a) {
1249 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1250 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1254 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1258 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1261 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1268 * \ingroup gdcmParser
1269 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1271 * @return The properly unswaped 32 bits integer.
1273 guint32 gdcmParser::UnswapLong(guint32 a) {
1274 return (SwapLong(a));
1278 * \ingroup gdcmParser
1279 * \brief Swaps the bytes so they agree with the processor order
1280 * @return The properly swaped 16 bits integer.
1282 guint16 gdcmParser::SwapShort(guint16 a) {
1283 if ( (sw==4321) || (sw==2143) )
1284 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1289 * \ingroup gdcmParser
1290 * \brief Unswaps the bytes so they agree with the processor order
1291 * @return The properly unswaped 16 bits integer.
1293 guint16 gdcmParser::UnswapShort(guint16 a) {
1294 return (SwapShort(a));
1297 //-----------------------------------------------------------------------------
1300 * \ingroup gdcmParser
1301 * \brief Parses the header of the file but WITHOUT loading element values.
1302 * @return false if file is not ACR-NEMA / DICOM
1304 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1310 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1311 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1312 SkipHeaderEntry(newHeaderEntry);
1313 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1314 AddHeaderEntry(newHeaderEntry);
1321 * \ingroup gdcmParser
1322 * \brief Loads the element values of all the Header Entries pointed in the
1323 * public Chained List.
1325 void gdcmParser::LoadHeaderEntries(void) {
1327 for (ListTag::iterator i = GetListEntry().begin();
1328 i != GetListEntry().end();
1331 LoadHeaderEntry(*i);
1336 // Load 'non string' values
1337 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1338 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1339 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1340 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1341 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1342 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1344 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1345 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1346 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1348 //FIXME : how to use it?
1349 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1351 // --------------------------------------------------------------
1352 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1354 // if recognition code tells us we deal with a LibIDO image
1355 // we switch lineNumber and columnNumber
1357 std::string RecCode;
1358 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1359 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1360 RecCode == "CANRME_AILIBOD1_1." )
1362 filetype = ACR_LIBIDO;
1363 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1364 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1365 SetEntryByNumber(columns, 0x0028, 0x0010);
1366 SetEntryByNumber(rows , 0x0028, 0x0011);
1368 // ----------------- End of Special Patch ----------------
1372 * \ingroup gdcmParser
1373 * \brief Loads the element content if its length doesn't exceed
1374 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1375 * @param Entry Header Entry (Dicom Element) to be dealt with
1377 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1379 guint16 group = Entry->GetGroup();
1380 std::string vr= Entry->GetVR();
1381 guint32 length = Entry->GetLength();
1382 bool SkipLoad = false;
1384 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1386 // the test was commented out to 'go inside' the SeQuences
1387 // we don't any longer skip them !
1389 // if( vr == "SQ" ) // (DO NOT remove this comment)
1392 // A SeQuence "contains" a set of Elements.
1393 // (fffe e000) tells us an Element is beginning
1394 // (fffe e00d) tells us an Element just ended
1395 // (fffe e0dd) tells us the current SeQuence just ended
1396 if( group == 0xfffe )
1400 Entry->SetLength(0);
1401 Entry->SetValue("gdcm::Skipped");
1405 // When the length is zero things are easy:
1406 if ( length == 0 ) {
1407 Entry->SetValue("");
1411 // The elements whose length is bigger than the specified upper bound
1412 // are not loaded. Instead we leave a short notice of the offset of
1413 // the element content and it's length.
1414 if (length > MaxSizeLoadEntry) {
1415 std::ostringstream s;
1416 s << "gdcm::NotLoaded.";
1417 s << " Address:" << (long)Entry->GetOffset();
1418 s << " Length:" << Entry->GetLength();
1419 s << " x(" << std::hex << Entry->GetLength() << ")";
1420 Entry->SetValue(s.str());
1424 // When integer(s) are expected, read and convert the following
1425 // n *(two or four bytes)
1426 // properly i.e. as integers as opposed to strings.
1427 // Elements with Value Multiplicity > 1
1428 // contain a set of integers (not a single one)
1430 // Any compacter code suggested (?)
1431 if ( IsHeaderEntryAnInteger(Entry) ) {
1433 std::ostringstream s;
1435 if (vr == "US" || vr == "SS") {
1437 NewInt = ReadInt16();
1440 for (int i=1; i < nbInt; i++) {
1442 NewInt = ReadInt16();
1447 else if (vr == "UL" || vr == "SL") {
1449 NewInt = ReadInt32();
1452 for (int i=1; i < nbInt; i++) {
1454 NewInt = ReadInt32();
1459 #ifdef GDCM_NO_ANSI_STRING_STREAM
1460 s << std::ends; // to avoid oddities on Solaris
1461 #endif //GDCM_NO_ANSI_STRING_STREAM
1463 Entry->SetValue(s.str());
1467 // We need an additional byte for storing \0 that is not on disk
1468 std::string NewValue(length,0);
1469 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1470 if ( item_read != 1 ) {
1471 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1472 Entry->SetValue("gdcm::UnRead");
1476 if( (vr == "UI") ) // Because of correspondance with the VR dic
1477 Entry->SetValue(NewValue.c_str());
1479 Entry->SetValue(NewValue);
1483 * \ingroup gdcmParser
1484 * \brief add a new Dicom Element pointer to
1485 * the H Table and at the end of the chained List
1486 * \warning push_bash in listEntries ONLY during ParseHeader
1487 * \todo something to allow further Elements addition,
1488 * (at their right place in the chained list)
1489 * when position to be taken care of
1490 * @param newHeaderEntry
1492 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1493 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1494 listEntries.push_back(newHeaderEntry);
1499 * \ingroup gdcmParser
1500 * \brief Find the value Length of the passed Header Entry
1501 * @param Entry Header Entry whose length of the value shall be loaded.
1503 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1504 guint16 element = Entry->GetElement();
1505 guint16 group = Entry->GetGroup();
1506 std::string vr = Entry->GetVR();
1509 if( (element == NumPixel) && (group == GrPixel) )
1511 dbg.SetDebug(GDCM_DEBUG);
1512 dbg.Verbose(2, "gdcmParser::FindLength: ",
1513 "we reached (GrPixel,NumPixel)");
1516 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1518 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1520 // The following reserved two bytes (see PS 3.5-2001, section
1521 // 7.1.2 Data element structure with explicit vr p27) must be
1522 // skipped before proceeding on reading the length on 4 bytes.
1523 fseek(fp, 2L, SEEK_CUR);
1524 guint32 length32 = ReadInt32();
1526 if ( (vr == "OB") && (length32 == 0xffffffff) )
1528 Entry->SetLength(FindHeaderEntryLengthOB());
1531 FixHeaderEntryFoundLength(Entry, length32);
1535 // Length is encoded on 2 bytes.
1536 length16 = ReadInt16();
1538 // We can tell the current file is encoded in big endian (like
1539 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1540 // and it's value is the one of the encoding of a big endian file.
1541 // In order to deal with such big endian encoded files, we have
1542 // (at least) two strategies:
1543 // * when we load the "Transfer Syntax" tag with value of big endian
1544 // encoding, we raise the proper flags. Then we wait for the end
1545 // of the META group (0x0002) among which is "Transfer Syntax",
1546 // before switching the swap code to big endian. We have to postpone
1547 // the switching of the swap code since the META group is fully encoded
1548 // in little endian, and big endian coding only starts at the next
1549 // group. The corresponding code can be hard to analyse and adds
1550 // many additional unnecessary tests for regular tags.
1551 // * the second strategy consists in waiting for trouble, that shall
1552 // appear when we find the first group with big endian encoding. This
1553 // is easy to detect since the length of a "Group Length" tag (the
1554 // ones with zero as element number) has to be of 4 (0x0004). When we
1555 // encounter 1024 (0x0400) chances are the encoding changed and we
1556 // found a group with big endian encoding.
1557 // We shall use this second strategy. In order to make sure that we
1558 // can interpret the presence of an apparently big endian encoded
1559 // length of a "Group Length" without committing a big mistake, we
1560 // add an additional check: we look in the already parsed elements
1561 // for the presence of a "Transfer Syntax" whose value has to be "big
1562 // endian encoding". When this is the case, chances are we have got our
1563 // hands on a big endian encoded file: we switch the swap code to
1564 // big endian and proceed...
1565 if ( (element == 0x0000) && (length16 == 0x0400) )
1567 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1569 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1574 SwitchSwapToBigEndian();
1575 // Restore the unproperly loaded values i.e. the group, the element
1576 // and the dictionary entry depending on them.
1577 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1578 guint16 CorrectElem = SwapShort(Entry->GetElement());
1579 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1583 // This correct tag is not in the dictionary. Create a new one.
1584 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1586 // FIXME this can create a memory leaks on the old entry that be
1587 // left unreferenced.
1588 Entry->SetDictEntry(NewTag);
1591 // Heuristic: well some files are really ill-formed.
1592 if ( length16 == 0xffff)
1595 //dbg.Verbose(0, "gdcmParser::FindLength",
1596 // "Erroneous element length fixed.");
1597 // Actually, length= 0xffff means that we deal with
1598 // Unknown Sequence Length
1600 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1605 // Either implicit VR or a non DICOM conformal (see note below) explicit
1606 // VR that ommited the VR of (at least) this element. Farts happen.
1607 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1608 // on Data elements "Implicit and Explicit VR Data Elements shall
1609 // not coexist in a Data Set and Data Sets nested within it".]
1610 // Length is on 4 bytes.
1612 FixHeaderEntryFoundLength(Entry, ReadInt32());
1618 * \ingroup gdcmParser
1619 * \brief Find the Value Representation of the current Dicom Element.
1622 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1624 if (filetype != ExplicitVR)
1629 long PositionOnEntry = ftell(fp);
1630 // Warning: we believe this is explicit VR (Value Representation) because
1631 // we used a heuristic that found "UL" in the first tag. Alas this
1632 // doesn't guarantee that all the tags will be in explicit VR. In some
1633 // cases (see e-film filtered files) one finds implicit VR tags mixed
1634 // within an explicit VR file. Hence we make sure the present tag
1635 // is in explicit VR and try to fix things if it happens not to be
1638 int lgrLue=fread (&VR, (size_t)2,(size_t)1, fp); // lgrLue not used
1640 if(!CheckHeaderEntryVR(Entry,VR))
1642 fseek(fp, PositionOnEntry, SEEK_SET);
1643 // When this element is known in the dictionary we shall use, e.g. for
1644 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1645 // dictionary entry. Still we have to flag the element as implicit since
1646 // we know now our assumption on expliciteness is not furfilled.
1648 if ( Entry->IsVRUnknown() )
1649 Entry->SetVR("Implicit");
1650 Entry->SetImplicitVR();
1655 * \ingroup gdcmParser
1656 * \brief Check the correspondance between the VR of the header entry
1657 * and the taken VR. If they are different, the header entry is
1658 * updated with the new VR.
1659 * @param Entry Header Entry to check
1660 * @param vr Dicom Value Representation
1661 * @return false if the VR is incorrect of if the VR isn't referenced
1662 * otherwise, it returns true
1664 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1666 char msg[100]; // for sprintf
1667 bool RealExplicit = true;
1669 // Assume we are reading a falsely explicit VR file i.e. we reached
1670 // a tag where we expect reading a VR but are in fact we read the
1671 // first to bytes of the length. Then we will interogate (through find)
1672 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1673 // both GCC and VC++ implementations of the STL map. Hence when the
1674 // expected VR read happens to be non-ascii characters we consider
1675 // we hit falsely explicit VR tag.
1677 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1678 RealExplicit = false;
1680 // CLEANME searching the dicom_vr at each occurence is expensive.
1681 // PostPone this test in an optional integrity check at the end
1682 // of parsing or only in debug mode.
1683 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1684 RealExplicit= false;
1686 if ( !RealExplicit )
1688 // We thought this was explicit VR, but we end up with an
1689 // implicit VR tag. Let's backtrack.
1690 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1691 Entry->GetGroup(),Entry->GetElement());
1692 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1693 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1694 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1695 Entry->GetGroup(),Entry->GetElement(),
1696 "UL","FIXME","Group Length");
1697 Entry->SetDictEntry(NewEntry);
1702 if ( Entry->IsVRUnknown() )
1704 // When not a dictionary entry, we can safely overwrite the VR.
1705 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1711 else if ( Entry->GetVR() != vr )
1713 // The VR present in the file and the dictionary disagree. We assume
1714 // the file writer knew best and use the VR of the file. Since it would
1715 // be unwise to overwrite the VR of a dictionary (since it would
1716 // compromise it's next user), we need to clone the actual DictEntry
1717 // and change the VR for the read one.
1718 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1719 Entry->GetGroup(),Entry->GetElement(),
1720 vr,"FIXME",Entry->GetName());
1721 Entry->SetDictEntry(NewEntry);
1727 * \ingroup gdcmParser
1728 * \brief Get the transformed value of the header entry. The VR value
1729 * is used to define the transformation to operate on the value
1730 * \warning NOT end user intended method !
1732 * @return Transformed entry value
1734 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1736 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1738 std::string val=Entry->GetValue();
1739 std::string vr=Entry->GetVR();
1740 guint32 length = Entry->GetLength();
1741 std::ostringstream s;
1744 if (vr == "US" || vr == "SS")
1749 for (int i=0; i < nbInt; i++)
1753 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1754 NewInt16 = SwapShort(NewInt16);
1759 else if (vr == "UL" || vr == "SL")
1764 for (int i=0; i < nbInt; i++)
1768 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1769 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1770 NewInt32=SwapLong(NewInt32);
1774 #ifdef GDCM_NO_ANSI_STRING_STREAM
1775 s << std::ends; // to avoid oddities on Solaris
1776 #endif //GDCM_NO_ANSI_STRING_STREAM
1780 return(Entry->GetValue());
1784 * \ingroup gdcmParser
1785 * \brief Get the reverse transformed value of the header entry. The VR
1786 * value is used to define the reverse transformation to operate on
1788 * \warning NOT end user intended method !
1790 * @return Reverse transformed entry value
1792 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1794 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1796 std::string vr=Entry->GetVR();
1797 std::ostringstream s;
1798 std::vector<std::string> tokens;
1800 if (vr == "US" || vr == "SS")
1804 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1805 Tokenize (Entry->GetValue(), tokens, "\\");
1806 for (unsigned int i=0; i<tokens.size();i++)
1808 NewInt16 = atoi(tokens[i].c_str());
1809 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1813 if (vr == "UL" || vr == "SL")
1817 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1818 Tokenize (Entry->GetValue(), tokens, "\\");
1819 for (unsigned int i=0; i<tokens.size();i++)
1821 NewInt32 = atoi(tokens[i].c_str());
1822 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1823 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1828 #ifdef GDCM_NO_ANSI_STRING_STREAM
1829 s << std::ends; // to avoid oddities on Solaris
1830 #endif //GDCM_NO_ANSI_STRING_STREAM
1834 return(Entry->GetValue());
1838 * \ingroup gdcmParser
1839 * \brief Skip a given Header Entry
1840 * \warning NOT end user intended method !
1843 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1845 SkipBytes(entry->GetLength());
1849 * \ingroup gdcmParser
1850 * \brief When the length of an element value is obviously wrong (because
1851 * the parser went Jabberwocky) one can hope improving things by
1852 * applying this heuristic.
1854 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1856 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1858 if ( FoundLength == 0xffffffff) {
1862 guint16 gr =Entry->GetGroup();
1863 guint16 el =Entry->GetElement();
1865 if (FoundLength%2) {
1866 std::ostringstream s;
1867 s << "Warning : Tag with uneven length " << FoundLength
1868 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1869 dbg.Verbose(0,s.str().c_str());
1872 // Sorry for the patch!
1873 // XMedCom did the trick to read some nasty GE images ...
1874 if (FoundLength == 13) {
1875 // The following 'if' will be removed when there is no more
1876 // images on Creatis HDs with a 13 length for Manufacturer...
1877 if ( (Entry->GetGroup() != 0x0008) ||
1878 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1879 // end of remove area
1881 Entry->SetReadLength(10); // a bug is to be fixed
1885 // to fix some garbage 'Leonardo' Siemens images
1886 // May be commented out to avoid overhead
1887 else if ( (Entry->GetGroup() == 0x0009) &&
1888 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1890 Entry->SetReadLength(4); // a bug is to be fixed
1894 // to try to 'go inside' SeQuences (with length), and not to skip them
1895 else if ( Entry->GetVR() == "SQ")
1897 if (enableSequences) // only if the user does want to !
1898 FoundLength =0; // ReadLength is unchanged
1901 // a SeQuence Element is beginning
1902 // fffe|e000 is just a marker, its length *should be* zero
1903 else if(Entry->GetGroup() == 0xfffe)
1905 // *normally, fffe|0000 doesn't exist !
1906 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1907 // causes extra troubles :-(
1910 Entry->SetUsableLength(FoundLength);
1914 * \ingroup gdcmParser
1915 * \brief Apply some heuristics to predict whether the considered
1916 * element value contains/represents an integer or not.
1917 * @param Entry The element value on which to apply the predicate.
1918 * @return The result of the heuristical predicate.
1920 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1921 guint16 element = Entry->GetElement();
1922 guint16 group = Entry->GetGroup();
1923 std::string vr = Entry->GetVR();
1924 guint32 length = Entry->GetLength();
1925 // When we have some semantics on the element we just read, and if we
1926 // a priori know we are dealing with an integer, then we shall be
1927 // able to swap it's element value properly.
1928 if ( element == 0 ) // This is the group length of the group
1934 std::ostringstream s;
1935 int filePosition = ftell(fp);
1936 s << "Erroneous Group Length element length on : (" \
1937 << std::hex << group << " , " << element
1938 << ") -before- position x(" << filePosition << ")"
1939 << "lgt : " << length;
1940 // These 2 lines commented out : a *very dirty* patch
1941 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1942 // have a glance at offset x(8336) ...
1943 // For *regular* headers, the test is useless..
1944 // lets's print a warning message and go on,
1945 // instead of giving up with an error message
1947 //std::cout << s.str().c_str() << std::endl;
1949 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1950 // s.str().c_str());
1953 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1959 * \ingroup gdcmParser
1960 * \brief Find the Length till the next sequence delimiter
1961 * \warning NOT end user intended method !
1965 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1966 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1969 long PositionOnEntry = ftell(fp);
1970 bool FoundSequenceDelimiter = false;
1971 guint32 TotalLength = 0;
1974 while ( ! FoundSequenceDelimiter)
1980 TotalLength += 4; // We even have to decount the group and element
1982 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1984 char msg[100]; // for sprintf. Sorry
1985 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1986 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1990 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1991 FoundSequenceDelimiter = true;
1992 else if ( n != 0xe000 )
1994 char msg[100]; // for sprintf. Sorry
1995 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1997 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
2001 ItemLength = ReadInt32();
2002 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2003 // the ItemLength with ReadInt32
2004 SkipBytes(ItemLength);
2006 fseek(fp, PositionOnEntry, SEEK_SET);
2011 * \ingroup gdcmParser
2012 * \brief Reads a supposed to be 16 Bits integer
2013 * (swaps it depending on processor endianity)
2014 * @return read value
2016 guint16 gdcmParser::ReadInt16(void) {
2019 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2020 if ( item_read != 1 ) {
2022 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
2032 * \ingroup gdcmParser
2033 * \brief Reads a supposed to be 32 Bits integer
2034 * (swaps it depending on processor endianity)
2035 * @return read value
2037 guint32 gdcmParser::ReadInt32(void) {
2040 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2041 if ( item_read != 1 ) {
2043 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
2053 * \ingroup gdcmParser
2054 * \brief skips bytes inside the source file
2055 * \warning NOT end user intended method !
2058 void gdcmParser::SkipBytes(guint32 NBytes) {
2059 //FIXME don't dump the returned value
2060 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2064 * \ingroup gdcmParser
2065 * \brief Loads all the needed Dictionaries
2066 * \warning NOT end user intended method !
2068 void gdcmParser::Initialise(void)
2070 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2071 RefShaDict = (gdcmDict*)0;
2075 * \ingroup gdcmParser
2076 * \brief Discover what the swap code is (among little endian, big endian,
2077 * bad little endian, bad big endian).
2079 * @return false when we are absolutely sure
2080 * it's neither ACR-NEMA nor DICOM
2081 * true when we hope ours assuptions are OK
2083 bool gdcmParser::CheckSwap() {
2085 // The only guaranted way of finding the swap code is to find a
2086 // group tag since we know it's length has to be of four bytes i.e.
2087 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2088 // occurs when we can't find such group...
2090 guint32 x=4; // x : for ntohs
2091 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2097 char deb[HEADER_LENGTH_TO_READ];
2099 // First, compare HostByteOrder and NetworkByteOrder in order to
2100 // determine if we shall need to swap bytes (i.e. the Endian type).
2106 // The easiest case is the one of a DICOM header, since it possesses a
2107 // file preamble where it suffice to look for the string "DICM".
2108 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2111 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2112 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2114 // Next, determine the value representation (VR). Let's skip to the
2115 // first element (0002, 0000) and check there if we find "UL"
2116 // - or "OB" if the 1st one is (0002,0001) -,
2117 // in which case we (almost) know it is explicit VR.
2118 // WARNING: if it happens to be implicit VR then what we will read
2119 // is the length of the group. If this ascii representation of this
2120 // length happens to be "UL" then we shall believe it is explicit VR.
2121 // FIXME: in order to fix the above warning, we could read the next
2122 // element value (or a couple of elements values) in order to make
2123 // sure we are not commiting a big mistake.
2124 // We need to skip :
2125 // * the 128 bytes of File Preamble (often padded with zeroes),
2126 // * the 4 bytes of "DICM" string,
2127 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2128 // i.e. a total of 136 bytes.
2132 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2133 // but elem 0002,0010 (Transfert Syntax) tells us the file is *Implicit* VR.
2136 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2137 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2138 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2139 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2140 // when Write DCM *adds*
2142 // Use gdcmParser::dicom_vr to test all the possibilities
2143 // instead of just checking for UL, OB and UI !? // group 0000
2146 filetype = ExplicitVR;
2147 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2148 "explicit Value Representation");
2152 filetype = ImplicitVR;
2153 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2154 "not an explicit Value Representation");
2160 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2161 "HostByteOrder != NetworkByteOrder");
2166 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2167 "HostByteOrder = NetworkByteOrder");
2170 // Position the file position indicator at first tag (i.e.
2171 // after the file preamble and the "DICM" string).
2173 fseek (fp, 132L, SEEK_SET);
2177 // Alas, this is not a DicomV3 file and whatever happens there is no file
2178 // preamble. We can reset the file position indicator to where the data
2179 // is (i.e. the beginning of the file).
2180 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2183 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2184 // By clean we mean that the length of the first tag is written down.
2185 // If this is the case and since the length of the first group HAS to be
2186 // four (bytes), then determining the proper swap code is straightforward.
2189 // We assume the array of char we are considering contains the binary
2190 // representation of a 32 bits integer. Hence the following dirty
2192 s32 = *((guint32 *)(entCur));
2213 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2214 // It is time for despaired wild guesses.
2215 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2216 // i.e. the 'group length' element is not present :
2218 // check the supposed to be 'group number'
2219 // 0x0002 or 0x0004 or 0x0008
2220 // to determine ' sw' value .
2221 // Only 0 or 4321 will be possible
2222 // (no oportunity to check for the formerly well known
2223 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2224 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2225 // the file IS NOT ACR-NEMA nor DICOM V3
2226 // Find a trick to tell it the caller...
2228 s16 = *((guint16 *)(deb));
2244 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2245 "ACR/NEMA unfound swap info (Really hopeless !)");
2250 // Then the only info we have is the net2host one.
2260 * \ingroup gdcmParser
2261 * \brief Restore the unproperly loaded values i.e. the group, the element
2262 * and the dictionary entry depending on them.
2264 void gdcmParser::SwitchSwapToBigEndian(void)
2266 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2267 "Switching to BigEndian mode.");
2288 * \ingroup gdcmParser
2289 * \brief during parsing, Header Elements too long are not loaded in memory
2292 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2296 if ((guint32)NewSize >= (guint32)0xffffffff)
2298 MaxSizeLoadEntry = 0xffffffff;
2301 MaxSizeLoadEntry = NewSize;
2306 * \ingroup gdcmParser
2307 * \brief Header Elements too long will not be printed
2309 * \todo : not yet usable
2310 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2311 * in gdcmHeaderEntry gdcmLoadEntry)
2315 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2319 if ((guint32)NewSize >= (guint32)0xffffffff)
2321 MaxSizePrintEntry = 0xffffffff;
2324 MaxSizePrintEntry = NewSize;
2328 * \ingroup gdcmParser
2329 * \brief Searches both the public and the shadow dictionary (when they
2330 * exist) for the presence of the DictEntry with given name.
2331 * The public dictionary has precedence on the shadow one.
2332 * @param Name name of the searched DictEntry
2333 * @return Corresponding DictEntry when it exists, NULL otherwise.
2335 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2337 gdcmDictEntry *found = (gdcmDictEntry *)0;
2338 if (!RefPubDict && !RefShaDict)
2340 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2341 "we SHOULD have a default dictionary");
2345 found = RefPubDict->GetDictEntryByName(Name);
2351 found = RefShaDict->GetDictEntryByName(Name);
2359 * \ingroup gdcmParser
2360 * \brief Searches both the public and the shadow dictionary (when they
2361 * exist) for the presence of the DictEntry with given
2362 * group and element. The public dictionary has precedence on the
2364 * @param group group of the searched DictEntry
2365 * @param element element of the searched DictEntry
2366 * @return Corresponding DictEntry when it exists, NULL otherwise.
2368 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2370 gdcmDictEntry *found = (gdcmDictEntry *)0;
2371 if (!RefPubDict && !RefShaDict)
2373 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2374 "we SHOULD have a default dictionary");
2378 found = RefPubDict->GetDictEntryByNumber(group, element);
2384 found = RefShaDict->GetDictEntryByNumber(group, element);
2392 * \ingroup gdcmParser
2393 * \brief Read the next tag but WITHOUT loading it's value
2394 * @return On succes the newly created HeaderEntry, NULL on failure.
2396 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2398 gdcmHeaderEntry *NewEntry;
2403 // We reached the EOF (or an error occured) therefore
2404 // header parsing has to be considered as finished.
2405 return (gdcmHeaderEntry *)0;
2407 // Pb : how to propagate the element length (used in SkipHeaderEntry)
2408 // direct call to SkipBytes ?
2410 // if (ignoreShadow == 1 && g%2 ==1)
2411 // if user wants to skip shadow groups
2412 // and current element *is* a shadow element
2413 // we don't create anything
2414 // return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2416 NewEntry = NewHeaderEntryByNumber(g, n);
2417 FindHeaderEntryVR(NewEntry);
2418 FindHeaderEntryLength(NewEntry);
2424 NewEntry->SetOffset(ftell(fp));
2429 * \ingroup gdcmParser
2430 * \brief Build a new Element Value from all the low level arguments.
2431 * Check for existence of dictionary entry, and build
2432 * a default one when absent.
2433 * @param Name Name of the underlying DictEntry
2435 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2437 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2439 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2441 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2444 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2445 "failed to allocate gdcmHeaderEntry");
2446 return (gdcmHeaderEntry *)0;
2452 * \ingroup gdcmParser
2453 * \brief Request a new virtual dict entry to the dict set
2454 * @param group group of the underlying DictEntry
2455 * @param element element of the underlying DictEntry
2456 * @param vr VR of the underlying DictEntry
2457 * @param fourth owner group
2458 * @param name english name
2460 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2465 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2469 * \ingroup gdcmParser
2470 * \brief Build a new Element Value from all the low level arguments.
2471 * Check for existence of dictionary entry, and build
2472 * a default one when absent.
2473 * @param Group group of the underlying DictEntry
2474 * @param Elem element of the underlying DictEntry
2476 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2478 // Find out if the tag we encountered is in the dictionaries:
2479 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2481 DictEntry = NewVirtualDictEntry(Group, Elem);
2483 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2486 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2487 "failed to allocate gdcmHeaderEntry");
2493 // Never used; commented out, waiting for removal.
2495 * \ingroup gdcmParser
2496 * \brief Small utility function that creates a new manually crafted
2497 * (as opposed as read from the file) gdcmHeaderEntry with user
2498 * specified name and adds it to the public tag hash table.
2499 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2500 * @param NewTagName The name to be given to this new tag.
2501 * @param VR The Value Representation to be given to this new tag.
2502 * @return The newly hand crafted Element Value.
2504 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2507 // gdcmHeaderEntry *NewEntry = NULL;
2508 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2509 // guint32 FreeElem = 0;
2510 // gdcmDictEntry *DictEntry = NULL;
2512 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2513 // if (FreeElem == UINT32_MAX)
2515 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2516 // "Group 0xffff in Public Dict is full");
2520 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2521 // VR, "GDCM", NewTagName);
2522 // NewEntry = new gdcmHeaderEntry(DictEntry);
2523 // AddHeaderEntry(NewEntry);
2528 * \ingroup gdcmParser
2529 * \brief Generate a free TagKey i.e. a TagKey that is not present
2530 * in the TagHt dictionary.
2531 * @param group The generated tag must belong to this group.
2532 * @return The element of tag with given group which is fee.
2534 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2536 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2538 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2539 if (tagHT.count(key) == 0)
2545 //-----------------------------------------------------------------------------