2 //-----------------------------------------------------------------------------
3 #include "gdcmParser.h"
11 #include <netinet/in.h>
14 #ifdef GDCM_NO_ANSI_STRING_STREAM
16 # define ostringstream ostrstream
22 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
23 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
24 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
25 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
29 // ---> Warning : This fourth field is NOT part
30 // of the 'official' Dicom Dictionnary
31 // and should NOT be used.
32 // (Not defined for all the groups
33 // may be removed in a future release)
36 // META Meta Information
48 // NMI Nuclear Medicine
50 // BFS Basic Film Session
52 // BIB Basic Image Box
67 // Other usefull abreviations :
68 //Radiographic view associated with Patient Position (0018,5100).
71 // AP = Anterior/Posterior
72 // PA = Posterior/Anterior
75 // RLD = Right Lateral Decubitus
76 // LLD = Left Lateral Decubitus
77 // RLO = Right Lateral Oblique
78 // LLO = Left Lateral Oblique
80 //-----------------------------------------------------------------------------
81 // Refer to gdcmParser::CheckSwap()
82 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
84 // Refer to gdcmParser::SetMaxSizeLoadEntry()
85 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
87 // Refer to gdcmParser::SetMaxSizePrintEntry()
88 // TODO : Right now, better see "define, in gdcmHederEntry.cxx
89 const unsigned int gdcmParser::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
91 //-----------------------------------------------------------------------------
92 // Constructor / Destructor
97 * @param exception_on_error
98 * @param enable_sequences = true to allow the header
99 * to be parsed *inside* the SeQuences,
100 * when they have an actual length
101 * @param ignore_shadow to allow skipping the shadow elements,
102 * to save memory space.
103 * \warning The TRUE value for this param has to be used
104 * with a FALSE value for the 'enable_sequence' param.
105 * ('public elements' may be embedded in 'shadow Sequences')
107 gdcmParser::gdcmParser(const char *InFilename,
108 bool exception_on_error,
109 bool enable_sequences,
110 bool ignore_shadow) {
111 enableSequences=enable_sequences;
112 ignoreShadow =ignore_shadow;
114 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
115 filename = InFilename;
118 if ( !OpenFile(exception_on_error))
125 wasUpdated = 0; // will be set to 1 if user adds an entry
126 printLevel = 1; // 'Medium' print level by default
130 * \ingroup gdcmParser
132 * @param exception_on_error
134 gdcmParser::gdcmParser(bool exception_on_error) {
137 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
140 wasUpdated = 0; // will be set to 1 if user adds an entry
141 printLevel = 1; // 'Medium' print level by default
145 * \ingroup gdcmParser
146 * \brief Canonical destructor.
148 gdcmParser::~gdcmParser (void) {
153 //-----------------------------------------------------------------------------
156 * \ingroup gdcmParser
157 * \brief Prints the Header Entries (Dicom Elements)
158 * both from the H Table and the chained list
161 void gdcmParser::PrintEntry(std::ostream & os) {
162 std::ostringstream s;
164 for (ListTag::iterator i = listEntries.begin();
165 i != listEntries.end();
168 (*i)->SetPrintLevel(printLevel);
175 * \ingroup gdcmParser
176 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
179 void gdcmParser::PrintPubDict(std::ostream & os) {
180 RefPubDict->Print(os);
184 * \ingroup gdcmParser
185 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnry
188 void gdcmParser::PrintShaDict(std::ostream & os) {
189 RefShaDict->Print(os);
192 //-----------------------------------------------------------------------------
195 * \ingroup gdcmParser
196 * \brief Get the public dictionary used
198 gdcmDict *gdcmParser::GetPubDict(void) {
203 * \ingroup gdcmParser
204 * \brief Get the shadow dictionary used
206 gdcmDict *gdcmParser::GetShaDict(void) {
211 * \ingroup gdcmParser
212 * \brief Set the shadow dictionary used
213 * \param dict dictionary to use in shadow
215 bool gdcmParser::SetShaDict(gdcmDict *dict){
221 * \ingroup gdcmParser
222 * \brief Set the shadow dictionary used
223 * \param dictName name of the dictionary to use in shadow
225 bool gdcmParser::SetShaDict(DictKey dictName){
226 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
231 * \ingroup gdcmParser
232 * \brief This predicate, based on hopefully reasonable heuristics,
233 * decides whether or not the current gdcmParser was properly parsed
234 * and contains the mandatory information for being considered as
235 * a well formed and usable Dicom/Acr File.
236 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
239 bool gdcmParser::IsReadable(void) {
240 if(filetype==Unknown) {
243 if(listEntries.size()<=0) {
251 * \ingroup gdcmParser
252 * \brief Determines if the Transfer Syntax was already encountered
253 * and if it corresponds to a ImplicitVRLittleEndian one.
254 * @return True when ImplicitVRLittleEndian found. False in all other cases.
256 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
257 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
260 LoadHeaderEntrySafe(Element);
262 std::string Transfer = Element->GetValue();
263 if ( Transfer == UI1_2_840_10008_1_2 )
269 * \ingroup gdcmParser
270 * \brief Determines if the Transfer Syntax was already encountered
271 * and if it corresponds to a ExplicitVRLittleEndian one.
272 * @return True when ExplicitVRLittleEndian found. False in all other cases.
274 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
275 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
278 LoadHeaderEntrySafe(Element);
280 std::string Transfer = Element->GetValue();
281 if ( Transfer == UI1_2_840_10008_1_2_1 )
287 * \ingroup gdcmParser
288 * \brief Determines if the Transfer Syntax was already encountered
289 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
290 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
292 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
293 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
296 LoadHeaderEntrySafe(Element);
298 std::string Transfer = Element->GetValue();
299 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
305 * \ingroup gdcmParser
306 * \brief Determines if the Transfer Syntax was already encountered
307 * and if it corresponds to a Explicit VR Big Endian one.
308 * @return True when big endian found. False in all other cases.
310 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
311 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
314 LoadHeaderEntrySafe(Element);
316 std::string Transfer = Element->GetValue();
317 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
323 * \ingroup gdcmParser
324 * \brief returns the File Type
325 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
326 * @return the FileType code
328 FileType gdcmParser::GetFileType(void) {
333 * \ingroup gdcmParser
334 * \brief opens the file
335 * @param exception_on_error
338 FILE *gdcmParser::OpenFile(bool exception_on_error)
341 fp=fopen(filename.c_str(),"rb");
342 if(exception_on_error)
345 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
351 fread(&zero, (size_t)2, (size_t)1, fp);
353 //ACR -- or DICOM with no Preamble --
354 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
358 fseek(fp, 126L, SEEK_CUR);
360 fread(dicm, (size_t)4, (size_t)1, fp);
361 if( memcmp(dicm, "DICM", 4) == 0 )
365 dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
368 dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
374 * \ingroup gdcmParser
375 * \brief closes the file
376 * @return TRUE if the close was successfull
378 bool gdcmParser::CloseFile(void) {
379 int closed = fclose(fp);
387 * \ingroup gdcmParser
389 * @param fp file pointer on an already open file
390 * @param type type of the File to be written
391 * (ACR-NEMA, ExplicitVR, ImplicitVR)
392 * @return always "True" ?!
394 bool gdcmParser::Write(FILE *fp, FileType type) {
396 // TODO The stuff was rewritten using the chained list instead
398 // so we could remove the GroupHT from the gdcmParser
402 // TODO : move the following lines (and a lot of others, to be written)
403 // to a future function CheckAndCorrectHeader
406 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
407 // (FileType est un champ de gdcmParser ...)
408 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
410 // a moins de se livrer a un tres complique ajout des champs manquants.
411 // faire un CheckAndCorrectHeader (?)
414 if (type == ImplicitVR)
416 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
417 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
419 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
420 // values with a VR of UI shall be padded with a single trailing null
421 // Dans le cas suivant on doit pader manuellement avec un 0
423 SetEntryLengthByNumber(18, 0x0002, 0x0010);
426 if (type == ExplicitVR)
428 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
429 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
431 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
432 // values with a VR of UI shall be padded with a single trailing null
433 // Dans le cas suivant on doit pader manuellement avec un 0
435 SetEntryLengthByNumber(20, 0x0002, 0x0010);
438 /* TODO : rewrite later
440 if ( (type == ImplicitVR) || (type == ExplicitVR) )
441 UpdateGroupLength(false,type);
443 UpdateGroupLength(true,ACR);
446 WriteEntries(fp,type);
451 * \ingroup gdcmParser
452 * \brief Modifies the value of a given Header Entry (Dicom Element)
453 * if it exists; Creates it with the given value if it doesn't
454 * @param Value passed as a std::string
457 * \return false only if new element creation fails
459 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
462 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
463 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
468 SetEntryByNumber(Value, Group, Elem);
473 * \ingroup gdcmParser
474 * \brief Modifies the value of a given Header Entry (Dicom Element)
475 * if it exists; Creates it with the given value if it doesn't
476 * @param Value passed as a char*
477 * @param Group group of the Entry
478 * @param Elem element of the Entry
482 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
483 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
488 AddHeaderEntry(nvHeaderEntry);
490 std::string v = Value;
491 SetEntryByNumber(v, Group, Elem);
496 * \ingroup gdcmParser
497 * \brief Set a new value if the invoked element exists
498 * Seems to be useless !!!
499 * @param Value new element value
500 * @param Group group of the Entry
501 * @param Elem element of the Entry
504 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
506 std::string v = Value;
507 SetEntryByNumber(v, Group, Elem);
511 //-----------------------------------------------------------------------------
515 * \ingroup gdcmParser
516 * \brief Checks if a given Dicom Element exists
518 * @param group Group number of the searched Dicom Element
519 * @param element Element number of the searched Dicom Element
520 * @return number of occurences
522 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
523 std::string key = gdcmDictEntry::TranslateToKey(group, element );
524 return (tagHT.count(key));
528 * \ingroup gdcmParser
529 * \brief Searches within Header Entries (Dicom Elements) parsed with
530 * the public and private dictionaries
531 * for the element value of a given tag.
532 * \warning Don't use any longer : use GetPubEntryByName
533 * @param tagName name of the searched element.
534 * @return Corresponding element value when it exists,
535 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
537 std::string gdcmParser::GetEntryByName(std::string tagName) {
538 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
539 if( dictEntry == NULL)
542 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
546 * \ingroup gdcmParser
547 * \brief Searches within Header Entries (Dicom Elements) parsed with
548 * the public and private dictionaries
549 * for the element value representation of a given tag.
551 * Obtaining the VR (Value Representation) might be needed by caller
552 * to convert the string typed content to caller's native type
553 * (think of C++ vs Python). The VR is actually of a higher level
554 * of semantics than just the native C++ type.
555 * @param tagName name of the searched element.
556 * @return Corresponding element value representation when it exists,
557 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
559 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
560 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
561 if( dictEntry == NULL)
564 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
565 dictEntry->GetElement());
566 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 element value representation of a given tag.
575 * @param group Group of the searched tag.
576 * @param element Element of the searched tag.
577 * @return Corresponding element value representation when it exists,
578 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
580 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
581 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
582 if ( ! tagHT.count(key))
584 return tagHT.find(key)->second->GetValue();
588 * \ingroup gdcmParser
589 * \brief Searches within Header Entries (Dicom Elements) parsed with
590 * the public and private dictionaries
591 * for the element value representation of a given tag..
593 * Obtaining the VR (Value Representation) might be needed by caller
594 * to convert the string typed content to caller's native type
595 * (think of C++ vs Python). The VR is actually of a higher level
596 * of semantics than just the native C++ type.
597 * @param group Group of the searched tag.
598 * @param element Element of the searched tag.
599 * @return Corresponding element value representation when it exists,
600 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
602 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
603 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
606 return elem->GetVR();
610 * \ingroup gdcmParser
611 * \brief Searches within Header Entries (Dicom Elements) parsed with
612 * the public and private dictionaries
613 * for the value length of a given tag..
614 * @param group Group of the searched tag.
615 * @param element Element of the searched tag.
616 * @return Corresponding element length; -2 if not found
618 int gdcmParser::GetEntryLengthByNumber(guint16 group, guint16 element) {
619 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
622 return elem->GetLength();
625 * \ingroup gdcmParser
626 * \brief Sets the value (string) of the Header Entry (Dicom Element)
627 * @param content string value of the Dicom Element
628 * @param tagName name of the searched Dicom Element.
629 * @return true when found
631 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
632 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
633 if( dictEntry == NULL)
636 return(SetEntryByNumber(content,dictEntry->GetGroup(),
637 dictEntry->GetElement()));
641 * \ingroup gdcmParser
642 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
643 * through it's (group, element) and modifies it's content with
645 * \warning Don't use any longer : use SetPubEntryByNumber
646 * @param content new value to substitute with
647 * @param group group of the Dicom Element to modify
648 * @param element element of the Dicom Element to modify
650 bool gdcmParser::SetEntryByNumber(std::string content,
654 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
655 if ( ! tagHT.count(key))
657 int l = content.length();
658 if(l%2) // Non even length are padded with a space (020H).
661 content = content + '\0';
666 TagHeaderEntryHT::iterator p2;
667 // DO NOT remove the following lines : they explain the stuff
668 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
669 //p2=p.first; // iterator on the first synonym
670 //a=p2->second; // H Table target column (2-nd col)
673 a = ((tagHT.equal_range(key)).first)->second;
675 a-> SetValue(content);
677 std::string vr = a->GetVR();
680 if( (vr == "US") || (vr == "SS") )
682 else if( (vr == "UL") || (vr == "SL") )
692 * \ingroup gdcmParser
693 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
694 * in the PubHeaderEntrySet of this instance
695 * through it's (group, element) and modifies it's length with
697 * \warning Use with extreme caution.
698 * @param l new length to substitute with
699 * @param group group of the Entry to modify
700 * @param element element of the Entry to modify
701 * @return true on success, false otherwise.
703 bool gdcmParser::SetEntryLengthByNumber(guint32 l,
707 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
708 if ( ! tagHT.count(key))
710 if (l%2) l++; // length must be even
711 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
717 * \ingroup gdcmParser
718 * \brief Gets (from Header) the offset of a 'non string' element value
719 * (LoadElementValues has already be executed)
720 * @param Group group of the Entry
721 * @param Elem element of the Entry
722 * @return File Offset of the Element Value
724 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
726 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
729 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
730 "failed to Locate gdcmHeaderEntry");
733 return Entry->GetOffset();
737 * \ingroup gdcmParser
738 * \brief Gets (from Header) a 'non string' element value
739 * (LoadElementValues has already be executed)
740 * @param Group group of the Entry
741 * @param Elem element of the Entry
742 * @return Pointer to the 'non string' area
744 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
746 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
749 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
750 "failed to Locate gdcmHeaderEntry");
753 return Entry->GetVoidArea();
757 * \ingroup gdcmParser
758 * \brief Loads (from disk) the element content
759 * when a string is not suitable
760 * @param Group group of the Entry
761 * @param Elem element of the Entry
763 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
765 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
768 size_t o =(size_t)Element->GetOffset();
769 fseek(fp, o, SEEK_SET);
770 int l=Element->GetLength();
771 void * a = malloc(l);
775 SetEntryVoidAreaByNumber(a, Group, Elem);
776 // TODO check the result
777 size_t l2 = fread(a, 1, l ,fp);
788 * \ingroup gdcmParser
789 * \brief Sets a 'non string' value to a given Dicom Element
791 * @param group Group number of the searched Dicom Element
792 * @param element Element number of the searched Dicom Element
795 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
799 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
800 if ( ! tagHT.count(key))
802 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
807 * \ingroup gdcmParser
808 * \brief Update the entries with the shadow dictionary.
809 * Only non even entries are analyzed
811 void gdcmParser::UpdateShaEntries(void) {
812 gdcmDictEntry *entry;
815 for(ListTag::iterator it=listEntries.begin();
816 it!=listEntries.end();
819 // Odd group => from public dictionary
820 if((*it)->GetGroup()%2==0)
823 // Peer group => search the corresponding dict entry
825 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
829 if((*it)->IsImplicitVR())
834 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
836 // Set the new entry and the new value
837 (*it)->SetDictEntry(entry);
838 CheckHeaderEntryVR(*it,vr);
840 (*it)->SetValue(GetHeaderEntryValue(*it));
844 // Remove precedent value transformation
845 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
851 * \ingroup gdcmParser
852 * \brief Searches within the Header Entries for a Dicom Element of
854 * @param tagName name of the searched Dicom Element.
855 * @return Corresponding Dicom Element when it exists, and NULL
858 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
859 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
860 if( dictEntry == NULL)
863 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
867 * \ingroup gdcmParser
868 * \brief retrieves a Dicom Element (the first one) using (group, element)
869 * \warning (group, element) IS NOT an identifier inside the Dicom Header
870 * if you think it's NOT UNIQUE, check the count number
871 * and use iterators to retrieve ALL the Dicoms Elements within
872 * a given couple (group, element)
873 * @param group Group number of the searched Dicom Element
874 * @param element Element number of the searched Dicom Element
877 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
879 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
880 if ( ! tagHT.count(key))
882 return tagHT.find(key)->second;
886 * \ingroup gdcmParser
887 * \brief retrieves the Dicom Elements (all of them) using (group, element)
888 * @param group Group number of the searched Dicom Element.
889 * @param element Element number of the searched Dicom Element.
890 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
893 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
894 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
895 return (tagHT.equal_range(key));
899 * \ingroup gdcmParser
900 * \brief Loads the element while preserving the current
901 * underlying file position indicator as opposed to
902 * to LoadHeaderEntry that modifies it.
903 * @param entry Header Entry whose value shall be loaded.
906 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
907 long PositionOnEntry = ftell(fp);
908 LoadHeaderEntry(entry);
909 fseek(fp, PositionOnEntry, SEEK_SET);
913 * \ingroup gdcmParser
914 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
915 * \warning : to be re-written using the chained list instead of the H table.
916 * \warning : DO NOT use (doesn't work any longer because of the multimap)
917 * \todo : to be re-written using the chained list instead of the H table
918 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
919 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
921 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
925 gdcmHeaderEntry *elem;
927 std::string str_trash;
930 GroupHT groupHt; // to hold the length of each group
933 // typedef std::map<GroupKey, int> GroupHT;
935 gdcmHeaderEntry *elemZ;
937 // for each Tag in the DCM Header
939 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
944 gr = elem->GetGroup();
945 el = elem->GetElement();
948 sprintf(trash, "%04x", gr);
949 key = trash; // generate 'group tag'
951 // if the caller decided not to take SEQUENCEs into account
952 // e.g : he wants to write an ACR-NEMA File
954 if (SkipSequence && vr == "SQ")
957 // Still unsolved problem :
958 // we cannot find the 'Sequence Delimitation Item'
959 // since it's at the end of the Hash Table
962 // pas SEQUENCE en ACR-NEMA
964 // --> la descente a l'interieur' des SQ
965 // devrait etre faite avec une liste chainee, pas avec une HTable...
967 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
969 if (el == 0x0000) // the first elem is 0x0000
971 groupHt[key] = 0; // initialize group length
975 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
978 else // any elem but the first
980 if (type == ExplicitVR)
982 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
984 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
987 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
991 unsigned short int gr_bid;
993 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
997 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
998 // warning: unsigned int format, different type arg
999 sscanf(g->first.c_str(),"%x",&gr_bid);
1000 tk = g->first + "|0000"; // generate the element full tag
1002 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
1004 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
1005 elemZ = new gdcmHeaderEntry(tagZ);
1006 elemZ->SetLength(4);
1007 AddHeaderEntry(elemZ); // create it
1011 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
1013 sprintf(trash ,"%d",g->second);
1015 elemZ->SetValue(str_trash);
1020 * \ingroup gdcmParser
1021 * \brief writes on disc according to the requested format
1022 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1023 * \warning does NOT add the missing elements in the header :
1024 * it's up to the user doing it !
1025 * (function CheckHeaderCoherence to be written)
1026 * \warning DON'T try, right now, to write a DICOM image
1027 * from an ACR Header (meta elements will be missing!)
1028 * @param type type of the File to be written
1029 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1030 * @param _fp already open file pointer
1032 void gdcmParser::WriteEntries(FILE *_fp,FileType type)
1043 std::vector<std::string> tokens;
1045 // TODO : function CheckHeaderCoherence to be written
1047 // uses now listEntries to iterate, not TagHt!
1049 // pb : gdcmParser.Add does NOT update listEntries
1050 // TODO : find a trick (in STL?) to do it, at low cost !
1054 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1057 for (ListTag::iterator tag2=listEntries.begin();
1058 tag2 != listEntries.end();
1061 // === Deal with the length
1062 // --------------------
1063 if(((*tag2)->GetLength())%2==1)
1065 (*tag2)->SetValue((*tag2)->GetValue()+"\0");
1066 (*tag2)->SetLength((*tag2)->GetReadLength()+1);
1069 gr = (*tag2)->GetGroup();
1070 el = (*tag2)->GetElement();
1071 lgr = (*tag2)->GetReadLength();
1072 val = (*tag2)->GetValue().c_str();
1073 vr = (*tag2)->GetVR();
1074 voidArea = (*tag2)->GetVoidArea();
1078 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
1079 if (gr %2) continue; // ignore shadow groups
1080 if (vr == "SQ" ) continue; // ignore Sequences
1081 // TODO : find a trick to *skip* the SeQuences !
1082 // Not only ignore the SQ element
1083 if (gr == 0xfffe ) continue; // ignore delimiters
1086 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1087 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1089 if ( (type == ExplicitVR) || (type == DICOMDIR) ) {
1091 guint16 z=0, shortLgr;
1093 if (gr == 0xfffe) { // NO Value Representation for 'delimiters'
1094 // no length : write ffffffff
1095 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1096 continue; // NO value for 'delimiters'
1100 if (vr == "unkn") { // Unknown was 'written'
1101 // deal with Little Endian
1102 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1103 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1105 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1106 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ){
1107 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1108 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1110 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1116 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1119 // === Deal with the value
1120 // -------------------
1121 if (vr == "SQ") continue; // no "value" to write for the SEQuences
1122 if (gr == 0xfffe)continue; // no "value" to write for the delimiters
1124 if (voidArea != NULL)
1125 { // there is a 'non string' LUT, overlay, etc
1126 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1130 if (vr == "US" || vr == "SS")
1132 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1133 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1134 for (unsigned int i=0; i<tokens.size();i++)
1136 val_uint16 = atoi(tokens[i].c_str());
1138 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1143 if (vr == "UL" || vr == "SL")
1145 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1146 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1147 for (unsigned int i=0; i<tokens.size();i++)
1149 val_uint32 = atoi(tokens[i].c_str());
1151 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1157 // Pixels are never loaded in the element !
1158 // we stop writting when Pixel are processed
1159 // FIX : we loose trailing elements (RAB, right now)
1161 if ((gr == GrPixel) && (el == NumPixel) ) {
1163 if (compte == countGrPixel) // we passed *all* the GrPixel,NumPixel
1166 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1172 * \ingroup gdcmParser
1173 * \brief writes on disc according to the requested format
1174 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1175 * \warning Uses the H Table, instead of the Chained List
1176 * in order to be compliant with the old way to proceed
1177 * (added elements taken in to account)
1178 * Only THERALYS, during a transitory phase is supposed
1179 * to use this method !!!
1180 * \warning DON'T try, right now, to write a DICOM image
1181 * from an ACR Header (meta elements will be missing!)
1182 * @param _fp already open file pointer
1183 * @param type type of the File to be written
1184 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1186 void gdcmParser::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1194 std::vector<std::string> tokens;
1198 // Tout ceci ne marche QUE parce qu'on est sur un proc Little Endian
1199 // restent a tester les echecs en ecriture (apres chaque fwrite)
1201 for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1202 tag2 != tagHT.end();
1205 gr = tag2->second->GetGroup();
1206 el = tag2->second->GetElement();
1207 lgr = tag2->second->GetLength();
1208 val = tag2->second->GetValue().c_str();
1209 vr = tag2->second->GetVR();
1211 // std::cout << "Tag "<< std::hex << gr << " " << el << std::endl;
1213 if ( type == ACR ) {
1214 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
1215 if (gr %2) continue; // ignore shadow groups
1216 if (vr == "SQ" ) continue; // ignore Sequences
1217 if (gr == 0xfffe ) continue; // ignore delimiters
1220 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1221 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1223 if ( (type == ExplicitVR) && (gr <= 0x0002) ) {
1225 guint16 z=0, shortLgr;
1226 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1228 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) {
1229 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1230 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1234 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1236 } else { // IMPLICIT VR
1237 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1240 if (vr == "US" || vr == "SS") {
1241 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1242 Tokenize (tag2->second->GetValue(), tokens, "\\");
1243 for (unsigned int i=0; i<tokens.size();i++) {
1244 val_uint16 = atoi(tokens[i].c_str());
1246 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1251 if (vr == "UL" || vr == "SL") {
1252 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1253 Tokenize (tag2->second->GetValue(), tokens, "\\");
1254 for (unsigned int i=0; i<tokens.size();i++) {
1255 val_uint32 = atoi(tokens[i].c_str());
1257 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1262 // Pixels are never loaded in the element !
1263 if ((gr == 0x7fe0) && (el == 0x0010) ) break;
1265 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1275 * \ingroup gdcmParser
1276 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1278 * @return The properly swaped 32 bits integer.
1280 guint32 gdcmParser::SwapLong(guint32 a) {
1285 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1286 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1290 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1294 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1297 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1304 * \ingroup gdcmParser
1305 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1307 * @return The properly unswaped 32 bits integer.
1309 guint32 gdcmParser::UnswapLong(guint32 a) {
1310 return (SwapLong(a));
1314 * \ingroup gdcmParser
1315 * \brief Swaps the bytes so they agree with the processor order
1316 * @return The properly swaped 16 bits integer.
1318 guint16 gdcmParser::SwapShort(guint16 a) {
1319 if ( (sw==4321) || (sw==2143) )
1320 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1325 * \ingroup gdcmParser
1326 * \brief Unswaps the bytes so they agree with the processor order
1327 * @return The properly unswaped 16 bits integer.
1329 guint16 gdcmParser::UnswapShort(guint16 a) {
1330 return (SwapShort(a));
1333 //-----------------------------------------------------------------------------
1336 * \ingroup gdcmParser
1337 * \brief Parses the header of the file but WITHOUT loading element values.
1338 * @return false if file is not ACR-NEMA / DICOM
1340 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1346 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1347 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1348 SkipHeaderEntry(newHeaderEntry);
1349 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1350 AddHeaderEntry(newHeaderEntry);
1357 * \ingroup gdcmParser
1358 * \brief Loads the element values of all the Header Entries pointed in the
1359 * public Chained List.
1361 void gdcmParser::LoadHeaderEntries(void) {
1363 for (ListTag::iterator i = GetListEntry().begin();
1364 i != GetListEntry().end();
1367 LoadHeaderEntry(*i);
1372 // Load 'non string' values
1373 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1374 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1375 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1376 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1377 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1378 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1380 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1381 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1382 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1384 //FIXME : how to use it?
1385 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1387 // --------------------------------------------------------------
1388 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1390 // if recognition code tells us we deal with a LibIDO image
1391 // we switch lineNumber and columnNumber
1393 std::string RecCode;
1394 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1395 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1396 RecCode == "CANRME_AILIBOD1_1." )
1398 filetype = ACR_LIBIDO;
1399 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1400 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1401 SetEntryByNumber(columns, 0x0028, 0x0010);
1402 SetEntryByNumber(rows , 0x0028, 0x0011);
1404 // ----------------- End of Special Patch ----------------
1408 * \ingroup gdcmParser
1409 * \brief Loads the element content if its length doesn't exceed
1410 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1411 * @param Entry Header Entry (Dicom Element) to be dealt with
1413 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1415 guint16 group = Entry->GetGroup();
1416 std::string vr= Entry->GetVR();
1417 guint32 length = Entry->GetLength();
1418 bool SkipLoad = false;
1420 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1422 // the test was commented out to 'go inside' the SeQuences
1423 // we don't any longer skip them !
1425 // if( vr == "SQ" ) // (DO NOT remove this comment)
1428 // A SeQuence "contains" a set of Elements.
1429 // (fffe e000) tells us an Element is beginning
1430 // (fffe e00d) tells us an Element just ended
1431 // (fffe e0dd) tells us the current SeQuence just ended
1432 if( group == 0xfffe )
1436 Entry->SetLength(0);
1437 Entry->SetValue("gdcm::Skipped");
1441 // When the length is zero things are easy:
1442 if ( length == 0 ) {
1443 Entry->SetValue("");
1447 // The elements whose length is bigger than the specified upper bound
1448 // are not loaded. Instead we leave a short notice of the offset of
1449 // the element content and it's length.
1450 if (length > MaxSizeLoadEntry) {
1451 std::ostringstream s;
1452 s << "gdcm::NotLoaded.";
1453 s << " Address:" << (long)Entry->GetOffset();
1454 s << " Length:" << Entry->GetLength();
1455 s << " x(" << std::hex << Entry->GetLength() << ")";
1456 Entry->SetValue(s.str());
1460 // When integer(s) are expected, read and convert the following
1461 // n *(two or four bytes)
1462 // properly i.e. as integers as opposed to strings.
1463 // Elements with Value Multiplicity > 1
1464 // contain a set of integers (not a single one)
1466 // Any compacter code suggested (?)
1467 if ( IsHeaderEntryAnInteger(Entry) ) {
1469 std::ostringstream s;
1471 if (vr == "US" || vr == "SS") {
1473 NewInt = ReadInt16();
1476 for (int i=1; i < nbInt; i++) {
1478 NewInt = ReadInt16();
1483 else if (vr == "UL" || vr == "SL") {
1485 NewInt = ReadInt32();
1488 for (int i=1; i < nbInt; i++) {
1490 NewInt = ReadInt32();
1495 #ifdef GDCM_NO_ANSI_STRING_STREAM
1496 s << std::ends; // to avoid oddities on Solaris
1497 #endif //GDCM_NO_ANSI_STRING_STREAM
1499 Entry->SetValue(s.str());
1503 // We need an additional byte for storing \0 that is not on disk
1504 std::string NewValue(length,0);
1505 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1506 if ( item_read != 1 ) {
1507 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1508 Entry->SetValue("gdcm::UnRead");
1512 if( (vr == "UI") ) // Because of correspondance with the VR dic
1513 Entry->SetValue(NewValue.c_str()); // ??? JPR ???
1515 Entry->SetValue(NewValue);
1519 * \ingroup gdcmParser
1520 * \brief add a new Dicom Element pointer to
1521 * the H Table and to the chained List
1522 * \warning push_bash in listEntries ONLY during ParseHeader
1523 * \todo something to allow further Elements addition,
1524 * (at their right place in the chained list)
1525 * when position to be taken care of
1526 * @param newHeaderEntry
1528 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1529 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1530 listEntries.push_back(newHeaderEntry);
1535 * \ingroup gdcmParser
1537 * @param Entry Header Entry whose length of the value shall be loaded.
1540 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1541 guint16 element = Entry->GetElement();
1542 guint16 group = Entry->GetGroup();
1543 std::string vr = Entry->GetVR();
1546 if( (element == NumPixel) && (group == GrPixel) )
1548 dbg.SetDebug(GDCM_DEBUG);
1549 dbg.Verbose(2, "gdcmParser::FindLength: ",
1550 "we reached (GrPixel,NumPixel)");
1553 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1555 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1557 // The following reserved two bytes (see PS 3.5-2001, section
1558 // 7.1.2 Data element structure with explicit vr p27) must be
1559 // skipped before proceeding on reading the length on 4 bytes.
1560 fseek(fp, 2L, SEEK_CUR);
1561 guint32 length32 = ReadInt32();
1563 if ( (vr == "OB") && (length32 == 0xffffffff) )
1565 Entry->SetLength(FindHeaderEntryLengthOB());
1568 FixHeaderEntryFoundLength(Entry, length32);
1572 // Length is encoded on 2 bytes.
1573 length16 = ReadInt16();
1575 // We can tell the current file is encoded in big endian (like
1576 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1577 // and it's value is the one of the encoding of a big endian file.
1578 // In order to deal with such big endian encoded files, we have
1579 // (at least) two strategies:
1580 // * when we load the "Transfer Syntax" tag with value of big endian
1581 // encoding, we raise the proper flags. Then we wait for the end
1582 // of the META group (0x0002) among which is "Transfer Syntax",
1583 // before switching the swap code to big endian. We have to postpone
1584 // the switching of the swap code since the META group is fully encoded
1585 // in little endian, and big endian coding only starts at the next
1586 // group. The corresponding code can be hard to analyse and adds
1587 // many additional unnecessary tests for regular tags.
1588 // * the second strategy consists in waiting for trouble, that shall
1589 // appear when we find the first group with big endian encoding. This
1590 // is easy to detect since the length of a "Group Length" tag (the
1591 // ones with zero as element number) has to be of 4 (0x0004). When we
1592 // encounter 1024 (0x0400) chances are the encoding changed and we
1593 // found a group with big endian encoding.
1594 // We shall use this second strategy. In order to make sure that we
1595 // can interpret the presence of an apparently big endian encoded
1596 // length of a "Group Length" without committing a big mistake, we
1597 // add an additional check: we look in the already parsed elements
1598 // for the presence of a "Transfer Syntax" whose value has to be "big
1599 // endian encoding". When this is the case, chances are we have got our
1600 // hands on a big endian encoded file: we switch the swap code to
1601 // big endian and proceed...
1602 if ( (element == 0x0000) && (length16 == 0x0400) )
1604 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1606 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1611 SwitchSwapToBigEndian();
1612 // Restore the unproperly loaded values i.e. the group, the element
1613 // and the dictionary entry depending on them.
1614 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1615 guint16 CorrectElem = SwapShort(Entry->GetElement());
1616 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1620 // This correct tag is not in the dictionary. Create a new one.
1621 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1623 // FIXME this can create a memory leaks on the old entry that be
1624 // left unreferenced.
1625 Entry->SetDictEntry(NewTag);
1628 // Heuristic: well some files are really ill-formed.
1629 if ( length16 == 0xffff)
1632 //dbg.Verbose(0, "gdcmParser::FindLength",
1633 // "Erroneous element length fixed.");
1634 // Actually, length= 0xffff means that we deal with
1635 // Unknown Sequence Length
1637 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1642 // Either implicit VR or a non DICOM conformal (see note below) explicit
1643 // VR that ommited the VR of (at least) this element. Farts happen.
1644 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1645 // on Data elements "Implicit and Explicit VR Data Elements shall
1646 // not coexist in a Data Set and Data Sets nested within it".]
1647 // Length is on 4 bytes.
1649 FixHeaderEntryFoundLength(Entry, ReadInt32());
1655 * \ingroup gdcmParser
1656 * \brief Find the Value Representation of the current Dicom Element.
1659 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1661 if (filetype != ExplicitVR)
1666 long PositionOnEntry = ftell(fp);
1667 // Warning: we believe this is explicit VR (Value Representation) because
1668 // we used a heuristic that found "UL" in the first tag. Alas this
1669 // doesn't guarantee that all the tags will be in explicit VR. In some
1670 // cases (see e-film filtered files) one finds implicit VR tags mixed
1671 // within an explicit VR file. Hence we make sure the present tag
1672 // is in explicit VR and try to fix things if it happens not to be
1675 int lgrLue=fread (&VR, (size_t)2,(size_t)1, fp); // lgrLue not used
1677 if(!CheckHeaderEntryVR(Entry,VR))
1679 fseek(fp, PositionOnEntry, SEEK_SET);
1680 // When this element is known in the dictionary we shall use, e.g. for
1681 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1682 // dictionary entry. Still we have to flag the element as implicit since
1683 // we know now our assumption on expliciteness is not furfilled.
1685 if ( Entry->IsVRUnknown() )
1686 Entry->SetVR("Implicit");
1687 Entry->SetImplicitVR();
1692 * \ingroup gdcmParser
1693 * \brief Check the correspondance between the VR of the header entry
1694 * and the taken VR. If they are different, the header entry is
1695 * updated with the new VR.
1696 * @param Entry Header Entry to check
1697 * @param vr Dicom Value Representation
1698 * @return false if the VR is incorrect of if the VR isn't referenced
1699 * otherwise, it returns true
1701 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1703 char msg[100]; // for sprintf
1704 bool RealExplicit = true;
1706 // Assume we are reading a falsely explicit VR file i.e. we reached
1707 // a tag where we expect reading a VR but are in fact we read the
1708 // first to bytes of the length. Then we will interogate (through find)
1709 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1710 // both GCC and VC++ implementations of the STL map. Hence when the
1711 // expected VR read happens to be non-ascii characters we consider
1712 // we hit falsely explicit VR tag.
1714 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1715 RealExplicit = false;
1717 // CLEANME searching the dicom_vr at each occurence is expensive.
1718 // PostPone this test in an optional integrity check at the end
1719 // of parsing or only in debug mode.
1720 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1721 RealExplicit= false;
1723 if ( !RealExplicit )
1725 // We thought this was explicit VR, but we end up with an
1726 // implicit VR tag. Let's backtrack.
1727 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1728 Entry->GetGroup(),Entry->GetElement());
1729 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1730 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1731 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1732 Entry->GetGroup(),Entry->GetElement(),
1733 "UL","FIXME","Group Length");
1734 Entry->SetDictEntry(NewEntry);
1739 if ( Entry->IsVRUnknown() )
1741 // When not a dictionary entry, we can safely overwrite the VR.
1742 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1748 else if ( Entry->GetVR() != vr )
1750 // The VR present in the file and the dictionary disagree. We assume
1751 // the file writer knew best and use the VR of the file. Since it would
1752 // be unwise to overwrite the VR of a dictionary (since it would
1753 // compromise it's next user), we need to clone the actual DictEntry
1754 // and change the VR for the read one.
1755 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1756 Entry->GetGroup(),Entry->GetElement(),
1757 vr,"FIXME",Entry->GetName());
1758 Entry->SetDictEntry(NewEntry);
1764 * \ingroup gdcmParser
1765 * \brief Get the transformed value of the header entry. The VR value
1766 * is used to define the transformation to operate on the value
1767 * \warning NOT end user intended method !
1769 * @return Transformed entry value
1771 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1773 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1775 std::string val=Entry->GetValue();
1776 std::string vr=Entry->GetVR();
1777 guint32 length = Entry->GetLength();
1778 std::ostringstream s;
1781 if (vr == "US" || vr == "SS")
1786 for (int i=0; i < nbInt; i++)
1790 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1791 NewInt16 = SwapShort(NewInt16);
1796 else if (vr == "UL" || vr == "SL")
1801 for (int i=0; i < nbInt; i++)
1805 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1806 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1807 NewInt32=SwapLong(NewInt32);
1811 #ifdef GDCM_NO_ANSI_STRING_STREAM
1812 s << std::ends; // to avoid oddities on Solaris
1813 #endif //GDCM_NO_ANSI_STRING_STREAM
1817 return(Entry->GetValue());
1821 * \ingroup gdcmParser
1822 * \brief Get the reverse transformed value of the header entry. The VR
1823 * value is used to define the reverse transformation to operate on
1825 * \warning NOT end user intended method !
1827 * @return Reverse transformed entry value
1829 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1831 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1833 std::string vr=Entry->GetVR();
1834 std::ostringstream s;
1835 std::vector<std::string> tokens;
1837 if (vr == "US" || vr == "SS")
1841 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1842 Tokenize (Entry->GetValue(), tokens, "\\");
1843 for (unsigned int i=0; i<tokens.size();i++)
1845 NewInt16 = atoi(tokens[i].c_str());
1846 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1850 if (vr == "UL" || vr == "SL")
1854 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1855 Tokenize (Entry->GetValue(), tokens, "\\");
1856 for (unsigned int i=0; i<tokens.size();i++)
1858 NewInt32 = atoi(tokens[i].c_str());
1859 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1860 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1865 #ifdef GDCM_NO_ANSI_STRING_STREAM
1866 s << std::ends; // to avoid oddities on Solaris
1867 #endif //GDCM_NO_ANSI_STRING_STREAM
1871 return(Entry->GetValue());
1875 * \ingroup gdcmParser
1876 * \brief Skip a given Header Entry
1877 * \warning NOT end user intended method !
1880 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1882 SkipBytes(entry->GetLength());
1886 * \ingroup gdcmParser
1887 * \brief When the length of an element value is obviously wrong (because
1888 * the parser went Jabberwocky) one can hope improving things by
1889 * applying this heuristic.
1891 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1893 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1895 if ( FoundLength == 0xffffffff) {
1899 guint16 gr =Entry->GetGroup();
1900 guint16 el =Entry->GetElement();
1902 if (FoundLength%2) {
1903 std::ostringstream s;
1904 s << "Warning : Tag with uneven length " << FoundLength
1905 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1906 dbg.Verbose(0,s.str().c_str());
1909 // Sorry for the patch!
1910 // XMedCom did the trick to read some nasty GE images ...
1911 if (FoundLength == 13) {
1912 // The following 'if' will be removed when there is no more
1913 // images on Creatis HDs with a 13 length for Manufacturer...
1914 if ( (Entry->GetGroup() != 0x0008) ||
1915 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1916 // end of remove area
1918 Entry->SetReadLength(10); // a bug is to be fixed
1922 // to fix some garbage 'Leonardo' Siemens images
1923 // May be commented out to avoid overhead
1924 else if ( (Entry->GetGroup() == 0x0009) &&
1925 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1927 Entry->SetReadLength(4); // a bug is to be fixed
1931 // to try to 'go inside' SeQuences (with length), and not to skip them
1932 else if ( Entry->GetVR() == "SQ")
1934 if (enableSequences) // only if the user does want to !
1935 FoundLength =0; // ReadLength is unchanged
1938 // a SeQuence Element is beginning
1939 // Let's forget it's length
1940 // (we want to 'go inside')
1942 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1943 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1944 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1945 // if we don't, we lost 28800 characters from the Header :-(
1947 else if(Entry->GetGroup() == 0xfffe)
1949 // cout << "ReadLength " <<Entry->GetReadLength() << " UsableLength " << FoundLength << endl;
1951 // sometimes, length seems to be wrong
1952 FoundLength =0; // some more clever checking to be done !
1954 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1955 // causes troubles :-(
1958 Entry->SetUsableLength(FoundLength);
1962 * \ingroup gdcmParser
1963 * \brief Apply some heuristics to predict wether the considered
1964 * element value contains/represents an integer or not.
1965 * @param Entry The element value on which to apply the predicate.
1966 * @return The result of the heuristical predicate.
1968 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1969 guint16 element = Entry->GetElement();
1970 guint16 group = Entry->GetGroup();
1971 std::string vr = Entry->GetVR();
1972 guint32 length = Entry->GetLength();
1973 // When we have some semantics on the element we just read, and if we
1974 // a priori know we are dealing with an integer, then we shall be
1975 // able to swap it's element value properly.
1976 if ( element == 0 ) // This is the group length of the group
1982 std::ostringstream s;
1983 int filePosition = ftell(fp);
1984 s << "Erroneous Group Length element length on : (" \
1985 << std::hex << group << " , " << element
1986 << ") -before- position x(" << filePosition << ")"
1987 << "lgt : " << length;
1988 // These 2 lines commented out : a *very dirty* patch
1989 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1990 // have a glance at offset x(8336) ...
1991 // For *regular* headers, the test is useless..
1992 // lets's print a warning message and go on,
1993 // instead of giving up with an error message
1995 //std::cout << s.str().c_str() << std::endl;
1997 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1998 // s.str().c_str());
2001 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2008 * \ingroup gdcmParser
2010 * \warning NOT end user intended method !
2013 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
2014 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2017 long PositionOnEntry = ftell(fp);
2018 bool FoundSequenceDelimiter = false;
2019 guint32 TotalLength = 0;
2022 while ( ! FoundSequenceDelimiter)
2028 TotalLength += 4; // We even have to decount the group and element
2030 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
2032 char msg[100]; // for sprintf. Sorry
2033 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2034 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
2038 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
2039 FoundSequenceDelimiter = true;
2040 else if ( n != 0xe000 )
2042 char msg[100]; // for sprintf. Sorry
2043 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2045 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
2049 ItemLength = ReadInt32();
2050 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2051 // the ItemLength with ReadInt32
2052 SkipBytes(ItemLength);
2054 fseek(fp, PositionOnEntry, SEEK_SET);
2059 * \ingroup gdcmParser
2060 * \brief Reads a supposed to be 16 Bits integer
2061 * (swaps it depending on processor endianity)
2062 * @return read value
2064 guint16 gdcmParser::ReadInt16(void) {
2067 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2068 if ( item_read != 1 ) {
2070 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
2080 * \ingroup gdcmParser
2081 * \brief Reads a supposed to be 32 Bits integer
2082 * (swaps it depending on processor endianity)
2083 * @return read value
2085 guint32 gdcmParser::ReadInt32(void) {
2088 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2089 if ( item_read != 1 ) {
2091 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
2101 * \ingroup gdcmParser
2103 * \warning NOT end user intended method !
2106 void gdcmParser::SkipBytes(guint32 NBytes) {
2107 //FIXME don't dump the returned value
2108 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2112 * \ingroup gdcmParser
2115 void gdcmParser::Initialise(void)
2117 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2118 RefShaDict = (gdcmDict*)0;
2122 * \ingroup gdcmParser
2123 * \brief Discover what the swap code is (among little endian, big endian,
2124 * bad little endian, bad big endian).
2126 * @return false when we are absolutely sure
2127 * it's neither ACR-NEMA nor DICOM
2128 * true when we hope ours assuptions are OK
2130 bool gdcmParser::CheckSwap() {
2132 // The only guaranted way of finding the swap code is to find a
2133 // group tag since we know it's length has to be of four bytes i.e.
2134 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2135 // occurs when we can't find such group...
2137 guint32 x=4; // x : for ntohs
2138 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2144 char deb[HEADER_LENGTH_TO_READ];
2146 // First, compare HostByteOrder and NetworkByteOrder in order to
2147 // determine if we shall need to swap bytes (i.e. the Endian type).
2153 // The easiest case is the one of a DICOM header, since it possesses a
2154 // file preamble where it suffice to look for the string "DICM".
2155 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2158 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2159 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2161 // Next, determine the value representation (VR). Let's skip to the
2162 // first element (0002, 0000) and check there if we find "UL"
2163 // - or "OB" if the 1st one is (0002,0001) -,
2164 // in which case we (almost) know it is explicit VR.
2165 // WARNING: if it happens to be implicit VR then what we will read
2166 // is the length of the group. If this ascii representation of this
2167 // length happens to be "UL" then we shall believe it is explicit VR.
2168 // FIXME: in order to fix the above warning, we could read the next
2169 // element value (or a couple of elements values) in order to make
2170 // sure we are not commiting a big mistake.
2171 // We need to skip :
2172 // * the 128 bytes of File Preamble (often padded with zeroes),
2173 // * the 4 bytes of "DICM" string,
2174 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2175 // i.e. a total of 136 bytes.
2179 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2180 // but elem 0002,0010 (Transfert Syntax) tells us the file is *Implicit* VR.
2183 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2184 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2185 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2186 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2187 // when Write DCM *adds*
2189 // Use gdcmParser::dicom_vr to test all the possibilities
2190 // instead of just checking for UL, OB and UI !? // group 0000
2193 filetype = ExplicitVR;
2194 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2195 "explicit Value Representation");
2199 filetype = ImplicitVR;
2200 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2201 "not an explicit Value Representation");
2207 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2208 "HostByteOrder != NetworkByteOrder");
2213 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2214 "HostByteOrder = NetworkByteOrder");
2217 // Position the file position indicator at first tag (i.e.
2218 // after the file preamble and the "DICM" string).
2220 fseek (fp, 132L, SEEK_SET);
2224 // Alas, this is not a DicomV3 file and whatever happens there is no file
2225 // preamble. We can reset the file position indicator to where the data
2226 // is (i.e. the beginning of the file).
2227 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2230 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2231 // By clean we mean that the length of the first tag is written down.
2232 // If this is the case and since the length of the first group HAS to be
2233 // four (bytes), then determining the proper swap code is straightforward.
2236 // We assume the array of char we are considering contains the binary
2237 // representation of a 32 bits integer. Hence the following dirty
2239 s32 = *((guint32 *)(entCur));
2260 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2261 // It is time for despaired wild guesses.
2262 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2263 // i.e. the 'group length' element is not present :
2265 // check the supposed to be 'group number'
2266 // 0x0002 or 0x0004 or 0x0008
2267 // to determine ' sw' value .
2268 // Only 0 or 4321 will be possible
2269 // (no oportunity to check for the formerly well known
2270 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2271 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2272 // the file IS NOT ACR-NEMA nor DICOM V3
2273 // Find a trick to tell it the caller...
2275 s16 = *((guint16 *)(deb));
2291 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2292 "ACR/NEMA unfound swap info (Really hopeless !)");
2297 // Then the only info we have is the net2host one.
2307 * \ingroup gdcmParser
2310 void gdcmParser::SwitchSwapToBigEndian(void)
2312 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2313 "Switching to BigEndian mode.");
2334 * \ingroup gdcmParser
2335 * \brief during parsing, Header Elements too long are not loaded in memory
2338 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2342 if ((guint32)NewSize >= (guint32)0xffffffff)
2344 MaxSizeLoadEntry = 0xffffffff;
2347 MaxSizeLoadEntry = NewSize;
2352 * \ingroup gdcmParser
2353 * \brief Header Elements too long will not be printed
2355 * \todo : not yet usable
2356 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2357 * in gdcmHeaderEntry gdcmLoadEntry)
2361 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2365 if ((guint32)NewSize >= (guint32)0xffffffff)
2367 MaxSizePrintEntry = 0xffffffff;
2370 MaxSizePrintEntry = NewSize;
2374 * \ingroup gdcmParser
2375 * \brief Searches both the public and the shadow dictionary (when they
2376 * exist) for the presence of the DictEntry with given name.
2377 * The public dictionary has precedence on the shadow one.
2378 * @param Name name of the searched DictEntry
2379 * @return Corresponding DictEntry when it exists, NULL otherwise.
2381 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2383 gdcmDictEntry *found = (gdcmDictEntry *)0;
2384 if (!RefPubDict && !RefShaDict)
2386 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2387 "we SHOULD have a default dictionary");
2391 found = RefPubDict->GetDictEntryByName(Name);
2397 found = RefShaDict->GetDictEntryByName(Name);
2405 * \ingroup gdcmParser
2406 * \brief Searches both the public and the shadow dictionary (when they
2407 * exist) for the presence of the DictEntry with given
2408 * group and element. The public dictionary has precedence on the
2410 * @param group group of the searched DictEntry
2411 * @param element element of the searched DictEntry
2412 * @return Corresponding DictEntry when it exists, NULL otherwise.
2414 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2416 gdcmDictEntry *found = (gdcmDictEntry *)0;
2417 if (!RefPubDict && !RefShaDict)
2419 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2420 "we SHOULD have a default dictionary");
2424 found = RefPubDict->GetDictEntryByNumber(group, element);
2430 found = RefShaDict->GetDictEntryByNumber(group, element);
2438 * \ingroup gdcmParser
2439 * \brief Read the next tag but WITHOUT loading it's value
2440 * @return On succes the newly created HeaderEntry, NULL on failure.
2442 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2444 gdcmHeaderEntry *NewEntry;
2449 // We reached the EOF (or an error occured) therefore
2450 // header parsing has to be considered as finished.
2451 return (gdcmHeaderEntry *)0;
2453 /* Pb : how to propagate the element length (used in SkipHeaderEntry)
2454 // direct call to SkipBytes ?
2456 if (ignoreShadow == 1 && g%2 ==1) //JPR
2457 // if user wants to skip shadow groups
2458 // and current element *is* a shadow element
2459 // we don't create anything
2460 return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2462 NewEntry = NewHeaderEntryByNumber(g, n);
2463 FindHeaderEntryVR(NewEntry);
2464 FindHeaderEntryLength(NewEntry);
2470 NewEntry->SetOffset(ftell(fp));
2475 * \ingroup gdcmParser
2476 * \brief Build a new Element Value from all the low level arguments.
2477 * Check for existence of dictionary entry, and build
2478 * a default one when absent.
2479 * @param Name Name of the underlying DictEntry
2481 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2483 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2485 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2487 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2490 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2491 "failed to allocate gdcmHeaderEntry");
2492 return (gdcmHeaderEntry *)0;
2498 * \ingroup gdcmParser
2499 * \brief Request a new virtual dict entry to the dict set
2500 * @param group group of the underlying DictEntry
2501 * @param element element of the underlying DictEntry
2502 * @param vr VR of the underlying DictEntry
2503 * @param fourth owner group
2504 * @param name english name
2506 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2511 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2515 * \ingroup gdcmParser
2516 * \brief Build a new Element Value from all the low level arguments.
2517 * Check for existence of dictionary entry, and build
2518 * a default one when absent.
2519 * @param Group group of the underlying DictEntry
2520 * @param Elem element of the underlying DictEntry
2522 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2524 // Find out if the tag we encountered is in the dictionaries:
2525 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2527 DictEntry = NewVirtualDictEntry(Group, Elem);
2529 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2532 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2533 "failed to allocate gdcmHeaderEntry");
2539 // Never used; commented out, waiting for removal.
2541 * \ingroup gdcmParser
2542 * \brief Small utility function that creates a new manually crafted
2543 * (as opposed as read from the file) gdcmHeaderEntry with user
2544 * specified name and adds it to the public tag hash table.
2545 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2546 * @param NewTagName The name to be given to this new tag.
2547 * @param VR The Value Representation to be given to this new tag.
2548 * @return The newly hand crafted Element Value.
2550 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2553 // gdcmHeaderEntry *NewEntry = NULL;
2554 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2555 // guint32 FreeElem = 0;
2556 // gdcmDictEntry *DictEntry = NULL;
2558 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2559 // if (FreeElem == UINT32_MAX)
2561 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2562 // "Group 0xffff in Public Dict is full");
2566 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2567 // VR, "GDCM", NewTagName);
2568 // NewEntry = new gdcmHeaderEntry(DictEntry);
2569 // AddHeaderEntry(NewEntry);
2574 * \ingroup gdcmParser
2575 * \brief Generate a free TagKey i.e. a TagKey that is not present
2576 * in the TagHt dictionary.
2577 * @param group The generated tag must belong to this group.
2578 * @return The element of tag with given group which is fee.
2580 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2582 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2584 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2585 if (tagHT.count(key) == 0)
2591 //-----------------------------------------------------------------------------