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 * \ingroup gdcmParser
127 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
130 void gdcmParser::PrintPubDict(std::ostream & os) {
131 RefPubDict->Print(os);
135 * \ingroup gdcmParser
136 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnary
139 void gdcmParser::PrintShaDict(std::ostream & os) {
140 RefShaDict->Print(os);
143 //-----------------------------------------------------------------------------
146 * \ingroup gdcmParser
147 * \brief Get the public dictionary used
149 gdcmDict *gdcmParser::GetPubDict(void) {
154 * \ingroup gdcmParser
155 * \brief Get the shadow dictionary used
157 gdcmDict *gdcmParser::GetShaDict(void) {
162 * \ingroup gdcmParser
163 * \brief Set the shadow dictionary used
164 * \param dict dictionary to use in shadow
166 bool gdcmParser::SetShaDict(gdcmDict *dict){
172 * \ingroup gdcmParser
173 * \brief Set the shadow dictionary used
174 * \param dictName name of the dictionary to use in shadow
176 bool gdcmParser::SetShaDict(DictKey dictName){
177 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
182 * \ingroup gdcmParser
183 * \brief This predicate, based on hopefully reasonable heuristics,
184 * decides whether or not the current gdcmParser was properly parsed
185 * and contains the mandatory information for being considered as
186 * a well formed and usable Dicom/Acr File.
187 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
190 bool gdcmParser::IsReadable(void) {
191 if(filetype==Unknown) {
194 if(listEntries.size()<=0) {
202 * \ingroup gdcmParser
203 * \brief Determines if the Transfer Syntax was already encountered
204 * and if it corresponds to a ImplicitVRLittleEndian one.
205 * @return True when ImplicitVRLittleEndian found. False in all other cases.
207 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
208 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
211 LoadHeaderEntrySafe(Element);
213 std::string Transfer = Element->GetValue();
214 if ( Transfer == UI1_2_840_10008_1_2 )
220 * \ingroup gdcmParser
221 * \brief Determines if the Transfer Syntax was already encountered
222 * and if it corresponds to a ExplicitVRLittleEndian one.
223 * @return True when ExplicitVRLittleEndian found. False in all other cases.
225 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
226 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
229 LoadHeaderEntrySafe(Element);
231 std::string Transfer = Element->GetValue();
232 if ( Transfer == UI1_2_840_10008_1_2_1 )
238 * \ingroup gdcmParser
239 * \brief Determines if the Transfer Syntax was already encountered
240 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
241 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
243 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
244 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
247 LoadHeaderEntrySafe(Element);
249 std::string Transfer = Element->GetValue();
250 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
256 * \ingroup gdcmParser
257 * \brief Determines if the Transfer Syntax was already encountered
258 * and if it corresponds to a Explicit VR Big Endian one.
259 * @return True when big endian found. False in all other cases.
261 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
262 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
265 LoadHeaderEntrySafe(Element);
267 std::string Transfer = Element->GetValue();
268 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
274 * \ingroup gdcmParser
275 * \brief returns the File Type
276 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
277 * @return the FileType code
279 FileType gdcmParser::GetFileType(void) {
284 * \ingroup gdcmParser
285 * \brief opens the file
286 * @param exception_on_error
289 FILE *gdcmParser::OpenFile(bool exception_on_error)
292 fp=fopen(filename.c_str(),"rb");
293 if(exception_on_error)
296 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
302 fread(&zero, (size_t)2, (size_t)1, fp);
304 //ACR -- or DICOM with no Preamble --
305 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
309 fseek(fp, 126L, SEEK_CUR);
311 fread(dicm, (size_t)4, (size_t)1, fp);
312 if( memcmp(dicm, "DICM", 4) == 0 )
316 dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
319 dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
325 * \ingroup gdcmParser
326 * \brief closes the file
327 * @return TRUE if the close was successfull
329 bool gdcmParser::CloseFile(void) {
330 int closed = fclose(fp);
338 * \ingroup gdcmParser
339 * \brief writes on disc all the Header Entries (Dicom Elements)
340 * of the Chained List
341 * @param fp file pointer on an already open file
342 * @param type type of the File to be written
343 * (ACR-NEMA, ExplicitVR, ImplicitVR)
344 * @return always "True" ?!
346 bool gdcmParser::Write(FILE *fp, FileType type) {
348 // TODO The stuff was rewritten using the chained list instead
350 // so we could remove the GroupHT from the gdcmParser
354 // TODO : move the following lines (and a lot of others, to be written)
355 // to a future function CheckAndCorrectHeader
358 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier
359 // DicomV3 ou non (FileType est un champ de gdcmParser ...)
360 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
362 // a moins de se livrer a un tres complique ajout des champs manquants.
363 // faire un CheckAndCorrectHeader (?)
365 if (type == ImplicitVR)
367 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
368 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
370 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
371 // values with a VR of UI shall be padded with a single trailing null
372 // Dans le cas suivant on doit pader manuellement avec un 0
374 SetEntryLengthByNumber(18, 0x0002, 0x0010);
377 if (type == ExplicitVR)
379 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
380 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
382 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
383 // values with a VR of UI shall be padded with a single trailing null
384 // Dans le cas suivant on doit pader manuellement avec un 0
386 SetEntryLengthByNumber(20, 0x0002, 0x0010);
389 /* TODO : rewrite later, if really usefull
391 if ( (type == ImplicitVR) || (type == ExplicitVR) )
392 UpdateGroupLength(false,type);
394 UpdateGroupLength(true,ACR);
397 WriteEntries(fp,type);
402 * \ingroup gdcmParser
403 * \brief Modifies the value of a given Header Entry (Dicom Element)
404 * if it exists; Creates it with the given value if it doesn't
405 * \warning : adds the Header Entry to the HTable, NOT to the chained List
406 * @param Value passed as a std::string
407 * @param Group group of the Entry
408 * @param Elem element of the Entry
409 * \return pointer to the created Header Entry
410 * NULL if creation failed
412 gdcmHeaderEntry * gdcmParser::ReplaceOrCreateByNumber(
417 a = GetHeaderEntryByNumber( Group, Elem);
419 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
424 //SetEntryByNumber(Value, Group, Elem);
430 * \ingroup gdcmParser
431 * \brief Modifies the value of a given Header Entry (Dicom Element)
432 * if it exists; Creates it with the given value if it doesn't
433 * @param Value passed as a char*
434 * @param Group group of the Entry
435 * @param Elem element of the Entry
436 * \return pointer to the created Header Entry
437 * NULL if creation failed
440 gdcmHeaderEntry * gdcmParser::ReplaceOrCreateByNumber(
444 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
449 AddHeaderEntry(nvHeaderEntry);
451 std::string v = Value;
452 SetEntryByNumber(v, Group, Elem);
453 return(nvHeaderEntry);
457 * \ingroup gdcmParser
458 * \brief Set a new value if the invoked element exists
459 * Seems to be useless !!!
460 * @param Value new element value
461 * @param Group group of the Entry
462 * @param Elem element of the Entry
465 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
467 std::string v = Value;
468 SetEntryByNumber(v, Group, Elem);
472 //-----------------------------------------------------------------------------
476 * \ingroup gdcmParser
477 * \brief Checks if a given Dicom Element exists
479 * @param group Group number of the searched Dicom Element
480 * @param element Element number of the searched Dicom Element
481 * @return number of occurences
483 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
484 std::string key = gdcmDictEntry::TranslateToKey(group, element );
485 return (tagHT.count(key));
489 * \ingroup gdcmParser
490 * \brief Searches within Header Entries (Dicom Elements) parsed with
491 * the public and private dictionaries
492 * for the element value of a given tag.
493 * \warning Don't use any longer : use GetPubEntryByName
494 * @param tagName name of the searched element.
495 * @return Corresponding element value when it exists,
496 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
498 std::string gdcmParser::GetEntryByName(std::string tagName) {
499 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
500 if( dictEntry == NULL)
503 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
507 * \ingroup gdcmParser
508 * \brief Searches within Header Entries (Dicom Elements) parsed with
509 * the public and private dictionaries
510 * for the element value representation of a given tag.
512 * Obtaining the VR (Value Representation) might be needed by caller
513 * to convert the string typed content to caller's native type
514 * (think of C++ vs Python). The VR is actually of a higher level
515 * of semantics than just the native C++ type.
516 * @param tagName name of the searched element.
517 * @return Corresponding element value representation when it exists,
518 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
520 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
521 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
522 if( dictEntry == NULL)
525 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
526 dictEntry->GetElement());
527 return elem->GetVR();
532 * \ingroup gdcmParser
533 * \brief Searches within Header Entries (Dicom Elements) parsed with
534 * the public and private dictionaries
535 * for the element value representation of a given tag.
536 * @param group Group of the searched tag.
537 * @param element Element of the searched tag.
538 * @return Corresponding element value representation when it exists,
539 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
541 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
542 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
543 if ( ! tagHT.count(key))
545 return tagHT.find(key)->second->GetValue();
549 * \ingroup gdcmParser
550 * \brief Searches within Header Entries (Dicom Elements) parsed with
551 * the public and private dictionaries
552 * for the element value representation of a given tag..
554 * Obtaining the VR (Value Representation) might be needed by caller
555 * to convert the string typed content to caller's native type
556 * (think of C++ vs Python). The VR is actually of a higher level
557 * of semantics than just the native C++ type.
558 * @param group Group of the searched tag.
559 * @param element Element of the searched tag.
560 * @return Corresponding element value representation when it exists,
561 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
563 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
564 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
567 return elem->GetVR();
571 * \ingroup gdcmParser
572 * \brief Searches within Header Entries (Dicom Elements) parsed with
573 * the public and private dictionaries
574 * for the value length of a given tag..
575 * @param group Group of the searched tag.
576 * @param element Element of the searched tag.
577 * @return Corresponding element length; -2 if not found
579 int gdcmParser::GetEntryLengthByNumber(guint16 group, guint16 element) {
580 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
583 return elem->GetLength();
586 * \ingroup gdcmParser
587 * \brief Sets the value (string) of the Header Entry (Dicom Element)
588 * @param content string value of the Dicom Element
589 * @param tagName name of the searched Dicom Element.
590 * @return true when found
592 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
593 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
594 if( dictEntry == NULL)
597 return(SetEntryByNumber(content,dictEntry->GetGroup(),
598 dictEntry->GetElement()));
602 * \ingroup gdcmParser
603 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
604 * through it's (group, element) and modifies it's content with
606 * \warning Don't use any longer : use SetPubEntryByNumber
607 * @param content new value to substitute with
608 * @param group group of the Dicom Element to modify
609 * @param element element of the Dicom Element to modify
611 bool gdcmParser::SetEntryByNumber(std::string content,
615 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
616 if ( ! tagHT.count(key))
618 int l = content.length();
619 if(l%2) // Non even length are padded with a space (020H).
622 content = content + '\0';
627 TagHeaderEntryHT::iterator p2;
628 // DO NOT remove the following lines : they explain the stuff
629 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
630 //p2=p.first; // iterator on the first synonym
631 //a=p2->second; // H Table target column (2-nd col)
634 a = ((tagHT.equal_range(key)).first)->second;
636 a-> SetValue(content);
638 std::string vr = a->GetVR();
641 if( (vr == "US") || (vr == "SS") )
643 else if( (vr == "UL") || (vr == "SL") )
653 * \ingroup gdcmParser
654 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
655 * in the PubHeaderEntrySet of this instance
656 * through it's (group, element) and modifies it's length with
658 * \warning Use with extreme caution.
659 * @param l new length to substitute with
660 * @param group group of the Entry to modify
661 * @param element element of the Entry to modify
662 * @return true on success, false otherwise.
664 bool gdcmParser::SetEntryLengthByNumber(guint32 l,
668 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
669 if ( ! tagHT.count(key))
671 if (l%2) l++; // length must be even
672 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
678 * \ingroup gdcmParser
679 * \brief Gets (from Header) the offset of a 'non string' element value
680 * (LoadElementValues has already be executed)
681 * @param Group group of the Entry
682 * @param Elem element of the Entry
683 * @return File Offset of the Element Value
685 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
687 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
690 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
691 "failed to Locate gdcmHeaderEntry");
694 return Entry->GetOffset();
698 * \ingroup gdcmParser
699 * \brief Gets (from Header) a 'non string' element value
700 * (LoadElementValues has already be executed)
701 * @param Group group of the Entry
702 * @param Elem element of the Entry
703 * @return Pointer to the 'non string' area
705 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
707 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
710 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
711 "failed to Locate gdcmHeaderEntry");
714 return Entry->GetVoidArea();
718 * \ingroup gdcmParser
719 * \brief Loads (from disk) the element content
720 * when a string is not suitable
721 * @param Group group of the Entry
722 * @param Elem element of the Entry
724 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
726 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
729 size_t o =(size_t)Element->GetOffset();
730 fseek(fp, o, SEEK_SET);
731 int l=Element->GetLength();
732 void * a = malloc(l);
736 SetEntryVoidAreaByNumber(a, Group, Elem);
737 // TODO check the result
738 size_t l2 = fread(a, 1, l ,fp);
749 * \ingroup gdcmParser
750 * \brief Sets a 'non string' value to a given Dicom Element
752 * @param group Group number of the searched Dicom Element
753 * @param element Element number of the searched Dicom Element
756 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
760 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
761 if ( ! tagHT.count(key))
763 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
768 * \ingroup gdcmParser
769 * \brief Update the entries with the shadow dictionary.
770 * Only non even entries are analyzed
772 void gdcmParser::UpdateShaEntries(void) {
773 gdcmDictEntry *entry;
776 for(ListTag::iterator it=listEntries.begin();
777 it!=listEntries.end();
780 // Odd group => from public dictionary
781 if((*it)->GetGroup()%2==0)
784 // Peer group => search the corresponding dict entry
786 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
790 if((*it)->IsImplicitVR())
795 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
797 // Set the new entry and the new value
798 (*it)->SetDictEntry(entry);
799 CheckHeaderEntryVR(*it,vr);
801 (*it)->SetValue(GetHeaderEntryValue(*it));
805 // Remove precedent value transformation
806 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
812 * \ingroup gdcmParser
813 * \brief Searches within the Header Entries for a Dicom Element of
815 * @param tagName name of the searched Dicom Element.
816 * @return Corresponding Dicom Element when it exists, and NULL
819 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
820 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
821 if( dictEntry == NULL)
824 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
828 * \ingroup gdcmParser
829 * \brief retrieves a Dicom Element (the first one) using (group, element)
830 * \warning (group, element) IS NOT an identifier inside the Dicom Header
831 * if you think it's NOT UNIQUE, check the count number
832 * and use iterators to retrieve ALL the Dicoms Elements within
833 * a given couple (group, element)
834 * @param group Group number of the searched Dicom Element
835 * @param element Element number of the searched Dicom Element
838 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
840 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
841 if ( ! tagHT.count(key))
843 return tagHT.find(key)->second;
847 * \ingroup gdcmParser
848 * \brief retrieves the Dicom Elements (all of them) using (group, element)
849 * @param group Group number of the searched Dicom Element.
850 * @param element Element number of the searched Dicom Element.
851 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
854 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
855 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
856 return (tagHT.equal_range(key));
860 * \ingroup gdcmParser
861 * \brief Loads the element while preserving the current
862 * underlying file position indicator as opposed to
863 * to LoadHeaderEntry that modifies it.
864 * @param entry Header Entry whose value shall be loaded.
867 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
868 long PositionOnEntry = ftell(fp);
869 LoadHeaderEntry(entry);
870 fseek(fp, PositionOnEntry, SEEK_SET);
874 * \ingroup gdcmParser
875 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
876 * \warning : to be re-written using the chained list instead of the H table.
877 * \warning : DO NOT use (doesn't work any longer because of the multimap)
878 * \todo : to be re-written using the chained list instead of the H table
879 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
880 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
882 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
886 gdcmHeaderEntry *elem;
888 std::string str_trash;
891 GroupHT groupHt; // to hold the length of each group
894 // typedef std::map<GroupKey, int> GroupHT;
896 gdcmHeaderEntry *elemZ;
898 // for each Tag in the DCM Header
900 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
905 gr = elem->GetGroup();
906 el = elem->GetElement();
909 sprintf(trash, "%04x", gr);
910 key = trash; // generate 'group tag'
912 // if the caller decided not to take SEQUENCEs into account
913 // e.g : he wants to write an ACR-NEMA File
915 if (SkipSequence && vr == "SQ")
918 // Still unsolved problem :
919 // we cannot find the 'Sequence Delimitation Item'
920 // since it's at the end of the Hash Table
923 // pas SEQUENCE en ACR-NEMA
925 // --> la descente a l'interieur' des SQ
926 // devrait etre faite avec une liste chainee, pas avec une HTable...
928 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
930 if (el == 0x0000) // the first elem is 0x0000
932 groupHt[key] = 0; // initialize group length
936 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
939 else // any elem but the first
941 if (type == ExplicitVR)
943 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
945 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
948 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
952 unsigned short int gr_bid;
954 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
958 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
959 // warning: unsigned int format, different type arg
960 sscanf(g->first.c_str(),"%x",&gr_bid);
961 tk = g->first + "|0000"; // generate the element full tag
963 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
965 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
966 elemZ = new gdcmHeaderEntry(tagZ);
968 AddHeaderEntry(elemZ); // create it
972 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
974 sprintf(trash ,"%d",g->second);
976 elemZ->SetValue(str_trash);
981 * \ingroup gdcmParser
982 * \brief writes on disc according to the requested format
983 * (ACR-NEMA, ExplicitVR, ImplicitVR) ONE
985 * @param tag pointer on the gdcmHeaderEntry to be written
986 * @param type type of the File to be written
987 * (ACR-NEMA, ExplicitVR, ImplicitVR)
988 * @param _fp already open file pointer
990 void gdcmParser::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1001 std::vector<std::string> tokens;
1005 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1007 itsTimeToWritePixels = false;
1009 gr = tag->GetGroup();
1010 el = tag->GetElement();
1011 lgr = tag->GetReadLength();
1012 val = tag->GetValue().c_str();
1014 voidArea = tag->GetVoidArea();
1016 // === Deal with the length
1017 // --------------------
1018 if((tag->GetLength())%2==1)
1020 tag->SetValue(tag->GetValue()+"\0");
1021 tag->SetLength(tag->GetReadLength()+1);
1024 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1025 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1027 if ( (type == ExplicitVR) || (type == DICOMDIR) ) {
1029 guint16 z=0, shortLgr;
1031 if (gr == 0xfffe) { // NO Value Representation for 'delimiters'
1032 // no length : write ffffffff
1034 // special patch to make some MR PHILIPS images e-film readable
1035 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1036 // from Hospital Guy de Chauliac, Montpellier
1037 // we just ignore spurious fffe|0000 tag !
1038 if (el == 0x0000) return;
1040 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1041 return; // NO value for 'delimiters'
1045 if (vr == "unkn") { // Unknown was 'written'
1046 // deal with Little Endian
1047 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1048 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1050 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1051 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1053 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1054 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1056 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1062 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1065 // === Deal with the value
1066 // -------------------
1067 if (vr == "SQ") return; // no "value" to write for the SEQuences
1068 if (gr == 0xfffe)return; // no "value" to write for the delimiters
1070 if (voidArea != NULL)
1071 { // there is a 'non string' LUT, overlay, etc
1072 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1076 if (vr == "US" || vr == "SS")
1078 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1079 Tokenize (tag->GetValue(), tokens, "\\");
1080 for (unsigned int i=0; i<tokens.size();i++)
1082 val_uint16 = atoi(tokens[i].c_str());
1084 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1090 if (vr == "UL" || vr == "SL")
1092 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1093 Tokenize (tag->GetValue(), tokens, "\\");
1094 for (unsigned int i=0; i<tokens.size();i++)
1096 val_uint32 = atoi(tokens[i].c_str());
1098 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1104 // Pixels are never loaded in the element !
1105 // we stop writting when Pixel are processed
1106 // FIX : we loose trailing elements (RAB, right now)
1108 if ((gr == GrPixel) && (el == NumPixel) ) {
1110 if (compte == countGrPixel) {// we passed *all* the GrPixel,NumPixel
1111 itsTimeToWritePixels = true;
1115 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1119 * \ingroup gdcmParser
1120 * \brief writes on disc according to the requested format
1121 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1122 * using the Chained List
1123 * \warning does NOT add the missing elements in the header :
1124 * it's up to the user doing it !
1125 * (function CheckHeaderCoherence to be written)
1126 * \warning DON'T try, right now, to write a DICOM image
1127 * from an ACR Header (meta elements will be missing!)
1128 * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1129 * @param type type of the File to be written
1130 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1131 * @param _fp already open file pointer
1134 void gdcmParser::WriteEntries(FILE *_fp,FileType type)
1136 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1138 for (ListTag::iterator tag2=listEntries.begin();
1139 tag2 != listEntries.end();
1143 if ((*tag2)->GetGroup() < 0x0008) continue; // ignore pure DICOM V3 groups
1144 if ((*tag2)->GetElement() %2) continue; // ignore shadow groups
1145 if ((*tag2)->GetVR() == "SQ" ) continue; // ignore Sequences
1146 // TODO : find a trick to *skip* the SeQuences !
1147 // Not only ignore the SQ element
1148 // --> will be done with the next organization
1149 if ((*tag2)->GetGroup() == 0xfffe ) continue; // ignore delimiters
1151 WriteEntry(*tag2,_fp,type);
1152 if (itsTimeToWritePixels)
1158 * \ingroup gdcmParser
1159 * \brief writes on disc according to the requested format
1160 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1161 * using only the last synonym of each mutimap H Table post.
1162 * \warning Uses the H Table, instead of the Chained List
1163 * in order to be compliant with the old way to proceed
1164 * (added elements taken in to account)
1165 * Only THERALYS, during a transitory phase is supposed
1166 * to use this method !!!
1167 * \warning DON'T try, right now, to write a DICOM image
1168 * from an ACR Header (meta elements will be missing!)
1170 * @param _fp already open file pointer
1171 * @param type type of the File to be written
1172 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1174 void gdcmParser::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1176 // restent a tester les echecs en ecriture (apres chaque fwrite)
1178 for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1179 tag2 != tagHT.end();
1182 if ((*tag2->second).GetGroup() < 0x0008) continue; // ignore pure DICOM V3 groups
1183 if ((*tag2->second).GetElement() %2) continue; // ignore shadow groups
1184 if ((*tag2->second).GetVR() == "SQ" ) continue; // ignore Sequences
1185 // TODO : find a trick to *skip* the SeQuences !
1186 // Not only ignore the SQ element
1187 // --> will be done with the next organization
1188 if ((*tag2->second).GetGroup() == 0xfffe ) continue; // ignore delimiters
1190 WriteEntry(tag2->second,_fp,type);
1191 if (itsTimeToWritePixels)
1197 * \ingroup gdcmParser
1198 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1200 * @return The properly swaped 32 bits integer.
1202 guint32 gdcmParser::SwapLong(guint32 a) {
1207 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1208 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1212 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1216 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1219 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1226 * \ingroup gdcmParser
1227 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1229 * @return The properly unswaped 32 bits integer.
1231 guint32 gdcmParser::UnswapLong(guint32 a) {
1232 return (SwapLong(a));
1236 * \ingroup gdcmParser
1237 * \brief Swaps the bytes so they agree with the processor order
1238 * @return The properly swaped 16 bits integer.
1240 guint16 gdcmParser::SwapShort(guint16 a) {
1241 if ( (sw==4321) || (sw==2143) )
1242 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1247 * \ingroup gdcmParser
1248 * \brief Unswaps the bytes so they agree with the processor order
1249 * @return The properly unswaped 16 bits integer.
1251 guint16 gdcmParser::UnswapShort(guint16 a) {
1252 return (SwapShort(a));
1255 //-----------------------------------------------------------------------------
1258 * \ingroup gdcmParser
1259 * \brief Parses the header of the file but WITHOUT loading element values.
1260 * @return false if file is not ACR-NEMA / DICOM
1262 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1268 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1269 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1270 SkipHeaderEntry(newHeaderEntry);
1271 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1272 AddHeaderEntry(newHeaderEntry);
1279 * \ingroup gdcmParser
1280 * \brief Loads the element values of all the Header Entries pointed in the
1281 * public Chained List.
1283 void gdcmParser::LoadHeaderEntries(void) {
1285 for (ListTag::iterator i = GetListEntry().begin();
1286 i != GetListEntry().end();
1289 LoadHeaderEntry(*i);
1294 // Load 'non string' values
1295 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1296 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1297 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1298 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1299 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1300 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1302 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1303 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1304 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1306 //FIXME : how to use it?
1307 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1309 // --------------------------------------------------------------
1310 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1312 // if recognition code tells us we deal with a LibIDO image
1313 // we switch lineNumber and columnNumber
1315 std::string RecCode;
1316 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1317 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1318 RecCode == "CANRME_AILIBOD1_1." )
1320 filetype = ACR_LIBIDO;
1321 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1322 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1323 SetEntryByNumber(columns, 0x0028, 0x0010);
1324 SetEntryByNumber(rows , 0x0028, 0x0011);
1326 // ----------------- End of Special Patch ----------------
1330 * \ingroup gdcmParser
1331 * \brief Loads the element content if its length doesn't exceed
1332 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1333 * @param Entry Header Entry (Dicom Element) to be dealt with
1335 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1337 guint16 group = Entry->GetGroup();
1338 std::string vr= Entry->GetVR();
1339 guint32 length = Entry->GetLength();
1340 bool SkipLoad = false;
1342 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1344 // the test was commented out to 'go inside' the SeQuences
1345 // we don't any longer skip them !
1347 // if( vr == "SQ" ) // (DO NOT remove this comment)
1350 // A SeQuence "contains" a set of Elements.
1351 // (fffe e000) tells us an Element is beginning
1352 // (fffe e00d) tells us an Element just ended
1353 // (fffe e0dd) tells us the current SeQuence just ended
1354 if( group == 0xfffe )
1358 Entry->SetLength(0);
1359 Entry->SetValue("gdcm::Skipped");
1363 // When the length is zero things are easy:
1364 if ( length == 0 ) {
1365 Entry->SetValue("");
1369 // The elements whose length is bigger than the specified upper bound
1370 // are not loaded. Instead we leave a short notice of the offset of
1371 // the element content and it's length.
1372 if (length > MaxSizeLoadEntry) {
1373 std::ostringstream s;
1374 s << "gdcm::NotLoaded.";
1375 s << " Address:" << (long)Entry->GetOffset();
1376 s << " Length:" << Entry->GetLength();
1377 s << " x(" << std::hex << Entry->GetLength() << ")";
1378 Entry->SetValue(s.str());
1382 // When integer(s) are expected, read and convert the following
1383 // n *(two or four bytes)
1384 // properly i.e. as integers as opposed to strings.
1385 // Elements with Value Multiplicity > 1
1386 // contain a set of integers (not a single one)
1388 // Any compacter code suggested (?)
1389 if ( IsHeaderEntryAnInteger(Entry) ) {
1391 std::ostringstream s;
1393 if (vr == "US" || vr == "SS") {
1395 NewInt = ReadInt16();
1398 for (int i=1; i < nbInt; i++) {
1400 NewInt = ReadInt16();
1405 else if (vr == "UL" || vr == "SL") {
1407 NewInt = ReadInt32();
1410 for (int i=1; i < nbInt; i++) {
1412 NewInt = ReadInt32();
1417 #ifdef GDCM_NO_ANSI_STRING_STREAM
1418 s << std::ends; // to avoid oddities on Solaris
1419 #endif //GDCM_NO_ANSI_STRING_STREAM
1421 Entry->SetValue(s.str());
1425 // We need an additional byte for storing \0 that is not on disk
1426 std::string NewValue(length,0);
1427 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1428 if ( item_read != 1 ) {
1429 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1430 Entry->SetValue("gdcm::UnRead");
1434 if( (vr == "UI") ) // Because of correspondance with the VR dic
1435 Entry->SetValue(NewValue.c_str());
1437 Entry->SetValue(NewValue);
1441 * \ingroup gdcmParser
1442 * \brief add a new Dicom Element pointer to
1443 * the H Table and at the end of the chained List
1444 * \warning push_bash in listEntries ONLY during ParseHeader
1445 * \todo something to allow further Elements addition,
1446 * (at their right place in the chained list)
1447 * when position to be taken care of
1448 * @param newHeaderEntry
1450 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1451 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1452 listEntries.push_back(newHeaderEntry);
1457 * \ingroup gdcmParser
1458 * \brief Find the value Length of the passed Header Entry
1459 * @param Entry Header Entry whose length of the value shall be loaded.
1461 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1462 guint16 element = Entry->GetElement();
1463 guint16 group = Entry->GetGroup();
1464 std::string vr = Entry->GetVR();
1467 if( (element == NumPixel) && (group == GrPixel) )
1469 dbg.SetDebug(GDCM_DEBUG);
1470 dbg.Verbose(2, "gdcmParser::FindLength: ",
1471 "we reached (GrPixel,NumPixel)");
1474 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1476 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1478 // The following reserved two bytes (see PS 3.5-2001, section
1479 // 7.1.2 Data element structure with explicit vr p27) must be
1480 // skipped before proceeding on reading the length on 4 bytes.
1481 fseek(fp, 2L, SEEK_CUR);
1482 guint32 length32 = ReadInt32();
1484 if ( (vr == "OB") && (length32 == 0xffffffff) )
1486 Entry->SetLength(FindHeaderEntryLengthOB());
1489 FixHeaderEntryFoundLength(Entry, length32);
1493 // Length is encoded on 2 bytes.
1494 length16 = ReadInt16();
1496 // We can tell the current file is encoded in big endian (like
1497 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1498 // and it's value is the one of the encoding of a big endian file.
1499 // In order to deal with such big endian encoded files, we have
1500 // (at least) two strategies:
1501 // * when we load the "Transfer Syntax" tag with value of big endian
1502 // encoding, we raise the proper flags. Then we wait for the end
1503 // of the META group (0x0002) among which is "Transfer Syntax",
1504 // before switching the swap code to big endian. We have to postpone
1505 // the switching of the swap code since the META group is fully encoded
1506 // in little endian, and big endian coding only starts at the next
1507 // group. The corresponding code can be hard to analyse and adds
1508 // many additional unnecessary tests for regular tags.
1509 // * the second strategy consists in waiting for trouble, that shall
1510 // appear when we find the first group with big endian encoding. This
1511 // is easy to detect since the length of a "Group Length" tag (the
1512 // ones with zero as element number) has to be of 4 (0x0004). When we
1513 // encounter 1024 (0x0400) chances are the encoding changed and we
1514 // found a group with big endian encoding.
1515 // We shall use this second strategy. In order to make sure that we
1516 // can interpret the presence of an apparently big endian encoded
1517 // length of a "Group Length" without committing a big mistake, we
1518 // add an additional check: we look in the already parsed elements
1519 // for the presence of a "Transfer Syntax" whose value has to be "big
1520 // endian encoding". When this is the case, chances are we have got our
1521 // hands on a big endian encoded file: we switch the swap code to
1522 // big endian and proceed...
1523 if ( (element == 0x0000) && (length16 == 0x0400) )
1525 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1527 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1532 SwitchSwapToBigEndian();
1533 // Restore the unproperly loaded values i.e. the group, the element
1534 // and the dictionary entry depending on them.
1535 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1536 guint16 CorrectElem = SwapShort(Entry->GetElement());
1537 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1541 // This correct tag is not in the dictionary. Create a new one.
1542 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1544 // FIXME this can create a memory leaks on the old entry that be
1545 // left unreferenced.
1546 Entry->SetDictEntry(NewTag);
1549 // Heuristic: well some files are really ill-formed.
1550 if ( length16 == 0xffff)
1553 //dbg.Verbose(0, "gdcmParser::FindLength",
1554 // "Erroneous element length fixed.");
1555 // Actually, length= 0xffff means that we deal with
1556 // Unknown Sequence Length
1558 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1563 // Either implicit VR or a non DICOM conformal (see note below) explicit
1564 // VR that ommited the VR of (at least) this element. Farts happen.
1565 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1566 // on Data elements "Implicit and Explicit VR Data Elements shall
1567 // not coexist in a Data Set and Data Sets nested within it".]
1568 // Length is on 4 bytes.
1570 FixHeaderEntryFoundLength(Entry, ReadInt32());
1576 * \ingroup gdcmParser
1577 * \brief Find the Value Representation of the current Dicom Element.
1580 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1582 if (filetype != ExplicitVR)
1587 long PositionOnEntry = ftell(fp);
1588 // Warning: we believe this is explicit VR (Value Representation) because
1589 // we used a heuristic that found "UL" in the first tag. Alas this
1590 // doesn't guarantee that all the tags will be in explicit VR. In some
1591 // cases (see e-film filtered files) one finds implicit VR tags mixed
1592 // within an explicit VR file. Hence we make sure the present tag
1593 // is in explicit VR and try to fix things if it happens not to be
1596 int lgrLue=fread (&VR, (size_t)2,(size_t)1, fp); // lgrLue not used
1598 if(!CheckHeaderEntryVR(Entry,VR))
1600 fseek(fp, PositionOnEntry, SEEK_SET);
1601 // When this element is known in the dictionary we shall use, e.g. for
1602 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1603 // dictionary entry. Still we have to flag the element as implicit since
1604 // we know now our assumption on expliciteness is not furfilled.
1606 if ( Entry->IsVRUnknown() )
1607 Entry->SetVR("Implicit");
1608 Entry->SetImplicitVR();
1613 * \ingroup gdcmParser
1614 * \brief Check the correspondance between the VR of the header entry
1615 * and the taken VR. If they are different, the header entry is
1616 * updated with the new VR.
1617 * @param Entry Header Entry to check
1618 * @param vr Dicom Value Representation
1619 * @return false if the VR is incorrect of if the VR isn't referenced
1620 * otherwise, it returns true
1622 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1624 char msg[100]; // for sprintf
1625 bool RealExplicit = true;
1627 // Assume we are reading a falsely explicit VR file i.e. we reached
1628 // a tag where we expect reading a VR but are in fact we read the
1629 // first to bytes of the length. Then we will interogate (through find)
1630 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1631 // both GCC and VC++ implementations of the STL map. Hence when the
1632 // expected VR read happens to be non-ascii characters we consider
1633 // we hit falsely explicit VR tag.
1635 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1636 RealExplicit = false;
1638 // CLEANME searching the dicom_vr at each occurence is expensive.
1639 // PostPone this test in an optional integrity check at the end
1640 // of parsing or only in debug mode.
1641 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1642 RealExplicit= false;
1644 if ( !RealExplicit )
1646 // We thought this was explicit VR, but we end up with an
1647 // implicit VR tag. Let's backtrack.
1648 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1649 Entry->GetGroup(),Entry->GetElement());
1650 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1651 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1652 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1653 Entry->GetGroup(),Entry->GetElement(),
1654 "UL","FIXME","Group Length");
1655 Entry->SetDictEntry(NewEntry);
1660 if ( Entry->IsVRUnknown() )
1662 // When not a dictionary entry, we can safely overwrite the VR.
1663 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1669 else if ( Entry->GetVR() != vr )
1671 // The VR present in the file and the dictionary disagree. We assume
1672 // the file writer knew best and use the VR of the file. Since it would
1673 // be unwise to overwrite the VR of a dictionary (since it would
1674 // compromise it's next user), we need to clone the actual DictEntry
1675 // and change the VR for the read one.
1676 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1677 Entry->GetGroup(),Entry->GetElement(),
1678 vr,"FIXME",Entry->GetName());
1679 Entry->SetDictEntry(NewEntry);
1685 * \ingroup gdcmParser
1686 * \brief Get the transformed value of the header entry. The VR value
1687 * is used to define the transformation to operate on the value
1688 * \warning NOT end user intended method !
1690 * @return Transformed entry value
1692 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1694 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1696 std::string val=Entry->GetValue();
1697 std::string vr=Entry->GetVR();
1698 guint32 length = Entry->GetLength();
1699 std::ostringstream s;
1702 if (vr == "US" || vr == "SS")
1707 for (int i=0; i < nbInt; i++)
1711 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1712 NewInt16 = SwapShort(NewInt16);
1717 else if (vr == "UL" || vr == "SL")
1722 for (int i=0; i < nbInt; i++)
1726 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1727 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1728 NewInt32=SwapLong(NewInt32);
1732 #ifdef GDCM_NO_ANSI_STRING_STREAM
1733 s << std::ends; // to avoid oddities on Solaris
1734 #endif //GDCM_NO_ANSI_STRING_STREAM
1738 return(Entry->GetValue());
1742 * \ingroup gdcmParser
1743 * \brief Get the reverse transformed value of the header entry. The VR
1744 * value is used to define the reverse transformation to operate on
1746 * \warning NOT end user intended method !
1748 * @return Reverse transformed entry value
1750 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1752 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1754 std::string vr=Entry->GetVR();
1755 std::ostringstream s;
1756 std::vector<std::string> tokens;
1758 if (vr == "US" || vr == "SS")
1762 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1763 Tokenize (Entry->GetValue(), tokens, "\\");
1764 for (unsigned int i=0; i<tokens.size();i++)
1766 NewInt16 = atoi(tokens[i].c_str());
1767 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1771 if (vr == "UL" || vr == "SL")
1775 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1776 Tokenize (Entry->GetValue(), tokens, "\\");
1777 for (unsigned int i=0; i<tokens.size();i++)
1779 NewInt32 = atoi(tokens[i].c_str());
1780 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1781 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1786 #ifdef GDCM_NO_ANSI_STRING_STREAM
1787 s << std::ends; // to avoid oddities on Solaris
1788 #endif //GDCM_NO_ANSI_STRING_STREAM
1792 return(Entry->GetValue());
1796 * \ingroup gdcmParser
1797 * \brief Skip a given Header Entry
1798 * \warning NOT end user intended method !
1801 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1803 SkipBytes(entry->GetLength());
1807 * \ingroup gdcmParser
1808 * \brief When the length of an element value is obviously wrong (because
1809 * the parser went Jabberwocky) one can hope improving things by
1810 * applying this heuristic.
1812 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1814 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1816 if ( FoundLength == 0xffffffff) {
1820 guint16 gr =Entry->GetGroup();
1821 guint16 el =Entry->GetElement();
1823 if (FoundLength%2) {
1824 std::ostringstream s;
1825 s << "Warning : Tag with uneven length " << FoundLength
1826 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1827 dbg.Verbose(0,s.str().c_str());
1830 // Sorry for the patch!
1831 // XMedCom did the trick to read some nasty GE images ...
1832 if (FoundLength == 13) {
1833 // The following 'if' will be removed when there is no more
1834 // images on Creatis HDs with a 13 length for Manufacturer...
1835 if ( (Entry->GetGroup() != 0x0008) ||
1836 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1837 // end of remove area
1839 Entry->SetReadLength(10); // a bug is to be fixed
1843 // to fix some garbage 'Leonardo' Siemens images
1844 // May be commented out to avoid overhead
1845 else if ( (Entry->GetGroup() == 0x0009) &&
1846 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1848 Entry->SetReadLength(4); // a bug is to be fixed
1852 // to try to 'go inside' SeQuences (with length), and not to skip them
1853 else if ( Entry->GetVR() == "SQ")
1855 if (enableSequences) // only if the user does want to !
1856 FoundLength =0; // ReadLength is unchanged
1859 // a SeQuence Element is beginning
1860 // fffe|e000 is just a marker, its length *should be* zero
1861 else if(Entry->GetGroup() == 0xfffe)
1863 // *normally, fffe|0000 doesn't exist !
1864 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1865 // causes extra troubles :-(
1868 Entry->SetUsableLength(FoundLength);
1872 * \ingroup gdcmParser
1873 * \brief Apply some heuristics to predict whether the considered
1874 * element value contains/represents an integer or not.
1875 * @param Entry The element value on which to apply the predicate.
1876 * @return The result of the heuristical predicate.
1878 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1879 guint16 element = Entry->GetElement();
1880 guint16 group = Entry->GetGroup();
1881 std::string vr = Entry->GetVR();
1882 guint32 length = Entry->GetLength();
1883 // When we have some semantics on the element we just read, and if we
1884 // a priori know we are dealing with an integer, then we shall be
1885 // able to swap it's element value properly.
1886 if ( element == 0 ) // This is the group length of the group
1892 std::ostringstream s;
1893 int filePosition = ftell(fp);
1894 s << "Erroneous Group Length element length on : (" \
1895 << std::hex << group << " , " << element
1896 << ") -before- position x(" << filePosition << ")"
1897 << "lgt : " << length;
1898 // These 2 lines commented out : a *very dirty* patch
1899 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1900 // have a glance at offset x(8336) ...
1901 // For *regular* headers, the test is useless..
1902 // lets's print a warning message and go on,
1903 // instead of giving up with an error message
1905 //std::cout << s.str().c_str() << std::endl;
1906 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1907 // s.str().c_str());
1910 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1916 * \ingroup gdcmParser
1917 * \brief Find the Length till the next sequence delimiter
1918 * \warning NOT end user intended method !
1922 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1923 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1926 long PositionOnEntry = ftell(fp);
1927 bool FoundSequenceDelimiter = false;
1928 guint32 TotalLength = 0;
1931 while ( ! FoundSequenceDelimiter)
1937 TotalLength += 4; // We even have to decount the group and element
1939 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1941 char msg[100]; // for sprintf. Sorry
1942 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1943 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1947 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1948 FoundSequenceDelimiter = true;
1949 else if ( n != 0xe000 )
1951 char msg[100]; // for sprintf. Sorry
1952 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1954 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1958 ItemLength = ReadInt32();
1959 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1960 // the ItemLength with ReadInt32
1961 SkipBytes(ItemLength);
1963 fseek(fp, PositionOnEntry, SEEK_SET);
1968 * \ingroup gdcmParser
1969 * \brief Reads a supposed to be 16 Bits integer
1970 * (swaps it depending on processor endianity)
1971 * @return read value
1973 guint16 gdcmParser::ReadInt16(void) {
1976 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1977 if ( item_read != 1 ) {
1979 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1989 * \ingroup gdcmParser
1990 * \brief Reads a supposed to be 32 Bits integer
1991 * (swaps it depending on processor endianity)
1992 * @return read value
1994 guint32 gdcmParser::ReadInt32(void) {
1997 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1998 if ( item_read != 1 ) {
2000 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
2010 * \ingroup gdcmParser
2011 * \brief skips bytes inside the source file
2012 * \warning NOT end user intended method !
2015 void gdcmParser::SkipBytes(guint32 NBytes) {
2016 //FIXME don't dump the returned value
2017 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2021 * \ingroup gdcmParser
2022 * \brief Loads all the needed Dictionaries
2023 * \warning NOT end user intended method !
2025 void gdcmParser::Initialise(void)
2027 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2028 RefShaDict = (gdcmDict*)0;
2032 * \ingroup gdcmParser
2033 * \brief Discover what the swap code is (among little endian, big endian,
2034 * bad little endian, bad big endian).
2036 * @return false when we are absolutely sure
2037 * it's neither ACR-NEMA nor DICOM
2038 * true when we hope ours assuptions are OK
2040 bool gdcmParser::CheckSwap() {
2042 // The only guaranted way of finding the swap code is to find a
2043 // group tag since we know it's length has to be of four bytes i.e.
2044 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2045 // occurs when we can't find such group...
2047 guint32 x=4; // x : for ntohs
2048 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2054 char deb[HEADER_LENGTH_TO_READ];
2056 // First, compare HostByteOrder and NetworkByteOrder in order to
2057 // determine if we shall need to swap bytes (i.e. the Endian type).
2063 // The easiest case is the one of a DICOM header, since it possesses a
2064 // file preamble where it suffice to look for the string "DICM".
2065 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2068 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2069 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2071 // Next, determine the value representation (VR). Let's skip to the
2072 // first element (0002, 0000) and check there if we find "UL"
2073 // - or "OB" if the 1st one is (0002,0001) -,
2074 // in which case we (almost) know it is explicit VR.
2075 // WARNING: if it happens to be implicit VR then what we will read
2076 // is the length of the group. If this ascii representation of this
2077 // length happens to be "UL" then we shall believe it is explicit VR.
2078 // FIXME: in order to fix the above warning, we could read the next
2079 // element value (or a couple of elements values) in order to make
2080 // sure we are not commiting a big mistake.
2081 // We need to skip :
2082 // * the 128 bytes of File Preamble (often padded with zeroes),
2083 // * the 4 bytes of "DICM" string,
2084 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2085 // i.e. a total of 136 bytes.
2089 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2090 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2091 // *Implicit* VR. -and it is !-
2093 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2094 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2095 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2096 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2097 // when Write DCM *adds*
2099 // Use gdcmParser::dicom_vr to test all the possibilities
2100 // instead of just checking for UL, OB and UI !? group 0000
2102 filetype = ExplicitVR;
2103 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2104 "explicit Value Representation");
2108 filetype = ImplicitVR;
2109 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2110 "not an explicit Value Representation");
2116 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2117 "HostByteOrder != NetworkByteOrder");
2122 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2123 "HostByteOrder = NetworkByteOrder");
2126 // Position the file position indicator at first tag (i.e.
2127 // after the file preamble and the "DICM" string).
2129 fseek (fp, 132L, SEEK_SET);
2133 // Alas, this is not a DicomV3 file and whatever happens there is no file
2134 // preamble. We can reset the file position indicator to where the data
2135 // is (i.e. the beginning of the file).
2136 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2139 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2140 // By clean we mean that the length of the first tag is written down.
2141 // If this is the case and since the length of the first group HAS to be
2142 // four (bytes), then determining the proper swap code is straightforward.
2145 // We assume the array of char we are considering contains the binary
2146 // representation of a 32 bits integer. Hence the following dirty
2148 s32 = *((guint32 *)(entCur));
2169 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2170 // It is time for despaired wild guesses.
2171 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2172 // i.e. the 'group length' element is not present :
2174 // check the supposed to be 'group number'
2175 // 0x0002 or 0x0004 or 0x0008
2176 // to determine ' sw' value .
2177 // Only 0 or 4321 will be possible
2178 // (no oportunity to check for the formerly well known
2179 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2180 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2181 // the file IS NOT ACR-NEMA nor DICOM V3
2182 // Find a trick to tell it the caller...
2184 s16 = *((guint16 *)(deb));
2200 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2201 "ACR/NEMA unfound swap info (Really hopeless !)");
2206 // Then the only info we have is the net2host one.
2216 * \ingroup gdcmParser
2217 * \brief Restore the unproperly loaded values i.e. the group, the element
2218 * and the dictionary entry depending on them.
2220 void gdcmParser::SwitchSwapToBigEndian(void)
2222 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2223 "Switching to BigEndian mode.");
2244 * \ingroup gdcmParser
2245 * \brief during parsing, Header Elements too long are not loaded in memory
2248 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2252 if ((guint32)NewSize >= (guint32)0xffffffff)
2254 MaxSizeLoadEntry = 0xffffffff;
2257 MaxSizeLoadEntry = NewSize;
2262 * \ingroup gdcmParser
2263 * \brief Header Elements too long will not be printed
2265 * \todo : not yet usable
2266 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2267 * in gdcmHeaderEntry gdcmLoadEntry)
2271 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2275 if ((guint32)NewSize >= (guint32)0xffffffff)
2277 MaxSizePrintEntry = 0xffffffff;
2280 MaxSizePrintEntry = NewSize;
2284 * \ingroup gdcmParser
2285 * \brief Searches both the public and the shadow dictionary (when they
2286 * exist) for the presence of the DictEntry with given name.
2287 * The public dictionary has precedence on the shadow one.
2288 * @param Name name of the searched DictEntry
2289 * @return Corresponding DictEntry when it exists, NULL otherwise.
2291 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2293 gdcmDictEntry *found = (gdcmDictEntry *)0;
2294 if (!RefPubDict && !RefShaDict)
2296 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2297 "we SHOULD have a default dictionary");
2301 found = RefPubDict->GetDictEntryByName(Name);
2307 found = RefShaDict->GetDictEntryByName(Name);
2315 * \ingroup gdcmParser
2316 * \brief Searches both the public and the shadow dictionary (when they
2317 * exist) for the presence of the DictEntry with given
2318 * group and element. The public dictionary has precedence on the
2320 * @param group group of the searched DictEntry
2321 * @param element element of the searched DictEntry
2322 * @return Corresponding DictEntry when it exists, NULL otherwise.
2324 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2326 gdcmDictEntry *found = (gdcmDictEntry *)0;
2327 if (!RefPubDict && !RefShaDict)
2329 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2330 "we SHOULD have a default dictionary");
2334 found = RefPubDict->GetDictEntryByNumber(group, element);
2340 found = RefShaDict->GetDictEntryByNumber(group, element);
2348 * \ingroup gdcmParser
2349 * \brief Read the next tag but WITHOUT loading it's value
2350 * @return On succes the newly created HeaderEntry, NULL on failure.
2352 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2354 gdcmHeaderEntry *NewEntry;
2359 // We reached the EOF (or an error occured) therefore
2360 // header parsing has to be considered as finished.
2361 return (gdcmHeaderEntry *)0;
2363 // Pb : how to propagate the element length (used in SkipHeaderEntry)
2364 // direct call to SkipBytes ?
2366 // if (ignoreShadow == 1 && g%2 ==1)
2367 // if user wants to skip shadow groups
2368 // and current element *is* a shadow element
2369 // we don't create anything
2370 // return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2372 NewEntry = NewHeaderEntryByNumber(g, n);
2373 FindHeaderEntryVR(NewEntry);
2374 FindHeaderEntryLength(NewEntry);
2380 NewEntry->SetOffset(ftell(fp));
2385 * \ingroup gdcmParser
2386 * \brief Build a new Element Value from all the low level arguments.
2387 * Check for existence of dictionary entry, and build
2388 * a default one when absent.
2389 * @param Name Name of the underlying DictEntry
2391 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2393 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2395 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2397 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2400 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2401 "failed to allocate gdcmHeaderEntry");
2402 return (gdcmHeaderEntry *)0;
2408 * \ingroup gdcmParser
2409 * \brief Request a new virtual dict entry to the dict set
2410 * @param group group of the underlying DictEntry
2411 * @param element element of the underlying DictEntry
2412 * @param vr VR of the underlying DictEntry
2413 * @param fourth owner group
2414 * @param name english name
2416 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2421 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2425 * \ingroup gdcmParser
2426 * \brief Build a new Element Value from all the low level arguments.
2427 * Check for existence of dictionary entry, and build
2428 * a default one when absent.
2429 * @param Group group of the underlying DictEntry
2430 * @param Elem element of the underlying DictEntry
2432 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2434 // Find out if the tag we encountered is in the dictionaries:
2435 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2437 DictEntry = NewVirtualDictEntry(Group, Elem);
2439 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2442 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2443 "failed to allocate gdcmHeaderEntry");
2449 // Never used; commented out, waiting for removal.
2451 * \ingroup gdcmParser
2452 * \brief Small utility function that creates a new manually crafted
2453 * (as opposed as read from the file) gdcmHeaderEntry with user
2454 * specified name and adds it to the public tag hash table.
2455 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2456 * @param NewTagName The name to be given to this new tag.
2457 * @param VR The Value Representation to be given to this new tag.
2458 * @return The newly hand crafted Element Value.
2460 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2463 // gdcmHeaderEntry *NewEntry = NULL;
2464 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2465 // guint32 FreeElem = 0;
2466 // gdcmDictEntry *DictEntry = NULL;
2468 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2469 // if (FreeElem == UINT32_MAX)
2471 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2472 // "Group 0xffff in Public Dict is full");
2476 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2477 // VR, "GDCM", NewTagName);
2478 // NewEntry = new gdcmHeaderEntry(DictEntry);
2479 // AddHeaderEntry(NewEntry);
2484 * \ingroup gdcmParser
2485 * \brief Generate a free TagKey i.e. a TagKey that is not present
2486 * in the TagHt dictionary.
2487 * @param group The generated tag must belong to this group.
2488 * @return The element of tag with given group which is fee.
2490 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2492 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2494 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2495 if (tagHT.count(key) == 0)
2501 //-----------------------------------------------------------------------------