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 * \brief Loads (from disk) the element content
719 * when a string is not suitable
720 * @param Group group of the Entry
721 * @param Elem element of the Entry
723 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
725 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
728 size_t o =(size_t)Element->GetOffset();
729 fseek(fp, o, SEEK_SET);
730 int l=Element->GetLength();
731 void * a = malloc(l);
735 SetEntryVoidAreaByNumber(a, Group, Elem);
736 // TODO check the result
737 size_t l2 = fread(a, 1, l ,fp);
748 * \ingroup gdcmParser
749 * \brief Sets a 'non string' value to a given Dicom Element
751 * @param group Group number of the searched Dicom Element
752 * @param element Element number of the searched Dicom Element
755 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
759 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
760 if ( ! tagHT.count(key))
762 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
767 * \ingroup gdcmParser
768 * \brief Update the entries with the shadow dictionary.
769 * Only non even entries are analyzed
771 void gdcmParser::UpdateShaEntries(void) {
772 gdcmDictEntry *entry;
775 for(ListTag::iterator it=listEntries.begin();
776 it!=listEntries.end();
779 // Odd group => from public dictionary
780 if((*it)->GetGroup()%2==0)
783 // Peer group => search the corresponding dict entry
785 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
789 if((*it)->IsImplicitVR())
794 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
796 // Set the new entry and the new value
797 (*it)->SetDictEntry(entry);
798 CheckHeaderEntryVR(*it,vr);
800 (*it)->SetValue(GetHeaderEntryValue(*it));
804 // Remove precedent value transformation
805 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
811 * \ingroup gdcmParser
812 * \brief Searches within the Header Entries for a Dicom Element of
814 * @param tagName name of the searched Dicom Element.
815 * @return Corresponding Dicom Element when it exists, and NULL
818 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
819 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
820 if( dictEntry == NULL)
823 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
827 * \ingroup gdcmParser
828 * \brief retrieves a Dicom Element (the first one) using (group, element)
829 * \warning (group, element) IS NOT an identifier inside the Dicom Header
830 * if you think it's NOT UNIQUE, check the count number
831 * and use iterators to retrieve ALL the Dicoms Elements within
832 * a given couple (group, element)
833 * @param group Group number of the searched Dicom Element
834 * @param element Element number of the searched Dicom Element
837 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
839 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
840 if ( ! tagHT.count(key))
842 return tagHT.find(key)->second;
846 * \ingroup gdcmParser
847 * \brief retrieves the Dicom Elements (all of them) using (group, element)
848 * @param group Group number of the searched Dicom Element.
849 * @param element Element number of the searched Dicom Element.
850 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
853 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
854 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
855 return (tagHT.equal_range(key));
859 * \ingroup gdcmParser
860 * \brief Loads the element while preserving the current
861 * underlying file position indicator as opposed to
862 * to LoadHeaderEntry that modifies it.
863 * @param entry Header Entry whose value shall be loaded.
866 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
867 long PositionOnEntry = ftell(fp);
868 LoadHeaderEntry(entry);
869 fseek(fp, PositionOnEntry, SEEK_SET);
873 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
874 * \warning : to be re-written using the chained list instead of the H table.
875 * \warning : DO NOT use (doesn't work any longer because of the multimap)
876 * \todo : to be re-written using the chained list instead of the H table
877 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
878 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
880 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
884 gdcmHeaderEntry *elem;
886 std::string str_trash;
889 GroupHT groupHt; // to hold the length of each group
892 // typedef std::map<GroupKey, int> GroupHT;
894 gdcmHeaderEntry *elemZ;
896 // for each Tag in the DCM Header
898 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
903 gr = elem->GetGroup();
904 el = elem->GetElement();
907 sprintf(trash, "%04x", gr);
908 key = trash; // generate 'group tag'
910 // if the caller decided not to take SEQUENCEs into account
911 // e.g : he wants to write an ACR-NEMA File
913 if (SkipSequence && vr == "SQ")
916 // Still unsolved problem :
917 // we cannot find the 'Sequence Delimitation Item'
918 // since it's at the end of the Hash Table
921 // pas SEQUENCE en ACR-NEMA
923 // --> la descente a l'interieur' des SQ
924 // devrait etre faite avec une liste chainee, pas avec une HTable...
926 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
928 if (el == 0x0000) // the first elem is 0x0000
930 groupHt[key] = 0; // initialize group length
934 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
937 else // any elem but the first
939 if (type == ExplicitVR)
941 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
943 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
946 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
950 unsigned short int gr_bid;
952 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
956 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
957 // warning: unsigned int format, different type arg
958 sscanf(g->first.c_str(),"%x",&gr_bid);
959 tk = g->first + "|0000"; // generate the element full tag
961 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
963 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
964 elemZ = new gdcmHeaderEntry(tagZ);
966 AddHeaderEntry(elemZ); // create it
970 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
972 sprintf(trash ,"%d",g->second);
974 elemZ->SetValue(str_trash);
979 * \brief Writes in a file (according to the requested format)
980 * the group, the element, the value representation and the length
981 of a single gdcmHeaderEntry passed as argument.
982 * @param tag pointer on the gdcmHeaderEntry to be written
983 * @param _fp already open file pointer
984 * @param type type of the File to be written
985 * (ACR-NEMA, ExplicitVR, ImplicitVR)
987 void gdcmParser::WriteEntryTagVRLength(gdcmHeaderEntry *tag,
991 guint16 group = tag->GetGroup();
992 std::string vr = tag->GetVR();
993 guint16 el = tag->GetElement();
994 guint32 lgr = tag->GetReadLength();
996 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
997 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
999 if ( type == ExplicitVR ) {
1001 // Special case of delimiters:
1002 if (group == 0xfffe) {
1003 // Delimiters have NO Value Representation and have NO length.
1004 // Hence we skip writing the VR and length and we pad by writing
1008 // Fix in order to make some MR PHILIPS images e-film readable
1009 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1010 // we just ignore spurious fffe|0000 tag !
1014 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1019 guint16 shortLgr = lgr;
1020 if (vr == "unkn") { // Unknown was 'written'
1021 // deal with Little Endian
1022 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1023 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1025 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1026 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1028 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1029 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1031 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1037 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1041 void gdcmParser::WriteEntryValue(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1043 guint16 group = tag->GetGroup();
1044 std::string vr = tag->GetVR();
1045 guint32 lgr = tag->GetReadLength();
1048 // SeQuences have no value:
1050 if (group == 0xfffe)
1051 // Delimiters have no associated value:
1056 voidArea = tag->GetVoidArea();
1057 if (voidArea != NULL)
1058 { // there is a 'non string' LUT, overlay, etc
1059 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1063 if (vr == "US" || vr == "SS")
1065 std::vector<std::string> tokens;
1066 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1067 Tokenize (tag->GetValue(), tokens, "\\");
1068 for (unsigned int i=0; i<tokens.size();i++)
1070 guint16 val_uint16 = atoi(tokens[i].c_str());
1071 void *ptr = &val_uint16;
1072 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1078 if (vr == "UL" || vr == "SL")
1080 std::vector<std::string> tokens;
1081 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1082 Tokenize (tag->GetValue(), tokens, "\\");
1083 for (unsigned int i=0; i<tokens.size();i++)
1085 guint32 val_uint32 = atoi(tokens[i].c_str());
1086 void *ptr = &val_uint32;
1087 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1093 fwrite (tag->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1096 void gdcmParser::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1098 guint32 length = tag->GetLength();
1100 // The value of a tag MUST (see the DICOM norm) be an odd number of
1101 // bytes. When this is not the case, pad with an additional byte:
1104 tag->SetValue(tag->GetValue()+"\0");
1105 tag->SetLength(tag->GetReadLength()+1);
1108 WriteEntryTagVRLength(tag, _fp, type);
1110 // Pixels are never loaded in the element !
1111 // we stop writting when Pixel are processed
1112 // FIX : we loose trailing elements (RAB, right now)
1113 guint16 el = tag->GetElement();
1114 guint16 group = tag->GetGroup();
1116 itsTimeToWritePixels = false;
1117 if ((group == GrPixel) && (el == NumPixel) ) {
1119 if (compte == countGrPixel) {// we passed *all* the GrPixel,NumPixel
1120 itsTimeToWritePixels = true;
1124 WriteEntryValue(tag, _fp, type);
1128 * \brief writes on disc according to the requested format
1129 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1130 * using the Chained List
1131 * \warning does NOT add the missing elements in the header :
1132 * it's up to the user doing it !
1133 * (function CheckHeaderCoherence to be written)
1134 * \warning DON'T try, right now, to write a DICOM image
1135 * from an ACR Header (meta elements will be missing!)
1136 * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1137 * @param type type of the File to be written
1138 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1139 * @param _fp already open file pointer
1142 void gdcmParser::WriteEntries(FILE *_fp,FileType type)
1144 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1146 for (ListTag::iterator tag2=listEntries.begin();
1147 tag2 != listEntries.end();
1151 if ((*tag2)->GetGroup() < 0x0008)
1152 // Ignore pure DICOM V3 groups
1154 if ((*tag2)->GetElement() %2)
1155 // Ignore the "shadow" groups
1157 if ((*tag2)->GetVR() == "SQ" )
1158 // For the time being sequences are simply ignored
1159 // TODO : find a trick not to *skip* the SeQuences !
1161 if ((*tag2)->GetGroup() == 0xfffe )
1162 // Ignore the documented delimiter
1165 WriteEntry(*tag2,_fp,type);
1166 if (itsTimeToWritePixels)
1172 * \ingroup gdcmParser
1173 * \brief writes on disc according to the requested format
1174 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1175 * using only the last synonym of each mutimap H Table post.
1176 * \warning Uses the H Table, instead of the Chained List
1177 * in order to be compliant with the old way to proceed
1178 * (added elements taken in to account)
1179 * Only THERALYS, during a transitory phase is supposed
1180 * to use this method !!!
1181 * \warning DON'T try, right now, to write a DICOM image
1182 * from an ACR Header (meta elements will be missing!)
1184 * @param _fp already open file pointer
1185 * @param type type of the File to be written
1186 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1188 void gdcmParser::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1190 // restent a tester les echecs en ecriture (apres chaque fwrite)
1192 for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1193 tag2 != tagHT.end();
1196 if ((*tag2->second).GetGroup() < 0x0008) continue; // ignore pure DICOM V3 groups
1197 if ((*tag2->second).GetElement() %2) continue; // ignore shadow groups
1198 if ((*tag2->second).GetVR() == "SQ" ) continue; // ignore Sequences
1199 // TODO : find a trick to *skip* the SeQuences !
1200 // Not only ignore the SQ element
1201 // --> will be done with the next organization
1202 if ((*tag2->second).GetGroup() == 0xfffe ) continue; // ignore delimiters
1204 WriteEntry(tag2->second,_fp,type);
1205 if (itsTimeToWritePixels)
1211 * \ingroup gdcmParser
1212 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1214 * @return The properly swaped 32 bits integer.
1216 guint32 gdcmParser::SwapLong(guint32 a) {
1221 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1222 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1226 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1230 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1233 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1240 * \ingroup gdcmParser
1241 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1243 * @return The properly unswaped 32 bits integer.
1245 guint32 gdcmParser::UnswapLong(guint32 a) {
1246 return (SwapLong(a));
1250 * \ingroup gdcmParser
1251 * \brief Swaps the bytes so they agree with the processor order
1252 * @return The properly swaped 16 bits integer.
1254 guint16 gdcmParser::SwapShort(guint16 a) {
1255 if ( (sw==4321) || (sw==2143) )
1256 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1261 * \ingroup gdcmParser
1262 * \brief Unswaps the bytes so they agree with the processor order
1263 * @return The properly unswaped 16 bits integer.
1265 guint16 gdcmParser::UnswapShort(guint16 a) {
1266 return (SwapShort(a));
1269 //-----------------------------------------------------------------------------
1272 * \ingroup gdcmParser
1273 * \brief Parses the header of the file but WITHOUT loading element values.
1274 * @return false if file is not ACR-NEMA / DICOM
1276 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1282 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1283 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1284 SkipHeaderEntry(newHeaderEntry);
1285 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1286 AddHeaderEntry(newHeaderEntry);
1293 * \ingroup gdcmParser
1294 * \brief Loads the element values of all the Header Entries pointed in the
1295 * public Chained List.
1297 void gdcmParser::LoadHeaderEntries(void) {
1299 for (ListTag::iterator i = GetListEntry().begin();
1300 i != GetListEntry().end();
1303 LoadHeaderEntry(*i);
1308 // Load 'non string' values
1309 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1310 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1311 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1312 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1313 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1314 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1316 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1317 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1318 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1320 //FIXME : how to use it?
1321 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1323 // --------------------------------------------------------------
1324 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1326 // if recognition code tells us we deal with a LibIDO image
1327 // we switch lineNumber and columnNumber
1329 std::string RecCode;
1330 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1331 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1332 RecCode == "CANRME_AILIBOD1_1." )
1334 filetype = ACR_LIBIDO;
1335 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1336 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1337 SetEntryByNumber(columns, 0x0028, 0x0010);
1338 SetEntryByNumber(rows , 0x0028, 0x0011);
1340 // ----------------- End of Special Patch ----------------
1344 * \ingroup gdcmParser
1345 * \brief Loads the element content if its length doesn't exceed
1346 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1347 * @param Entry Header Entry (Dicom Element) to be dealt with
1349 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1351 guint16 group = Entry->GetGroup();
1352 std::string vr= Entry->GetVR();
1353 guint32 length = Entry->GetLength();
1354 bool SkipLoad = false;
1356 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1358 // the test was commented out to 'go inside' the SeQuences
1359 // we don't any longer skip them !
1361 // if( vr == "SQ" ) // (DO NOT remove this comment)
1364 // A SeQuence "contains" a set of Elements.
1365 // (fffe e000) tells us an Element is beginning
1366 // (fffe e00d) tells us an Element just ended
1367 // (fffe e0dd) tells us the current SeQuence just ended
1368 if( group == 0xfffe )
1372 Entry->SetLength(0);
1373 Entry->SetValue("gdcm::Skipped");
1377 // When the length is zero things are easy:
1378 if ( length == 0 ) {
1379 Entry->SetValue("");
1383 // The elements whose length is bigger than the specified upper bound
1384 // are not loaded. Instead we leave a short notice of the offset of
1385 // the element content and it's length.
1386 if (length > MaxSizeLoadEntry) {
1387 std::ostringstream s;
1388 s << "gdcm::NotLoaded.";
1389 s << " Address:" << (long)Entry->GetOffset();
1390 s << " Length:" << Entry->GetLength();
1391 s << " x(" << std::hex << Entry->GetLength() << ")";
1392 Entry->SetValue(s.str());
1396 // When integer(s) are expected, read and convert the following
1397 // n *(two or four bytes)
1398 // properly i.e. as integers as opposed to strings.
1399 // Elements with Value Multiplicity > 1
1400 // contain a set of integers (not a single one)
1402 // Any compacter code suggested (?)
1403 if ( IsHeaderEntryAnInteger(Entry) ) {
1405 std::ostringstream s;
1407 if (vr == "US" || vr == "SS") {
1409 NewInt = ReadInt16();
1412 for (int i=1; i < nbInt; i++) {
1414 NewInt = ReadInt16();
1419 else if (vr == "UL" || vr == "SL") {
1421 NewInt = ReadInt32();
1424 for (int i=1; i < nbInt; i++) {
1426 NewInt = ReadInt32();
1431 #ifdef GDCM_NO_ANSI_STRING_STREAM
1432 s << std::ends; // to avoid oddities on Solaris
1433 #endif //GDCM_NO_ANSI_STRING_STREAM
1435 Entry->SetValue(s.str());
1439 // We need an additional byte for storing \0 that is not on disk
1440 std::string NewValue(length,0);
1441 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1442 if ( item_read != 1 ) {
1443 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1444 Entry->SetValue("gdcm::UnRead");
1448 if( (vr == "UI") ) // Because of correspondance with the VR dic
1449 Entry->SetValue(NewValue.c_str());
1451 Entry->SetValue(NewValue);
1455 * \ingroup gdcmParser
1456 * \brief add a new Dicom Element pointer to
1457 * the H Table and at the end of the chained List
1458 * \warning push_bash in listEntries ONLY during ParseHeader
1459 * \todo something to allow further Elements addition,
1460 * (at their right place in the chained list)
1461 * when position to be taken care of
1462 * @param newHeaderEntry
1464 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1465 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1466 listEntries.push_back(newHeaderEntry);
1471 * \ingroup gdcmParser
1472 * \brief Find the value Length of the passed Header Entry
1473 * @param Entry Header Entry whose length of the value shall be loaded.
1475 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1476 guint16 element = Entry->GetElement();
1477 guint16 group = Entry->GetGroup();
1478 std::string vr = Entry->GetVR();
1481 if( (element == NumPixel) && (group == GrPixel) )
1483 dbg.SetDebug(GDCM_DEBUG);
1484 dbg.Verbose(2, "gdcmParser::FindLength: ",
1485 "we reached (GrPixel,NumPixel)");
1488 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1490 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1492 // The following reserved two bytes (see PS 3.5-2001, section
1493 // 7.1.2 Data element structure with explicit vr p27) must be
1494 // skipped before proceeding on reading the length on 4 bytes.
1495 fseek(fp, 2L, SEEK_CUR);
1496 guint32 length32 = ReadInt32();
1498 if ( (vr == "OB") && (length32 == 0xffffffff) )
1500 Entry->SetLength(FindHeaderEntryLengthOB());
1503 FixHeaderEntryFoundLength(Entry, length32);
1507 // Length is encoded on 2 bytes.
1508 length16 = ReadInt16();
1510 // We can tell the current file is encoded in big endian (like
1511 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1512 // and it's value is the one of the encoding of a big endian file.
1513 // In order to deal with such big endian encoded files, we have
1514 // (at least) two strategies:
1515 // * when we load the "Transfer Syntax" tag with value of big endian
1516 // encoding, we raise the proper flags. Then we wait for the end
1517 // of the META group (0x0002) among which is "Transfer Syntax",
1518 // before switching the swap code to big endian. We have to postpone
1519 // the switching of the swap code since the META group is fully encoded
1520 // in little endian, and big endian coding only starts at the next
1521 // group. The corresponding code can be hard to analyse and adds
1522 // many additional unnecessary tests for regular tags.
1523 // * the second strategy consists in waiting for trouble, that shall
1524 // appear when we find the first group with big endian encoding. This
1525 // is easy to detect since the length of a "Group Length" tag (the
1526 // ones with zero as element number) has to be of 4 (0x0004). When we
1527 // encounter 1024 (0x0400) chances are the encoding changed and we
1528 // found a group with big endian encoding.
1529 // We shall use this second strategy. In order to make sure that we
1530 // can interpret the presence of an apparently big endian encoded
1531 // length of a "Group Length" without committing a big mistake, we
1532 // add an additional check: we look in the already parsed elements
1533 // for the presence of a "Transfer Syntax" whose value has to be "big
1534 // endian encoding". When this is the case, chances are we have got our
1535 // hands on a big endian encoded file: we switch the swap code to
1536 // big endian and proceed...
1537 if ( (element == 0x0000) && (length16 == 0x0400) )
1539 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1541 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1546 SwitchSwapToBigEndian();
1547 // Restore the unproperly loaded values i.e. the group, the element
1548 // and the dictionary entry depending on them.
1549 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1550 guint16 CorrectElem = SwapShort(Entry->GetElement());
1551 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1555 // This correct tag is not in the dictionary. Create a new one.
1556 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1558 // FIXME this can create a memory leaks on the old entry that be
1559 // left unreferenced.
1560 Entry->SetDictEntry(NewTag);
1563 // Heuristic: well some files are really ill-formed.
1564 if ( length16 == 0xffff)
1567 //dbg.Verbose(0, "gdcmParser::FindLength",
1568 // "Erroneous element length fixed.");
1569 // Actually, length= 0xffff means that we deal with
1570 // Unknown Sequence Length
1572 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1577 // Either implicit VR or a non DICOM conformal (see note below) explicit
1578 // VR that ommited the VR of (at least) this element. Farts happen.
1579 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1580 // on Data elements "Implicit and Explicit VR Data Elements shall
1581 // not coexist in a Data Set and Data Sets nested within it".]
1582 // Length is on 4 bytes.
1584 FixHeaderEntryFoundLength(Entry, ReadInt32());
1590 * \ingroup gdcmParser
1591 * \brief Find the Value Representation of the current Dicom Element.
1594 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1596 if (filetype != ExplicitVR)
1601 long PositionOnEntry = ftell(fp);
1602 // Warning: we believe this is explicit VR (Value Representation) because
1603 // we used a heuristic that found "UL" in the first tag. Alas this
1604 // doesn't guarantee that all the tags will be in explicit VR. In some
1605 // cases (see e-film filtered files) one finds implicit VR tags mixed
1606 // within an explicit VR file. Hence we make sure the present tag
1607 // is in explicit VR and try to fix things if it happens not to be
1610 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1612 if(!CheckHeaderEntryVR(Entry,VR))
1614 fseek(fp, PositionOnEntry, SEEK_SET);
1615 // When this element is known in the dictionary we shall use, e.g. for
1616 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1617 // dictionary entry. Still we have to flag the element as implicit since
1618 // we know now our assumption on expliciteness is not furfilled.
1620 if ( Entry->IsVRUnknown() )
1621 Entry->SetVR("Implicit");
1622 Entry->SetImplicitVR();
1627 * \ingroup gdcmParser
1628 * \brief Check the correspondance between the VR of the header entry
1629 * and the taken VR. If they are different, the header entry is
1630 * updated with the new VR.
1631 * @param Entry Header Entry to check
1632 * @param vr Dicom Value Representation
1633 * @return false if the VR is incorrect of if the VR isn't referenced
1634 * otherwise, it returns true
1636 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1638 char msg[100]; // for sprintf
1639 bool RealExplicit = true;
1641 // Assume we are reading a falsely explicit VR file i.e. we reached
1642 // a tag where we expect reading a VR but are in fact we read the
1643 // first to bytes of the length. Then we will interogate (through find)
1644 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1645 // both GCC and VC++ implementations of the STL map. Hence when the
1646 // expected VR read happens to be non-ascii characters we consider
1647 // we hit falsely explicit VR tag.
1649 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1650 RealExplicit = false;
1652 // CLEANME searching the dicom_vr at each occurence is expensive.
1653 // PostPone this test in an optional integrity check at the end
1654 // of parsing or only in debug mode.
1655 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1656 RealExplicit= false;
1658 if ( !RealExplicit )
1660 // We thought this was explicit VR, but we end up with an
1661 // implicit VR tag. Let's backtrack.
1662 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1663 Entry->GetGroup(),Entry->GetElement());
1664 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1665 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1666 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1667 Entry->GetGroup(),Entry->GetElement(),
1668 "UL","FIXME","Group Length");
1669 Entry->SetDictEntry(NewEntry);
1674 if ( Entry->IsVRUnknown() )
1676 // When not a dictionary entry, we can safely overwrite the VR.
1677 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1683 else if ( Entry->GetVR() != vr )
1685 // The VR present in the file and the dictionary disagree. We assume
1686 // the file writer knew best and use the VR of the file. Since it would
1687 // be unwise to overwrite the VR of a dictionary (since it would
1688 // compromise it's next user), we need to clone the actual DictEntry
1689 // and change the VR for the read one.
1690 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1691 Entry->GetGroup(),Entry->GetElement(),
1692 vr,"FIXME",Entry->GetName());
1693 Entry->SetDictEntry(NewEntry);
1699 * \ingroup gdcmParser
1700 * \brief Get the transformed value of the header entry. The VR value
1701 * is used to define the transformation to operate on the value
1702 * \warning NOT end user intended method !
1704 * @return Transformed entry value
1706 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1708 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1710 std::string val=Entry->GetValue();
1711 std::string vr=Entry->GetVR();
1712 guint32 length = Entry->GetLength();
1713 std::ostringstream s;
1716 if (vr == "US" || vr == "SS")
1721 for (int i=0; i < nbInt; i++)
1725 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1726 NewInt16 = SwapShort(NewInt16);
1731 else if (vr == "UL" || vr == "SL")
1736 for (int i=0; i < nbInt; i++)
1740 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1741 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1742 NewInt32=SwapLong(NewInt32);
1746 #ifdef GDCM_NO_ANSI_STRING_STREAM
1747 s << std::ends; // to avoid oddities on Solaris
1748 #endif //GDCM_NO_ANSI_STRING_STREAM
1752 return(Entry->GetValue());
1756 * \ingroup gdcmParser
1757 * \brief Get the reverse transformed value of the header entry. The VR
1758 * value is used to define the reverse transformation to operate on
1760 * \warning NOT end user intended method !
1762 * @return Reverse transformed entry value
1764 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1766 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1768 std::string vr=Entry->GetVR();
1769 std::ostringstream s;
1770 std::vector<std::string> tokens;
1772 if (vr == "US" || vr == "SS")
1776 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1777 Tokenize (Entry->GetValue(), tokens, "\\");
1778 for (unsigned int i=0; i<tokens.size();i++)
1780 NewInt16 = atoi(tokens[i].c_str());
1781 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1785 if (vr == "UL" || vr == "SL")
1789 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1790 Tokenize (Entry->GetValue(), tokens, "\\");
1791 for (unsigned int i=0; i<tokens.size();i++)
1793 NewInt32 = atoi(tokens[i].c_str());
1794 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1795 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1800 #ifdef GDCM_NO_ANSI_STRING_STREAM
1801 s << std::ends; // to avoid oddities on Solaris
1802 #endif //GDCM_NO_ANSI_STRING_STREAM
1806 return(Entry->GetValue());
1810 * \ingroup gdcmParser
1811 * \brief Skip a given Header Entry
1812 * \warning NOT end user intended method !
1815 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1817 SkipBytes(entry->GetLength());
1821 * \ingroup gdcmParser
1822 * \brief When the length of an element value is obviously wrong (because
1823 * the parser went Jabberwocky) one can hope improving things by
1824 * applying this heuristic.
1826 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1828 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1830 if ( FoundLength == 0xffffffff) {
1834 guint16 gr =Entry->GetGroup();
1835 guint16 el =Entry->GetElement();
1837 if (FoundLength%2) {
1838 std::ostringstream s;
1839 s << "Warning : Tag with uneven length " << FoundLength
1840 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1841 dbg.Verbose(0,s.str().c_str());
1844 // Sorry for the patch!
1845 // XMedCom did the trick to read some nasty GE images ...
1846 if (FoundLength == 13) {
1847 // The following 'if' will be removed when there is no more
1848 // images on Creatis HDs with a 13 length for Manufacturer...
1849 if ( (Entry->GetGroup() != 0x0008) ||
1850 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1851 // end of remove area
1853 Entry->SetReadLength(10); // a bug is to be fixed
1857 // to fix some garbage 'Leonardo' Siemens images
1858 // May be commented out to avoid overhead
1859 else if ( (Entry->GetGroup() == 0x0009) &&
1860 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1862 Entry->SetReadLength(4); // a bug is to be fixed
1866 // to try to 'go inside' SeQuences (with length), and not to skip them
1867 else if ( Entry->GetVR() == "SQ")
1869 if (enableSequences) // only if the user does want to !
1870 FoundLength =0; // ReadLength is unchanged
1873 // a SeQuence Element is beginning
1874 // fffe|e000 is just a marker, its length *should be* zero
1875 else if(Entry->GetGroup() == 0xfffe)
1877 // *normally, fffe|0000 doesn't exist !
1878 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1879 // causes extra troubles :-(
1882 Entry->SetUsableLength(FoundLength);
1886 * \ingroup gdcmParser
1887 * \brief Apply some heuristics to predict whether the considered
1888 * element value contains/represents an integer or not.
1889 * @param Entry The element value on which to apply the predicate.
1890 * @return The result of the heuristical predicate.
1892 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1893 guint16 element = Entry->GetElement();
1894 guint16 group = Entry->GetGroup();
1895 std::string vr = Entry->GetVR();
1896 guint32 length = Entry->GetLength();
1897 // When we have some semantics on the element we just read, and if we
1898 // a priori know we are dealing with an integer, then we shall be
1899 // able to swap it's element value properly.
1900 if ( element == 0 ) // This is the group length of the group
1906 std::ostringstream s;
1907 int filePosition = ftell(fp);
1908 s << "Erroneous Group Length element length on : (" \
1909 << std::hex << group << " , " << element
1910 << ") -before- position x(" << filePosition << ")"
1911 << "lgt : " << length;
1912 // These 2 lines commented out : a *very dirty* patch
1913 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1914 // have a glance at offset x(8336) ...
1915 // For *regular* headers, the test is useless..
1916 // lets's print a warning message and go on,
1917 // instead of giving up with an error message
1919 //std::cout << s.str().c_str() << std::endl;
1920 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1921 // s.str().c_str());
1924 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1930 * \ingroup gdcmParser
1931 * \brief Find the Length till the next sequence delimiter
1932 * \warning NOT end user intended method !
1936 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1937 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1940 long PositionOnEntry = ftell(fp);
1941 bool FoundSequenceDelimiter = false;
1942 guint32 TotalLength = 0;
1945 while ( ! FoundSequenceDelimiter)
1951 TotalLength += 4; // We even have to decount the group and element
1953 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1955 char msg[100]; // for sprintf. Sorry
1956 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1957 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1961 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1962 FoundSequenceDelimiter = true;
1963 else if ( n != 0xe000 )
1965 char msg[100]; // for sprintf. Sorry
1966 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1968 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1972 ItemLength = ReadInt32();
1973 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1974 // the ItemLength with ReadInt32
1975 SkipBytes(ItemLength);
1977 fseek(fp, PositionOnEntry, SEEK_SET);
1982 * \ingroup gdcmParser
1983 * \brief Reads a supposed to be 16 Bits integer
1984 * (swaps it depending on processor endianity)
1985 * @return read value
1987 guint16 gdcmParser::ReadInt16(void) {
1990 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1991 if ( item_read != 1 ) {
1993 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
2003 * \ingroup gdcmParser
2004 * \brief Reads a supposed to be 32 Bits integer
2005 * (swaps it depending on processor endianity)
2006 * @return read value
2008 guint32 gdcmParser::ReadInt32(void) {
2011 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2012 if ( item_read != 1 ) {
2014 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
2024 * \ingroup gdcmParser
2025 * \brief skips bytes inside the source file
2026 * \warning NOT end user intended method !
2029 void gdcmParser::SkipBytes(guint32 NBytes) {
2030 //FIXME don't dump the returned value
2031 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2035 * \ingroup gdcmParser
2036 * \brief Loads all the needed Dictionaries
2037 * \warning NOT end user intended method !
2039 void gdcmParser::Initialise(void)
2041 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2042 RefShaDict = (gdcmDict*)0;
2046 * \ingroup gdcmParser
2047 * \brief Discover what the swap code is (among little endian, big endian,
2048 * bad little endian, bad big endian).
2050 * @return false when we are absolutely sure
2051 * it's neither ACR-NEMA nor DICOM
2052 * true when we hope ours assuptions are OK
2054 bool gdcmParser::CheckSwap() {
2056 // The only guaranted way of finding the swap code is to find a
2057 // group tag since we know it's length has to be of four bytes i.e.
2058 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2059 // occurs when we can't find such group...
2061 guint32 x=4; // x : for ntohs
2062 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2068 char deb[HEADER_LENGTH_TO_READ];
2070 // First, compare HostByteOrder and NetworkByteOrder in order to
2071 // determine if we shall need to swap bytes (i.e. the Endian type).
2077 // The easiest case is the one of a DICOM header, since it possesses a
2078 // file preamble where it suffice to look for the string "DICM".
2079 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2082 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2083 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2085 // Next, determine the value representation (VR). Let's skip to the
2086 // first element (0002, 0000) and check there if we find "UL"
2087 // - or "OB" if the 1st one is (0002,0001) -,
2088 // in which case we (almost) know it is explicit VR.
2089 // WARNING: if it happens to be implicit VR then what we will read
2090 // is the length of the group. If this ascii representation of this
2091 // length happens to be "UL" then we shall believe it is explicit VR.
2092 // FIXME: in order to fix the above warning, we could read the next
2093 // element value (or a couple of elements values) in order to make
2094 // sure we are not commiting a big mistake.
2095 // We need to skip :
2096 // * the 128 bytes of File Preamble (often padded with zeroes),
2097 // * the 4 bytes of "DICM" string,
2098 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2099 // i.e. a total of 136 bytes.
2103 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2104 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2105 // *Implicit* VR. -and it is !-
2107 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2108 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2109 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2110 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2111 // when Write DCM *adds*
2113 // Use gdcmParser::dicom_vr to test all the possibilities
2114 // instead of just checking for UL, OB and UI !? group 0000
2116 filetype = ExplicitVR;
2117 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2118 "explicit Value Representation");
2122 filetype = ImplicitVR;
2123 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2124 "not an explicit Value Representation");
2130 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2131 "HostByteOrder != NetworkByteOrder");
2136 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2137 "HostByteOrder = NetworkByteOrder");
2140 // Position the file position indicator at first tag (i.e.
2141 // after the file preamble and the "DICM" string).
2143 fseek (fp, 132L, SEEK_SET);
2147 // Alas, this is not a DicomV3 file and whatever happens there is no file
2148 // preamble. We can reset the file position indicator to where the data
2149 // is (i.e. the beginning of the file).
2150 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2153 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2154 // By clean we mean that the length of the first tag is written down.
2155 // If this is the case and since the length of the first group HAS to be
2156 // four (bytes), then determining the proper swap code is straightforward.
2159 // We assume the array of char we are considering contains the binary
2160 // representation of a 32 bits integer. Hence the following dirty
2162 s32 = *((guint32 *)(entCur));
2183 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2184 // It is time for despaired wild guesses.
2185 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2186 // i.e. the 'group length' element is not present :
2188 // check the supposed to be 'group number'
2189 // 0x0002 or 0x0004 or 0x0008
2190 // to determine ' sw' value .
2191 // Only 0 or 4321 will be possible
2192 // (no oportunity to check for the formerly well known
2193 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2194 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2195 // the file IS NOT ACR-NEMA nor DICOM V3
2196 // Find a trick to tell it the caller...
2198 s16 = *((guint16 *)(deb));
2214 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2215 "ACR/NEMA unfound swap info (Really hopeless !)");
2220 // Then the only info we have is the net2host one.
2230 * \ingroup gdcmParser
2231 * \brief Restore the unproperly loaded values i.e. the group, the element
2232 * and the dictionary entry depending on them.
2234 void gdcmParser::SwitchSwapToBigEndian(void)
2236 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2237 "Switching to BigEndian mode.");
2258 * \ingroup gdcmParser
2259 * \brief during parsing, Header Elements too long are not loaded in memory
2262 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2266 if ((guint32)NewSize >= (guint32)0xffffffff)
2268 MaxSizeLoadEntry = 0xffffffff;
2271 MaxSizeLoadEntry = NewSize;
2276 * \ingroup gdcmParser
2277 * \brief Header Elements too long will not be printed
2279 * \todo : not yet usable
2280 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2281 * in gdcmHeaderEntry gdcmLoadEntry)
2285 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2289 if ((guint32)NewSize >= (guint32)0xffffffff)
2291 MaxSizePrintEntry = 0xffffffff;
2294 MaxSizePrintEntry = NewSize;
2298 * \ingroup gdcmParser
2299 * \brief Searches both the public and the shadow dictionary (when they
2300 * exist) for the presence of the DictEntry with given name.
2301 * The public dictionary has precedence on the shadow one.
2302 * @param Name name of the searched DictEntry
2303 * @return Corresponding DictEntry when it exists, NULL otherwise.
2305 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2307 gdcmDictEntry *found = (gdcmDictEntry *)0;
2308 if (!RefPubDict && !RefShaDict)
2310 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2311 "we SHOULD have a default dictionary");
2315 found = RefPubDict->GetDictEntryByName(Name);
2321 found = RefShaDict->GetDictEntryByName(Name);
2329 * \ingroup gdcmParser
2330 * \brief Searches both the public and the shadow dictionary (when they
2331 * exist) for the presence of the DictEntry with given
2332 * group and element. The public dictionary has precedence on the
2334 * @param group group of the searched DictEntry
2335 * @param element element of the searched DictEntry
2336 * @return Corresponding DictEntry when it exists, NULL otherwise.
2338 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2340 gdcmDictEntry *found = (gdcmDictEntry *)0;
2341 if (!RefPubDict && !RefShaDict)
2343 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2344 "we SHOULD have a default dictionary");
2348 found = RefPubDict->GetDictEntryByNumber(group, element);
2354 found = RefShaDict->GetDictEntryByNumber(group, element);
2362 * \ingroup gdcmParser
2363 * \brief Read the next tag but WITHOUT loading it's value
2364 * @return On succes the newly created HeaderEntry, NULL on failure.
2366 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2368 gdcmHeaderEntry *NewEntry;
2373 // We reached the EOF (or an error occured) therefore
2374 // header parsing has to be considered as finished.
2375 return (gdcmHeaderEntry *)0;
2377 // Pb : how to propagate the element length (used in SkipHeaderEntry)
2378 // direct call to SkipBytes ?
2380 // if (ignoreShadow == 1 && g%2 ==1)
2381 // if user wants to skip shadow groups
2382 // and current element *is* a shadow element
2383 // we don't create anything
2384 // return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2386 NewEntry = NewHeaderEntryByNumber(g, n);
2387 FindHeaderEntryVR(NewEntry);
2388 FindHeaderEntryLength(NewEntry);
2394 NewEntry->SetOffset(ftell(fp));
2399 * \ingroup gdcmParser
2400 * \brief Build a new Element Value from all the low level arguments.
2401 * Check for existence of dictionary entry, and build
2402 * a default one when absent.
2403 * @param Name Name of the underlying DictEntry
2405 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2407 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2409 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2411 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2414 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2415 "failed to allocate gdcmHeaderEntry");
2416 return (gdcmHeaderEntry *)0;
2422 * \ingroup gdcmParser
2423 * \brief Request a new virtual dict entry to the dict set
2424 * @param group group of the underlying DictEntry
2425 * @param element element of the underlying DictEntry
2426 * @param vr VR of the underlying DictEntry
2427 * @param fourth owner group
2428 * @param name english name
2430 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2435 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2439 * \ingroup gdcmParser
2440 * \brief Build a new Element Value from all the low level arguments.
2441 * Check for existence of dictionary entry, and build
2442 * a default one when absent.
2443 * @param Group group of the underlying DictEntry
2444 * @param Elem element of the underlying DictEntry
2446 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2448 // Find out if the tag we encountered is in the dictionaries:
2449 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2451 DictEntry = NewVirtualDictEntry(Group, Elem);
2453 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2456 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2457 "failed to allocate gdcmHeaderEntry");
2463 // Never used; commented out, waiting for removal.
2465 * \ingroup gdcmParser
2466 * \brief Small utility function that creates a new manually crafted
2467 * (as opposed as read from the file) gdcmHeaderEntry with user
2468 * specified name and adds it to the public tag hash table.
2469 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2470 * @param NewTagName The name to be given to this new tag.
2471 * @param VR The Value Representation to be given to this new tag.
2472 * @return The newly hand crafted Element Value.
2474 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2477 // gdcmHeaderEntry *NewEntry = NULL;
2478 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2479 // guint32 FreeElem = 0;
2480 // gdcmDictEntry *DictEntry = NULL;
2482 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2483 // if (FreeElem == UINT32_MAX)
2485 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2486 // "Group 0xffff in Public Dict is full");
2490 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2491 // VR, "GDCM", NewTagName);
2492 // NewEntry = new gdcmHeaderEntry(DictEntry);
2493 // AddHeaderEntry(NewEntry);
2498 * \ingroup gdcmParser
2499 * \brief Generate a free TagKey i.e. a TagKey that is not present
2500 * in the TagHt dictionary.
2501 * @param group The generated tag must belong to this group.
2502 * @return The element of tag with given group which is fee.
2504 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2506 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2508 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2509 if (tagHT.count(key) == 0)
2515 //-----------------------------------------------------------------------------