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
47 * @param inFilename file to be opened for parsing
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 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
53 * @param ignore_shadow to allow skipping the shadow elements,
54 * to save memory space.
55 * \warning The TRUE value for this param has to be used
56 * with a FALSE value for the 'enable_sequence' param.
57 * ('public elements' may be embedded in 'shadow Sequences')
59 gdcmParser::gdcmParser(const char *inFilename,
60 bool exception_on_error,
61 bool enable_sequences,
63 enableSequences=enable_sequences;
64 ignoreShadow =ignore_shadow;
66 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
67 filename = inFilename;
70 if ( !OpenFile(exception_on_error))
77 wasUpdated = 0; // will be set to 1 if user adds an entry
78 printLevel = 1; // 'Medium' print level by default
84 * @param exception_on_error
86 gdcmParser::gdcmParser(bool exception_on_error) {
89 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
92 wasUpdated = 0; // will be set to 1 if user adds an entry
93 printLevel = 1; // 'Medium' print level by default
98 * \brief Canonical destructor.
100 gdcmParser::~gdcmParser (void) {
105 //-----------------------------------------------------------------------------
108 * \ingroup gdcmParser
109 * \brief Prints the Header Entries (Dicom Elements)
110 * from the chained list
113 void gdcmParser::PrintEntry(std::ostream & os) {
115 for (ListTag::iterator i = listEntries.begin();
116 i != listEntries.end();
119 (*i)->SetPrintLevel(printLevel);
125 * \ingroup gdcmParser
126 * \brief Prints the Header Entries (Dicom Elements)
127 * from the chained list
128 * and skips the elements belonging to a SeQuence
131 void gdcmParser::PrintEntryNoSQ(std::ostream & os) {
133 for (ListTag::iterator i = listEntries.begin();
134 i != listEntries.end();
137 if ( (*i)->GetVR() == "SQ"){
141 if ( (*i)->GetGroup() == 0xfffe && (*i)->GetElement() == 0xe0dd){
147 (*i)->SetPrintLevel(printLevel);
154 * \ingroup gdcmParser
155 * \brief Prints the Header Entries (Dicom Elements)
156 * from the chained list
157 * and indents the elements belonging to a SeQuence
160 void gdcmParser::PrintEntryNiceSQ(std::ostream & os) {
162 std::ostringstream tab;
164 for (ListTag::iterator i = listEntries.begin();
165 i != listEntries.end();
168 // we ignore '0 length' SeQuences
169 if ( (*i)->GetVR() == "SQ" && (*i)->GetReadLength()!=0){
172 // a SeQuence is over when a Sequence Delimiter Item is found
173 // pb : 'actual length' Sequence have NO Sequence Delimiter
174 // --> They 'never' finish : check the global length !
175 if ( (*i)->GetGroup() == 0xfffe && (*i)->GetElement() == 0xe0dd){
182 for (int i=0;i<countSQ;i++)
185 (*i)->SetPrintLevel(printLevel);
190 * \brief Prints The Dict Entries of THE public Dicom Dictionary
193 void gdcmParser::PrintPubDict(std::ostream & os) {
194 RefPubDict->Print(os);
198 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
201 void gdcmParser::PrintShaDict(std::ostream & os) {
202 RefShaDict->Print(os);
205 //-----------------------------------------------------------------------------
208 * \brief Get the public dictionary used
210 gdcmDict *gdcmParser::GetPubDict(void) {
215 * \brief Get the shadow dictionary used
217 gdcmDict *gdcmParser::GetShaDict(void) {
222 * \brief Set the shadow dictionary used
223 * \param dict dictionary to use in shadow
225 bool gdcmParser::SetShaDict(gdcmDict *dict){
231 * \brief Set the shadow dictionary used
232 * \param dictName name of the dictionary to use in shadow
234 bool gdcmParser::SetShaDict(DictKey dictName){
235 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
240 * \brief This predicate, based on hopefully reasonable heuristics,
241 * decides whether or not the current gdcmParser was properly parsed
242 * and contains the mandatory information for being considered as
243 * a well formed and usable Dicom/Acr File.
244 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
247 bool gdcmParser::IsReadable(void) {
248 if(filetype==Unknown) {
251 if(listEntries.size()<=0) {
259 * \brief Determines if the Transfer Syntax was already encountered
260 * and if it corresponds to a ImplicitVRLittleEndian one.
261 * @return True when ImplicitVRLittleEndian found. False in all other cases.
263 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
264 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
267 LoadHeaderEntrySafe(Element);
269 std::string Transfer = Element->GetValue();
270 if ( Transfer == UI1_2_840_10008_1_2 )
276 * \ingroup gdcmParser
277 * \brief Determines if the Transfer Syntax was already encountered
278 * and if it corresponds to a ExplicitVRLittleEndian one.
279 * @return True when ExplicitVRLittleEndian found. False in all other cases.
281 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
282 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
285 LoadHeaderEntrySafe(Element);
287 std::string Transfer = Element->GetValue();
288 if ( Transfer == UI1_2_840_10008_1_2_1 )
294 * \brief Determines if the Transfer Syntax was already encountered
295 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
296 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
298 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
299 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
302 LoadHeaderEntrySafe(Element);
304 std::string Transfer = Element->GetValue();
305 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
311 * \brief Determines if the Transfer Syntax was already encountered
312 * and if it corresponds to a Explicit VR Big Endian one.
313 * @return True when big endian found. False in all other cases.
315 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
316 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
319 LoadHeaderEntrySafe(Element);
321 std::string Transfer = Element->GetValue();
322 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
328 * \brief returns the File Type
329 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
330 * @return the FileType code
332 FileType gdcmParser::GetFileType(void) {
337 * \brief opens the file
338 * @param exception_on_error
341 FILE *gdcmParser::OpenFile(bool exception_on_error)
344 fp=fopen(filename.c_str(),"rb");
345 if(exception_on_error)
348 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
354 fread(&zero, (size_t)2, (size_t)1, fp);
356 //ACR -- or DICOM with no Preamble --
357 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
361 fseek(fp, 126L, SEEK_CUR);
363 fread(dicm, (size_t)4, (size_t)1, fp);
364 if( memcmp(dicm, "DICM", 4) == 0 )
368 dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
371 dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
377 * \brief closes the file
378 * @return TRUE if the close was successfull
380 bool gdcmParser::CloseFile(void) {
381 int closed = fclose(fp);
389 * \brief Writes in a file all the Header Entries (Dicom Elements)
390 * of the Chained List
391 * @param fp file pointer on an already open file
392 * @param type Type of the File to be written
393 * (ACR-NEMA, ExplicitVR, ImplicitVR)
394 * \return Always true.
396 bool gdcmParser::Write(FILE *fp, FileType type) {
398 // TODO The stuff was rewritten using the chained list instead
400 // so we could remove the GroupHT from the gdcmParser
404 // TODO : move the following lines (and a lot of others, to be written)
405 // to a future function CheckAndCorrectHeader
408 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier
409 // DicomV3 ou non (FileType est un champ de gdcmParser ...)
410 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
412 // a moins de se livrer a un tres complique ajout des champs manquants.
413 // faire un CheckAndCorrectHeader (?)
415 if (type == ImplicitVR)
417 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
418 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
420 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
421 // values with a VR of UI shall be padded with a single trailing null
422 // Dans le cas suivant on doit pader manuellement avec un 0
424 SetEntryLengthByNumber(18, 0x0002, 0x0010);
427 if (type == ExplicitVR)
429 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
430 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
432 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
433 // values with a VR of UI shall be padded with a single trailing null
434 // Dans le cas suivant on doit pader manuellement avec un 0
436 SetEntryLengthByNumber(20, 0x0002, 0x0010);
439 /* TODO : rewrite later, if really usefull
441 --> Warning : un-updated odd groups lengths can causes pb
443 --> to be re- written with future org.
445 if ( (type == ImplicitVR) || (type == ExplicitVR) )
446 UpdateGroupLength(false,type);
448 UpdateGroupLength(true,ACR);
451 WriteEntries(fp,type);
456 * \brief Modifies the value of a given Header Entry (Dicom Element)
457 * when it exists. Create it with the given value when unexistant.
458 * \warning Adds the Header Entry to the HTable, NOT to the chained List
459 * @param Value Value to be set
460 * @param Group Group of the Entry
461 * @param Elem Element of the Entry
462 * \return pointer to the modified/created Header Entry (NULL when creation
465 gdcmHeaderEntry * gdcmParser::ReplaceOrCreateByNumber(
470 a = GetHeaderEntryByNumber( Group, Elem);
472 a =NewHeaderEntryByNumber(Group, Elem);
477 //CLEANME SetEntryByNumber(Value, Group, Elem);
483 * \brief Set a new value if the invoked element exists
484 * Seems to be useless !!!
485 * @param Value new element value
486 * @param Group group of the Entry
487 * @param Elem element of the Entry
490 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
492 std::string v = Value;
493 SetEntryByNumber(v, Group, Elem);
497 //-----------------------------------------------------------------------------
501 * \brief Checks if a given Dicom Element exists
503 * @param group Group number of the searched Dicom Element
504 * @param element Element number of the searched Dicom Element
505 * @return number of occurences
507 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
508 std::string key = gdcmDictEntry::TranslateToKey(group, element );
509 return (tagHT.count(key));
513 * \ingroup gdcmParser
514 * \brief Searches within Header Entries (Dicom Elements) parsed with
515 * the public and private dictionaries
516 * for the element value of a given tag.
517 * \warning Don't use any longer : use GetPubEntryByName
518 * @param tagName name of the searched element.
519 * @return Corresponding element value when it exists,
520 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
522 std::string gdcmParser::GetEntryByName(std::string tagName) {
523 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
524 if( dictEntry == NULL)
527 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
531 * \ingroup gdcmParser
532 * \brief Searches within Header Entries (Dicom Elements) parsed with
533 * the public and private dictionaries
534 * for the element value representation of a given tag.
536 * Obtaining the VR (Value Representation) might be needed by caller
537 * to convert the string typed content to caller's native type
538 * (think of C++ vs Python). The VR is actually of a higher level
539 * of semantics than just the native C++ type.
540 * @param tagName name of the searched element.
541 * @return Corresponding element value representation when it exists,
542 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
544 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
545 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
546 if( dictEntry == NULL)
549 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
550 dictEntry->GetElement());
551 return elem->GetVR();
556 * \ingroup gdcmParser
557 * \brief Searches within Header Entries (Dicom Elements) parsed with
558 * the public and private dictionaries
559 * for the element value representation of a given tag.
560 * @param group Group of the searched tag.
561 * @param element Element of the searched tag.
562 * @return Corresponding element value representation when it exists,
563 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
565 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
566 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
567 if ( ! tagHT.count(key))
569 return tagHT.find(key)->second->GetValue();
573 * \ingroup gdcmParser
574 * \brief Searches within Header Entries (Dicom Elements) parsed with
575 * the public and private dictionaries
576 * for the element value representation of a given tag..
578 * Obtaining the VR (Value Representation) might be needed by caller
579 * to convert the string typed content to caller's native type
580 * (think of C++ vs Python). The VR is actually of a higher level
581 * of semantics than just the native C++ type.
582 * @param group Group of the searched tag.
583 * @param element Element of the searched tag.
584 * @return Corresponding element value representation when it exists,
585 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
587 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
588 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
591 return elem->GetVR();
595 * \ingroup gdcmParser
596 * \brief Searches within Header Entries (Dicom Elements) parsed with
597 * the public and private dictionaries
598 * for the value length of a given tag..
599 * @param group Group of the searched tag.
600 * @param element Element of the searched tag.
601 * @return Corresponding element length; -2 if not found
603 int gdcmParser::GetEntryLengthByNumber(guint16 group, guint16 element) {
604 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
607 return elem->GetLength();
610 * \ingroup gdcmParser
611 * \brief Sets the value (string) of the Header Entry (Dicom Element)
612 * @param content string value of the Dicom Element
613 * @param tagName name of the searched Dicom Element.
614 * @return true when found
616 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
617 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
618 if( dictEntry == NULL)
621 return(SetEntryByNumber(content,dictEntry->GetGroup(),
622 dictEntry->GetElement()));
626 * \ingroup gdcmParser
627 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
628 * through it's (group, element) and modifies it's content with
630 * \warning Don't use any longer : use SetPubEntryByNumber
631 * @param content new value to substitute with
632 * @param group group of the Dicom Element to modify
633 * @param element element of the Dicom Element to modify
635 bool gdcmParser::SetEntryByNumber(std::string content,
639 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
640 if ( ! tagHT.count(key))
642 int l = content.length();
643 if(l%2) // Non even length are padded with a space (020H).
646 content = content + '\0';
651 TagHeaderEntryHT::iterator p2;
652 // DO NOT remove the following lines : they explain the stuff
653 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
654 //p2=p.first; // iterator on the first synonym
655 //a=p2->second; // H Table target column (2-nd col)
658 a = ((tagHT.equal_range(key)).first)->second;
660 a-> SetValue(content);
662 std::string vr = a->GetVR();
665 if( (vr == "US") || (vr == "SS") )
667 else if( (vr == "UL") || (vr == "SL") )
677 * \ingroup gdcmParser
678 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
679 * in the PubHeaderEntrySet of this instance
680 * through it's (group, element) and modifies it's length with
682 * \warning Use with extreme caution.
683 * @param l new length to substitute with
684 * @param group group of the Entry to modify
685 * @param element element of the Entry to modify
686 * @return true on success, false otherwise.
688 bool gdcmParser::SetEntryLengthByNumber(guint32 l,
692 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
693 if ( ! tagHT.count(key))
695 if (l%2) l++; // length must be even
696 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
702 * \ingroup gdcmParser
703 * \brief Gets (from Header) the offset of a 'non string' element value
704 * (LoadElementValues has already be executed)
705 * @param Group group of the Entry
706 * @param Elem element of the Entry
707 * @return File Offset of the Element Value
709 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
711 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
714 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
715 "failed to Locate gdcmHeaderEntry");
718 return Entry->GetOffset();
722 * \ingroup gdcmParser
723 * \brief Gets (from Header) a 'non string' element value
724 * (LoadElementValues has already be executed)
725 * @param Group group of the Entry
726 * @param Elem element of the Entry
727 * @return Pointer to the 'non string' area
729 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
731 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
734 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
735 "failed to Locate gdcmHeaderEntry");
738 return Entry->GetVoidArea();
742 * \brief Loads (from disk) the element content
743 * when a string is not suitable
744 * @param Group group of the Entry
745 * @param Elem element of the Entry
747 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
749 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
752 size_t o =(size_t)Element->GetOffset();
753 fseek(fp, o, SEEK_SET);
754 int l=Element->GetLength();
755 void * a = malloc(l);
759 SetEntryVoidAreaByNumber(a, Group, Elem);
760 // TODO check the result
761 size_t l2 = fread(a, 1, l ,fp);
772 * \ingroup gdcmParser
773 * \brief Sets a 'non string' value to a given Dicom Element
775 * @param group Group number of the searched Dicom Element
776 * @param element Element number of the searched Dicom Element
779 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
783 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
784 if ( ! tagHT.count(key))
786 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
791 * \ingroup gdcmParser
792 * \brief Update the entries with the shadow dictionary.
793 * Only non even entries are analyzed
795 void gdcmParser::UpdateShaEntries(void) {
796 gdcmDictEntry *entry;
799 for(ListTag::iterator it=listEntries.begin();
800 it!=listEntries.end();
803 // Odd group => from public dictionary
804 if((*it)->GetGroup()%2==0)
807 // Peer group => search the corresponding dict entry
809 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
813 if((*it)->IsImplicitVR())
818 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
820 // Set the new entry and the new value
821 (*it)->SetDictEntry(entry);
822 CheckHeaderEntryVR(*it,vr);
824 (*it)->SetValue(GetHeaderEntryValue(*it));
828 // Remove precedent value transformation
829 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
835 * \ingroup gdcmParser
836 * \brief Searches within the Header Entries for a Dicom Element of
838 * @param tagName name of the searched Dicom Element.
839 * @return Corresponding Dicom Element when it exists, and NULL
842 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
843 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
844 if( dictEntry == NULL)
847 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
851 * \ingroup gdcmParser
852 * \brief retrieves a Dicom Element (the first one) using (group, element)
853 * \warning (group, element) IS NOT an identifier inside the Dicom Header
854 * if you think it's NOT UNIQUE, check the count number
855 * and use iterators to retrieve ALL the Dicoms Elements within
856 * a given couple (group, element)
857 * @param group Group number of the searched Dicom Element
858 * @param element Element number of the searched Dicom Element
861 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
863 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
864 if ( ! tagHT.count(key))
866 return tagHT.find(key)->second;
870 * \ingroup gdcmParser
871 * \brief retrieves the Dicom Elements (all of them) using (group, element)
872 * @param group Group number of the searched Dicom Element.
873 * @param element Element number of the searched Dicom Element.
874 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
877 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
878 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
879 return (tagHT.equal_range(key));
883 * \ingroup gdcmParser
884 * \brief Loads the element while preserving the current
885 * underlying file position indicator as opposed to
886 * to LoadHeaderEntry that modifies it.
887 * @param entry Header Entry whose value shall be loaded.
890 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
891 long PositionOnEntry = ftell(fp);
892 LoadHeaderEntry(entry);
893 fseek(fp, PositionOnEntry, SEEK_SET);
897 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
898 * \warning : to be re-written using the chained list instead of the H table.
899 * \warning : DO NOT use (doesn't work any longer because of the multimap)
900 * \todo : to be re-written using the chained list instead of the H table
901 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
902 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
904 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
908 gdcmHeaderEntry *elem;
910 std::string str_trash;
913 GroupHT groupHt; // to hold the length of each group
916 // typedef std::map<GroupKey, int> GroupHT;
918 gdcmHeaderEntry *elemZ;
920 // for each Tag in the DCM Header
922 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
927 gr = elem->GetGroup();
928 el = elem->GetElement();
931 sprintf(trash, "%04x", gr);
932 key = trash; // generate 'group tag'
934 // if the caller decided not to take SEQUENCEs into account
935 // e.g : he wants to write an ACR-NEMA File
937 if (SkipSequence && vr == "SQ")
940 // Still unsolved problem :
941 // we cannot find the 'Sequence Delimitation Item'
942 // since it's at the end of the Hash Table
945 // there is SEQUENCE in ACR-NEMA
947 // --> la descente a l'interieur' des SQ
948 // devrait etre faite avec une liste chainee, pas avec une HTable...
950 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
952 if (el == 0x0000) // the first elem is 0x0000
954 groupHt[key] = 0; // initialize group length
958 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
961 else // any elem but the first
963 if (type == ExplicitVR)
965 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
967 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
970 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
974 unsigned short int gr_bid;
976 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
980 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
981 // warning: unsigned int format, different type arg
982 sscanf(g->first.c_str(),"%x",&gr_bid);
983 tk = g->first + "|0000"; // generate the element full tag
985 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
987 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
988 elemZ = new gdcmHeaderEntry(tagZ);
990 AddHeaderEntry(elemZ); // create it
994 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
996 sprintf(trash ,"%d",g->second);
998 elemZ->SetValue(str_trash);
1003 * \brief Writes in a file (according to the requested format)
1004 * the group, the element, the value representation and the length
1005 * of a single gdcmHeaderEntry passed as argument.
1006 * @param tag pointer on the gdcmHeaderEntry to be written
1007 * @param _fp already open file pointer
1008 * @param type type of the File to be written
1010 void gdcmParser::WriteEntryTagVRLength(gdcmHeaderEntry *tag,
1014 guint16 group = tag->GetGroup();
1015 std::string vr = tag->GetVR();
1016 guint16 el = tag->GetElement();
1017 guint32 lgr = tag->GetReadLength();
1019 if ( (group == 0xfffe) && (el == 0x0000) )
1020 // Fix in order to make some MR PHILIPS images e-film readable
1021 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1022 // we just *always* ignore spurious fffe|0000 tag !
1025 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1026 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1028 if ( type == ExplicitVR ) {
1030 // Special case of delimiters:
1031 if (group == 0xfffe) {
1032 // Delimiters have NO Value Representation and have NO length.
1033 // Hence we skip writing the VR and length and we pad by writing
1037 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1042 guint16 shortLgr = lgr;
1043 if (vr == "unkn") { // Unknown was 'written'
1044 // deal with Little Endian
1045 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1046 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1048 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1049 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1051 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1052 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1054 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1060 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1065 * \brief Writes in a file (according to the requested format)
1066 * the value of a single gdcmHeaderEntry passed as argument.
1067 * @param tag Pointer on the gdcmHeaderEntry to be written
1068 * @param _fp Already open file pointer
1069 * @param type type of the File to be written
1071 void gdcmParser::WriteEntryValue(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1073 guint16 group = tag->GetGroup();
1074 std::string vr = tag->GetVR();
1075 guint32 lgr = tag->GetReadLength();
1078 // SeQuences have no value:
1080 if (group == 0xfffe)
1081 // Delimiters have no associated value:
1085 voidArea = tag->GetVoidArea();
1086 if (voidArea != NULL)
1087 { // there is a 'non string' LUT, overlay, etc
1088 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1092 if (vr == "US" || vr == "SS")
1094 // some 'Short integer' fields may be mulivaluated
1095 // each single value is separated from the next one by \
1096 // we split the string and write each value as a short int
1097 std::vector<std::string> tokens;
1098 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1099 Tokenize (tag->GetValue(), tokens, "\\");
1100 for (unsigned int i=0; i<tokens.size();i++)
1102 guint16 val_uint16 = atoi(tokens[i].c_str());
1103 void *ptr = &val_uint16;
1104 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1109 // some 'Integer' fields may be mulivaluated
1110 // each single value is separated from the next one by \
1111 // we split the string and write each value as an int
1112 if (vr == "UL" || vr == "SL")
1114 std::vector<std::string> tokens;
1115 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1116 Tokenize (tag->GetValue(), tokens, "\\");
1117 for (unsigned int i=0; i<tokens.size();i++)
1119 guint32 val_uint32 = atoi(tokens[i].c_str());
1120 void *ptr = &val_uint32;
1121 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1126 fwrite (tag->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1130 * \brief Writes in a file (according to the requested format)
1131 * a single gdcmHeaderEntry passed as argument.
1132 * \sa WriteEntryValue, WriteEntryTagVRLength.
1133 * @param tag Pointer on the gdcmHeaderEntry to be written
1134 * @param _fp Already open file pointer
1135 * @param type type of the File to be written
1138 bool gdcmParser::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1140 guint32 length = tag->GetLength();
1142 // The value of a tag MUST (see the DICOM norm) be an odd number of
1143 // bytes. When this is not the case, pad with an additional byte:
1146 tag->SetValue(tag->GetValue()+"\0");
1147 tag->SetLength(tag->GetReadLength()+1);
1150 WriteEntryTagVRLength(tag, _fp, type);
1151 WriteEntryValue(tag, _fp, type);
1156 * \brief writes on disc according to the requested format
1157 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1158 * using the Chained List
1159 * \warning does NOT add the missing elements in the header :
1160 * it's up to the user doing it !
1161 * (function CheckHeaderCoherence to be written)
1162 * \warning DON'T try, right now, to write a DICOM image
1163 * from an ACR Header (meta elements will be missing!)
1164 * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1165 * @param type type of the File to be written
1166 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1167 * @param _fp already open file pointer
1170 bool gdcmParser::WriteEntries(FILE *_fp,FileType type)
1172 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1174 for (ListTag::iterator tag2=listEntries.begin();
1175 tag2 != listEntries.end();
1179 if ((*tag2)->GetGroup() < 0x0008)
1180 // Ignore pure DICOM V3 groups
1182 if ((*tag2)->GetElement() %2)
1183 // Ignore the "shadow" groups
1185 if ((*tag2)->GetVR() == "SQ" )
1186 // For the time being sequences are simply ignored
1187 // TODO : find a trick not to *skip* the SeQuences !
1189 if ((*tag2)->GetGroup() == 0xfffe )
1190 // Ignore the documented delimiter
1193 if (! WriteEntry(*tag2,_fp,type) )
1200 * \ingroup gdcmParser
1201 * \brief writes on disc according to the requested format
1202 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1203 * using only the last synonym of each mutimap H Table post.
1204 * \warning Uses the H Table, instead of the Chained List
1205 * in order to be compliant with the old way to proceed
1206 * (added elements taken in to account)
1207 * Only THERALYS, during a transitory phase is supposed
1208 * to use this method !!!
1209 * \warning DON'T try, right now, to write a DICOM image
1210 * from an ACR Header (meta elements will be missing!)
1212 * @param _fp already open file pointer
1213 * @param type type of the File to be written
1214 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1216 void gdcmParser::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1218 // restent a tester les echecs en ecriture (apres chaque fwrite)
1220 for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1221 tag2 != tagHT.end();
1224 if ((*tag2->second).GetGroup() < 0x0008) continue; // ignore pure DICOM V3 groups
1225 if ((*tag2->second).GetElement() %2) continue; // ignore shadow groups
1226 if ((*tag2->second).GetVR() == "SQ" ) continue; // ignore Sequences
1227 // TODO : find a trick to *skip* the SeQuences !
1228 // Not only ignore the SQ element
1229 // --> will be done with the next organization
1230 if ((*tag2->second).GetGroup() == 0xfffe ) continue; // ignore delimiters
1232 if ( ! WriteEntry(tag2->second,_fp,type))
1238 * \ingroup gdcmParser
1239 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1241 * @return The properly swaped 32 bits integer.
1243 guint32 gdcmParser::SwapLong(guint32 a) {
1248 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1249 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1253 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1257 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1260 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1267 * \ingroup gdcmParser
1268 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1270 * @return The properly unswaped 32 bits integer.
1272 guint32 gdcmParser::UnswapLong(guint32 a) {
1273 return (SwapLong(a));
1277 * \ingroup gdcmParser
1278 * \brief Swaps the bytes so they agree with the processor order
1279 * @return The properly swaped 16 bits integer.
1281 guint16 gdcmParser::SwapShort(guint16 a) {
1282 if ( (sw==4321) || (sw==2143) )
1283 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1288 * \ingroup gdcmParser
1289 * \brief Unswaps the bytes so they agree with the processor order
1290 * @return The properly unswaped 16 bits integer.
1292 guint16 gdcmParser::UnswapShort(guint16 a) {
1293 return (SwapShort(a));
1296 //-----------------------------------------------------------------------------
1299 * \ingroup gdcmParser
1300 * \brief Parses the header of the file but WITHOUT loading element values.
1301 * @return false if file is not ACR-NEMA / DICOM
1303 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1309 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1310 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1311 SkipHeaderEntry(newHeaderEntry);
1312 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1313 AddHeaderEntry(newHeaderEntry);
1320 * \ingroup gdcmParser
1321 * \brief Loads the element values of all the Header Entries pointed in the
1322 * public Chained List.
1324 void gdcmParser::LoadHeaderEntries(void) {
1326 for (ListTag::iterator i = GetListEntry().begin();
1327 i != GetListEntry().end();
1330 LoadHeaderEntry(*i);
1335 // Load 'non string' values
1336 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1337 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1338 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1339 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1340 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1341 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1343 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1344 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1345 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1347 //FIXME : how to use it?
1348 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1350 // --------------------------------------------------------------
1351 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1353 // if recognition code tells us we deal with a LibIDO image
1354 // we switch lineNumber and columnNumber
1356 std::string RecCode;
1357 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1358 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1359 RecCode == "CANRME_AILIBOD1_1." )
1361 filetype = ACR_LIBIDO;
1362 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1363 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1364 SetEntryByNumber(columns, 0x0028, 0x0010);
1365 SetEntryByNumber(rows , 0x0028, 0x0011);
1367 // ----------------- End of Special Patch ----------------
1371 * \ingroup gdcmParser
1372 * \brief Loads the element content if its length doesn't exceed
1373 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1374 * @param Entry Header Entry (Dicom Element) to be dealt with
1376 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1378 guint16 group = Entry->GetGroup();
1379 std::string vr= Entry->GetVR();
1380 guint32 length = Entry->GetLength();
1381 bool SkipLoad = false;
1383 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1385 // the test was commented out to 'go inside' the SeQuences
1386 // we don't any longer skip them !
1388 // if( vr == "SQ" ) // (DO NOT remove this comment)
1391 // A SeQuence "contains" a set of Elements.
1392 // (fffe e000) tells us an Element is beginning
1393 // (fffe e00d) tells us an Element just ended
1394 // (fffe e0dd) tells us the current SeQuence just ended
1395 if( group == 0xfffe )
1399 Entry->SetLength(0);
1400 Entry->SetValue("gdcm::Skipped");
1404 // When the length is zero things are easy:
1405 if ( length == 0 ) {
1406 Entry->SetValue("");
1410 // The elements whose length is bigger than the specified upper bound
1411 // are not loaded. Instead we leave a short notice of the offset of
1412 // the element content and it's length.
1413 if (length > MaxSizeLoadEntry) {
1414 std::ostringstream s;
1415 s << "gdcm::NotLoaded.";
1416 s << " Address:" << (long)Entry->GetOffset();
1417 s << " Length:" << Entry->GetLength();
1418 s << " x(" << std::hex << Entry->GetLength() << ")";
1419 Entry->SetValue(s.str());
1423 // Any compacter code suggested (?)
1424 if ( IsHeaderEntryAnInteger(Entry) ) {
1426 std::ostringstream s;
1428 // When short integer(s) are expected, read and convert the following
1429 // n *two characters properly i.e. as short integers as opposed to strings.
1430 // Elements with Value Multiplicity > 1
1431 // contain a set of integers (not a single one)
1432 if (vr == "US" || vr == "SS") {
1434 NewInt = ReadInt16();
1437 for (int i=1; i < nbInt; i++) {
1439 NewInt = ReadInt16();
1444 // When integer(s) are expected, read and convert the following
1445 // n * four characters properly i.e. as integers as opposed to strings.
1446 // Elements with Value Multiplicity > 1
1447 // contain a set of integers (not a single one)
1448 else if (vr == "UL" || vr == "SL") {
1450 NewInt = ReadInt32();
1453 for (int i=1; i < nbInt; i++) {
1455 NewInt = ReadInt32();
1460 #ifdef GDCM_NO_ANSI_STRING_STREAM
1461 s << std::ends; // to avoid oddities on Solaris
1462 #endif //GDCM_NO_ANSI_STRING_STREAM
1464 Entry->SetValue(s.str());
1468 // We need an additional byte for storing \0 that is not on disk
1469 std::string NewValue(length,0);
1470 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1471 if ( item_read != 1 ) {
1472 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1473 Entry->SetValue("gdcm::UnRead");
1477 if( (vr == "UI") ) // Because of correspondance with the VR dic
1478 Entry->SetValue(NewValue.c_str());
1480 Entry->SetValue(NewValue);
1484 * \ingroup gdcmParser
1485 * \brief add a new Dicom Element pointer to
1486 * the H Table and at the end of the chained List
1487 * \warning push_bash in listEntries ONLY during ParseHeader
1488 * \todo something to allow further Elements addition,
1489 * (at their right place in the chained list)
1490 * when position to be taken care of
1491 * @param newHeaderEntry
1493 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1494 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1495 listEntries.push_back(newHeaderEntry);
1500 * \ingroup gdcmParser
1501 * \brief Find the value Length of the passed Header Entry
1502 * @param Entry Header Entry whose length of the value shall be loaded.
1504 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1505 guint16 element = Entry->GetElement();
1506 guint16 group = Entry->GetGroup();
1507 std::string vr = Entry->GetVR();
1510 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1512 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1514 // The following reserved two bytes (see PS 3.5-2001, section
1515 // 7.1.2 Data element structure with explicit vr p27) must be
1516 // skipped before proceeding on reading the length on 4 bytes.
1517 fseek(fp, 2L, SEEK_CUR);
1518 guint32 length32 = ReadInt32();
1520 if ( (vr == "OB") && (length32 == 0xffffffff) )
1522 Entry->SetLength(FindHeaderEntryLengthOB());
1525 FixHeaderEntryFoundLength(Entry, length32);
1529 // Length is encoded on 2 bytes.
1530 length16 = ReadInt16();
1532 // We can tell the current file is encoded in big endian (like
1533 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1534 // and it's value is the one of the encoding of a big endian file.
1535 // In order to deal with such big endian encoded files, we have
1536 // (at least) two strategies:
1537 // * when we load the "Transfer Syntax" tag with value of big endian
1538 // encoding, we raise the proper flags. Then we wait for the end
1539 // of the META group (0x0002) among which is "Transfer Syntax",
1540 // before switching the swap code to big endian. We have to postpone
1541 // the switching of the swap code since the META group is fully encoded
1542 // in little endian, and big endian coding only starts at the next
1543 // group. The corresponding code can be hard to analyse and adds
1544 // many additional unnecessary tests for regular tags.
1545 // * the second strategy consists in waiting for trouble, that shall
1546 // appear when we find the first group with big endian encoding. This
1547 // is easy to detect since the length of a "Group Length" tag (the
1548 // ones with zero as element number) has to be of 4 (0x0004). When we
1549 // encounter 1024 (0x0400) chances are the encoding changed and we
1550 // found a group with big endian encoding.
1551 // We shall use this second strategy. In order to make sure that we
1552 // can interpret the presence of an apparently big endian encoded
1553 // length of a "Group Length" without committing a big mistake, we
1554 // add an additional check: we look in the already parsed elements
1555 // for the presence of a "Transfer Syntax" whose value has to be "big
1556 // endian encoding". When this is the case, chances are we have got our
1557 // hands on a big endian encoded file: we switch the swap code to
1558 // big endian and proceed...
1559 if ( (element == 0x0000) && (length16 == 0x0400) )
1561 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1563 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1568 SwitchSwapToBigEndian();
1569 // Restore the unproperly loaded values i.e. the group, the element
1570 // and the dictionary entry depending on them.
1571 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1572 guint16 CorrectElem = SwapShort(Entry->GetElement());
1573 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1577 // This correct tag is not in the dictionary. Create a new one.
1578 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1580 // FIXME this can create a memory leaks on the old entry that be
1581 // left unreferenced.
1582 Entry->SetDictEntry(NewTag);
1585 // Heuristic: well some files are really ill-formed.
1586 if ( length16 == 0xffff)
1589 //dbg.Verbose(0, "gdcmParser::FindLength",
1590 // "Erroneous element length fixed.");
1591 // Actually, length= 0xffff means that we deal with
1592 // Unknown Sequence Length
1594 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1599 // Either implicit VR or a non DICOM conformal (see note below) explicit
1600 // VR that ommited the VR of (at least) this element. Farts happen.
1601 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1602 // on Data elements "Implicit and Explicit VR Data Elements shall
1603 // not coexist in a Data Set and Data Sets nested within it".]
1604 // Length is on 4 bytes.
1606 FixHeaderEntryFoundLength(Entry, ReadInt32());
1612 * \ingroup gdcmParser
1613 * \brief Find the Value Representation of the current Dicom Element.
1616 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1618 if (filetype != ExplicitVR)
1623 long PositionOnEntry = ftell(fp);
1624 // Warning: we believe this is explicit VR (Value Representation) because
1625 // we used a heuristic that found "UL" in the first tag. Alas this
1626 // doesn't guarantee that all the tags will be in explicit VR. In some
1627 // cases (see e-film filtered files) one finds implicit VR tags mixed
1628 // within an explicit VR file. Hence we make sure the present tag
1629 // is in explicit VR and try to fix things if it happens not to be
1632 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1634 if(!CheckHeaderEntryVR(Entry,VR))
1636 fseek(fp, PositionOnEntry, SEEK_SET);
1637 // When this element is known in the dictionary we shall use, e.g. for
1638 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1639 // dictionary entry. Still we have to flag the element as implicit since
1640 // we know now our assumption on expliciteness is not furfilled.
1642 if ( Entry->IsVRUnknown() )
1643 Entry->SetVR("Implicit");
1644 Entry->SetImplicitVR();
1649 * \ingroup gdcmParser
1650 * \brief Check the correspondance between the VR of the header entry
1651 * and the taken VR. If they are different, the header entry is
1652 * updated with the new VR.
1653 * @param Entry Header Entry to check
1654 * @param vr Dicom Value Representation
1655 * @return false if the VR is incorrect of if the VR isn't referenced
1656 * otherwise, it returns true
1658 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1660 char msg[100]; // for sprintf
1661 bool RealExplicit = true;
1663 // Assume we are reading a falsely explicit VR file i.e. we reached
1664 // a tag where we expect reading a VR but are in fact we read the
1665 // first to bytes of the length. Then we will interogate (through find)
1666 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1667 // both GCC and VC++ implementations of the STL map. Hence when the
1668 // expected VR read happens to be non-ascii characters we consider
1669 // we hit falsely explicit VR tag.
1671 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1672 RealExplicit = false;
1674 // CLEANME searching the dicom_vr at each occurence is expensive.
1675 // PostPone this test in an optional integrity check at the end
1676 // of parsing or only in debug mode.
1677 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1678 RealExplicit= false;
1680 if ( !RealExplicit )
1682 // We thought this was explicit VR, but we end up with an
1683 // implicit VR tag. Let's backtrack.
1684 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1685 Entry->GetGroup(),Entry->GetElement());
1686 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1687 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1688 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1689 Entry->GetGroup(),Entry->GetElement(),
1690 "UL","FIXME","Group Length");
1691 Entry->SetDictEntry(NewEntry);
1696 if ( Entry->IsVRUnknown() )
1698 // When not a dictionary entry, we can safely overwrite the VR.
1699 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1705 else if ( Entry->GetVR() != vr )
1707 // The VR present in the file and the dictionary disagree. We assume
1708 // the file writer knew best and use the VR of the file. Since it would
1709 // be unwise to overwrite the VR of a dictionary (since it would
1710 // compromise it's next user), we need to clone the actual DictEntry
1711 // and change the VR for the read one.
1712 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1713 Entry->GetGroup(),Entry->GetElement(),
1714 vr,"FIXME",Entry->GetName());
1715 Entry->SetDictEntry(NewEntry);
1721 * \ingroup gdcmParser
1722 * \brief Get the transformed value of the header entry. The VR value
1723 * is used to define the transformation to operate on the value
1724 * \warning NOT end user intended method !
1726 * @return Transformed entry value
1728 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1730 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1732 std::string val=Entry->GetValue();
1733 std::string vr=Entry->GetVR();
1734 guint32 length = Entry->GetLength();
1735 std::ostringstream s;
1738 // When short integer(s) are expected, read and convert the following
1739 // n * 2 bytes properly i.e. as a multivaluated strings
1740 // (each single value is separated fromthe next one by \
1741 // as usual for standard multivaluated filels
1742 // Elements with Value Multiplicity > 1
1743 // contain a set of short integers (not a single one)
1745 if (vr == "US" || vr == "SS")
1750 for (int i=0; i < nbInt; i++)
1754 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1755 NewInt16 = SwapShort(NewInt16);
1760 // When integer(s) are expected, read and convert the following
1761 // n * 4 bytes properly i.e. as a multivaluated strings
1762 // (each single value is separated fromthe next one by \
1763 // as usual for standard multivaluated filels
1764 // Elements with Value Multiplicity > 1
1765 // contain a set of integers (not a single one)
1766 else if (vr == "UL" || vr == "SL")
1771 for (int i=0; i < nbInt; i++)
1775 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1776 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1777 NewInt32=SwapLong(NewInt32);
1781 #ifdef GDCM_NO_ANSI_STRING_STREAM
1782 s << std::ends; // to avoid oddities on Solaris
1783 #endif //GDCM_NO_ANSI_STRING_STREAM
1787 return(Entry->GetValue());
1791 * \ingroup gdcmParser
1792 * \brief Get the reverse transformed value of the header entry. The VR
1793 * value is used to define the reverse transformation to operate on
1795 * \warning NOT end user intended method !
1797 * @return Reverse transformed entry value
1799 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1801 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1803 std::string vr=Entry->GetVR();
1804 std::ostringstream s;
1805 std::vector<std::string> tokens;
1807 if (vr == "US" || vr == "SS")
1811 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1812 Tokenize (Entry->GetValue(), tokens, "\\");
1813 for (unsigned int i=0; i<tokens.size();i++)
1815 NewInt16 = atoi(tokens[i].c_str());
1816 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1820 if (vr == "UL" || vr == "SL")
1824 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1825 Tokenize (Entry->GetValue(), tokens, "\\");
1826 for (unsigned int i=0; i<tokens.size();i++)
1828 NewInt32 = atoi(tokens[i].c_str());
1829 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1830 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1835 #ifdef GDCM_NO_ANSI_STRING_STREAM
1836 s << std::ends; // to avoid oddities on Solaris
1837 #endif //GDCM_NO_ANSI_STRING_STREAM
1841 return(Entry->GetValue());
1845 * \ingroup gdcmParser
1846 * \brief Skip a given Header Entry
1847 * \warning NOT end user intended method !
1850 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1852 SkipBytes(entry->GetLength());
1856 * \ingroup gdcmParser
1857 * \brief When the length of an element value is obviously wrong (because
1858 * the parser went Jabberwocky) one can hope improving things by
1859 * applying this heuristic.
1861 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1863 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1865 if ( FoundLength == 0xffffffff) {
1869 guint16 gr =Entry->GetGroup();
1870 guint16 el =Entry->GetElement();
1872 if (FoundLength%2) {
1873 std::ostringstream s;
1874 s << "Warning : Tag with uneven length " << FoundLength
1875 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1876 dbg.Verbose(0,s.str().c_str());
1879 // Sorry for the patch!
1880 // XMedCom did the trick to read some nasty GE images ...
1881 if (FoundLength == 13) {
1882 // The following 'if' will be removed when there is no more
1883 // images on Creatis HDs with a 13 length for Manufacturer...
1884 if ( (Entry->GetGroup() != 0x0008) ||
1885 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1886 // end of remove area
1888 Entry->SetReadLength(10); // a bug is to be fixed
1892 // to fix some garbage 'Leonardo' Siemens images
1893 // May be commented out to avoid overhead
1894 else if ( (Entry->GetGroup() == 0x0009) &&
1895 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1897 Entry->SetReadLength(4); // a bug is to be fixed
1901 // to try to 'go inside' SeQuences (with length), and not to skip them
1902 else if ( Entry->GetVR() == "SQ")
1904 if (enableSequences) // only if the user does want to !
1905 FoundLength =0; // ReadLength is unchanged
1908 // a SeQuence Element is beginning
1909 // fffe|e000 is just a marker, its length *should be* zero
1910 else if(Entry->GetGroup() == 0xfffe)
1912 // *normally, fffe|0000 doesn't exist !
1913 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1914 // causes extra troubles :-(
1917 Entry->SetUsableLength(FoundLength);
1921 * \ingroup gdcmParser
1922 * \brief Apply some heuristics to predict whether the considered
1923 * element value contains/represents an integer or not.
1924 * @param Entry The element value on which to apply the predicate.
1925 * @return The result of the heuristical predicate.
1927 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1928 guint16 element = Entry->GetElement();
1929 guint16 group = Entry->GetGroup();
1930 std::string vr = Entry->GetVR();
1931 guint32 length = Entry->GetLength();
1932 // When we have some semantics on the element we just read, and if we
1933 // a priori know we are dealing with an integer, then we shall be
1934 // able to swap it's element value properly.
1935 if ( element == 0 ) // This is the group length of the group
1941 std::ostringstream s;
1942 int filePosition = ftell(fp);
1943 s << "Erroneous Group Length element length on : (" \
1944 << std::hex << group << " , " << element
1945 << ") -before- position x(" << filePosition << ")"
1946 << "lgt : " << length;
1947 // These 2 lines commented out : a *very dirty* patch
1948 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1949 // have a glance at offset x(8336) ...
1950 // For *regular* headers, the test is useless..
1951 // lets's print a warning message and go on,
1952 // instead of giving up with an error message
1954 //std::cout << s.str().c_str() << std::endl;
1955 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1956 // s.str().c_str());
1959 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1965 * \ingroup gdcmParser
1966 * \brief Find the Length till the next sequence delimiter
1967 * \warning NOT end user intended method !
1971 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1972 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1975 long PositionOnEntry = ftell(fp);
1976 bool FoundSequenceDelimiter = false;
1977 guint32 TotalLength = 0;
1980 while ( ! FoundSequenceDelimiter)
1986 TotalLength += 4; // We even have to decount the group and element
1988 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1990 char msg[100]; // for sprintf. Sorry
1991 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1992 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1996 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1997 FoundSequenceDelimiter = true;
1998 else if ( n != 0xe000 )
2000 char msg[100]; // for sprintf. Sorry
2001 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2003 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
2007 ItemLength = ReadInt32();
2008 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2009 // the ItemLength with ReadInt32
2010 SkipBytes(ItemLength);
2012 fseek(fp, PositionOnEntry, SEEK_SET);
2017 * \ingroup gdcmParser
2018 * \brief Reads a supposed to be 16 Bits integer
2019 * (swaps it depending on processor endianity)
2020 * @return read value
2022 guint16 gdcmParser::ReadInt16(void) {
2025 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2026 if ( item_read != 1 ) {
2028 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
2038 * \ingroup gdcmParser
2039 * \brief Reads a supposed to be 32 Bits integer
2040 * (swaps it depending on processor endianity)
2041 * @return read value
2043 guint32 gdcmParser::ReadInt32(void) {
2046 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2047 if ( item_read != 1 ) {
2049 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
2059 * \ingroup gdcmParser
2060 * \brief skips bytes inside the source file
2061 * \warning NOT end user intended method !
2064 void gdcmParser::SkipBytes(guint32 NBytes) {
2065 //FIXME don't dump the returned value
2066 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2070 * \ingroup gdcmParser
2071 * \brief Loads all the needed Dictionaries
2072 * \warning NOT end user intended method !
2074 void gdcmParser::Initialise(void)
2076 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2077 RefShaDict = (gdcmDict*)0;
2081 * \ingroup gdcmParser
2082 * \brief Discover what the swap code is (among little endian, big endian,
2083 * bad little endian, bad big endian).
2085 * @return false when we are absolutely sure
2086 * it's neither ACR-NEMA nor DICOM
2087 * true when we hope ours assuptions are OK
2089 bool gdcmParser::CheckSwap() {
2091 // The only guaranted way of finding the swap code is to find a
2092 // group tag since we know it's length has to be of four bytes i.e.
2093 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2094 // occurs when we can't find such group...
2096 guint32 x=4; // x : for ntohs
2097 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2103 char deb[HEADER_LENGTH_TO_READ];
2105 // First, compare HostByteOrder and NetworkByteOrder in order to
2106 // determine if we shall need to swap bytes (i.e. the Endian type).
2112 // The easiest case is the one of a DICOM header, since it possesses a
2113 // file preamble where it suffice to look for the string "DICM".
2114 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2117 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2118 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2120 // Next, determine the value representation (VR). Let's skip to the
2121 // first element (0002, 0000) and check there if we find "UL"
2122 // - or "OB" if the 1st one is (0002,0001) -,
2123 // in which case we (almost) know it is explicit VR.
2124 // WARNING: if it happens to be implicit VR then what we will read
2125 // is the length of the group. If this ascii representation of this
2126 // length happens to be "UL" then we shall believe it is explicit VR.
2127 // FIXME: in order to fix the above warning, we could read the next
2128 // element value (or a couple of elements values) in order to make
2129 // sure we are not commiting a big mistake.
2130 // We need to skip :
2131 // * the 128 bytes of File Preamble (often padded with zeroes),
2132 // * the 4 bytes of "DICM" string,
2133 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2134 // i.e. a total of 136 bytes.
2138 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2139 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2140 // *Implicit* VR. -and it is !-
2142 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2143 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2144 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2145 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2146 // when Write DCM *adds*
2148 // Use gdcmParser::dicom_vr to test all the possibilities
2149 // instead of just checking for UL, OB and UI !? group 0000
2151 filetype = ExplicitVR;
2152 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2153 "explicit Value Representation");
2157 filetype = ImplicitVR;
2158 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2159 "not an explicit Value Representation");
2165 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2166 "HostByteOrder != NetworkByteOrder");
2171 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2172 "HostByteOrder = NetworkByteOrder");
2175 // Position the file position indicator at first tag (i.e.
2176 // after the file preamble and the "DICM" string).
2178 fseek (fp, 132L, SEEK_SET);
2182 // Alas, this is not a DicomV3 file and whatever happens there is no file
2183 // preamble. We can reset the file position indicator to where the data
2184 // is (i.e. the beginning of the file).
2185 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2188 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2189 // By clean we mean that the length of the first tag is written down.
2190 // If this is the case and since the length of the first group HAS to be
2191 // four (bytes), then determining the proper swap code is straightforward.
2194 // We assume the array of char we are considering contains the binary
2195 // representation of a 32 bits integer. Hence the following dirty
2197 s32 = *((guint32 *)(entCur));
2218 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2219 // It is time for despaired wild guesses.
2220 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2221 // i.e. the 'group length' element is not present :
2223 // check the supposed to be 'group number'
2224 // 0x0002 or 0x0004 or 0x0008
2225 // to determine ' sw' value .
2226 // Only 0 or 4321 will be possible
2227 // (no oportunity to check for the formerly well known
2228 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2229 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2230 // the file IS NOT ACR-NEMA nor DICOM V3
2231 // Find a trick to tell it the caller...
2233 s16 = *((guint16 *)(deb));
2249 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2250 "ACR/NEMA unfound swap info (Really hopeless !)");
2255 // Then the only info we have is the net2host one.
2265 * \ingroup gdcmParser
2266 * \brief Restore the unproperly loaded values i.e. the group, the element
2267 * and the dictionary entry depending on them.
2269 void gdcmParser::SwitchSwapToBigEndian(void)
2271 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2272 "Switching to BigEndian mode.");
2293 * \ingroup gdcmParser
2294 * \brief during parsing, Header Elements too long are not loaded in memory
2297 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2301 if ((guint32)NewSize >= (guint32)0xffffffff)
2303 MaxSizeLoadEntry = 0xffffffff;
2306 MaxSizeLoadEntry = NewSize;
2311 * \ingroup gdcmParser
2312 * \brief Header Elements too long will not be printed
2314 * \todo : not yet usable
2315 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2316 * in gdcmHeaderEntry gdcmLoadEntry)
2320 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2324 if ((guint32)NewSize >= (guint32)0xffffffff)
2326 MaxSizePrintEntry = 0xffffffff;
2329 MaxSizePrintEntry = NewSize;
2333 * \ingroup gdcmParser
2334 * \brief Searches both the public and the shadow dictionary (when they
2335 * exist) for the presence of the DictEntry with given name.
2336 * The public dictionary has precedence on the shadow one.
2337 * @param Name name of the searched DictEntry
2338 * @return Corresponding DictEntry when it exists, NULL otherwise.
2340 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2342 gdcmDictEntry *found = (gdcmDictEntry *)0;
2343 if (!RefPubDict && !RefShaDict)
2345 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2346 "we SHOULD have a default dictionary");
2350 found = RefPubDict->GetDictEntryByName(Name);
2356 found = RefShaDict->GetDictEntryByName(Name);
2364 * \ingroup gdcmParser
2365 * \brief Searches both the public and the shadow dictionary (when they
2366 * exist) for the presence of the DictEntry with given
2367 * group and element. The public dictionary has precedence on the
2369 * @param group group of the searched DictEntry
2370 * @param element element of the searched DictEntry
2371 * @return Corresponding DictEntry when it exists, NULL otherwise.
2373 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2375 gdcmDictEntry *found = (gdcmDictEntry *)0;
2376 if (!RefPubDict && !RefShaDict)
2378 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2379 "we SHOULD have a default dictionary");
2383 found = RefPubDict->GetDictEntryByNumber(group, element);
2389 found = RefShaDict->GetDictEntryByNumber(group, element);
2397 * \ingroup gdcmParser
2398 * \brief Read the next tag but WITHOUT loading it's value
2399 * @return On succes the newly created HeaderEntry, NULL on failure.
2401 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2403 gdcmHeaderEntry *NewEntry;
2408 // We reached the EOF (or an error occured) therefore
2409 // header parsing has to be considered as finished.
2410 return (gdcmHeaderEntry *)0;
2412 // Pb : how to propagate the element length (used in SkipHeaderEntry)
2413 // direct call to SkipBytes ?
2415 // if (ignoreShadow == 1 && g%2 ==1)
2416 // if user wants to skip shadow groups
2417 // and current element *is* a shadow element
2418 // we don't create anything
2419 // return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2421 NewEntry = NewHeaderEntryByNumber(g, n);
2422 FindHeaderEntryVR(NewEntry);
2423 FindHeaderEntryLength(NewEntry);
2429 NewEntry->SetOffset(ftell(fp));
2434 * \ingroup gdcmParser
2435 * \brief Build a new Element Value from all the low level arguments.
2436 * Check for existence of dictionary entry, and build
2437 * a default one when absent.
2438 * @param Name Name of the underlying DictEntry
2440 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2442 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2444 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2446 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2449 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2450 "failed to allocate gdcmHeaderEntry");
2451 return (gdcmHeaderEntry *)0;
2457 * \ingroup gdcmParser
2458 * \brief Request a new virtual dict entry to the dict set
2459 * @param group group of the underlying DictEntry
2460 * @param element element of the underlying DictEntry
2461 * @param vr VR of the underlying DictEntry
2462 * @param fourth owner group
2463 * @param name english name
2465 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2470 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2474 * \ingroup gdcmParser
2475 * \brief Build a new Element Value from all the low level arguments.
2476 * Check for existence of dictionary entry, and build
2477 * a default one when absent.
2478 * @param Group group of the underlying DictEntry
2479 * @param Elem element of the underlying DictEntry
2481 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2483 // Find out if the tag we encountered is in the dictionaries:
2484 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2486 DictEntry = NewVirtualDictEntry(Group, Elem);
2488 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2491 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2492 "failed to allocate gdcmHeaderEntry");
2498 // Never used; commented out, waiting for removal.
2500 * \ingroup gdcmParser
2501 * \brief Small utility function that creates a new manually crafted
2502 * (as opposed as read from the file) gdcmHeaderEntry with user
2503 * specified name and adds it to the public tag hash table.
2504 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2505 * @param NewTagName The name to be given to this new tag.
2506 * @param VR The Value Representation to be given to this new tag.
2507 * @return The newly hand crafted Element Value.
2509 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2512 // gdcmHeaderEntry *NewEntry = NULL;
2513 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2514 // guint32 FreeElem = 0;
2515 // gdcmDictEntry *DictEntry = NULL;
2517 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2518 // if (FreeElem == UINT32_MAX)
2520 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2521 // "Group 0xffff in Public Dict is full");
2525 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2526 // VR, "GDCM", NewTagName);
2527 // NewEntry = new gdcmHeaderEntry(DictEntry);
2528 // AddHeaderEntry(NewEntry);
2533 * \ingroup gdcmParser
2534 * \brief Generate a free TagKey i.e. a TagKey that is not present
2535 * in the TagHt dictionary.
2536 * @param group The generated tag must belong to this group.
2537 * @return The element of tag with given group which is fee.
2539 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2541 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2543 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2544 if (tagHT.count(key) == 0)
2550 //-----------------------------------------------------------------------------