2 //-----------------------------------------------------------------------------
10 #include <netinet/in.h>
13 #ifdef GDCM_NO_ANSI_STRING_STREAM
15 # define ostringstream ostrstream
21 #include "gdcmParser.h"
22 #include "gdcmGlobal.h"
24 #include "gdcmDebug.h"
26 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
27 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
28 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
29 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
31 //-----------------------------------------------------------------------------
32 // Refer to gdcmParser::CheckSwap()
33 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
35 // Refer to gdcmParser::SetMaxSizeLoadEntry()
36 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
38 // Refer to gdcmParser::SetMaxSizePrintEntry()
39 // TODO : Right now, better see "define, in gdcmHederEntry.cxx
40 const unsigned int gdcmParser::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
42 //-----------------------------------------------------------------------------
43 // Constructor / Destructor
48 * @param exception_on_error whether we throw an exception or not
49 * @param enable_sequences = true to allow the header
50 * to be parsed *inside* the SeQuences,
51 * when they have an actual length
52 * @param ignore_shadow to allow skipping the shadow elements,
53 * to save memory space.
54 * \warning The TRUE value for this param has to be used
55 * with a FALSE value for the 'enable_sequence' param.
56 * ('public elements' may be embedded in 'shadow Sequences')
58 gdcmParser::gdcmParser(const char *inFilename,
59 bool exception_on_error,
60 bool enable_sequences,
62 enableSequences=enable_sequences;
63 ignoreShadow =ignore_shadow;
65 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
66 filename = inFilename;
69 if ( !OpenFile(exception_on_error))
76 wasUpdated = 0; // will be set to 1 if user adds an entry
77 printLevel = 1; // 'Medium' print level by default
83 * @param exception_on_error
85 gdcmParser::gdcmParser(bool exception_on_error) {
88 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
91 wasUpdated = 0; // will be set to 1 if user adds an entry
92 printLevel = 1; // 'Medium' print level by default
97 * \brief Canonical destructor.
99 gdcmParser::~gdcmParser (void) {
104 //-----------------------------------------------------------------------------
107 * \ingroup gdcmParser
108 * \brief Prints the Header Entries (Dicom Elements)
109 * from the chained list
112 void gdcmParser::PrintEntry(std::ostream & os) {
114 for (ListTag::iterator i = listEntries.begin();
115 i != listEntries.end();
118 (*i)->SetPrintLevel(printLevel);
124 * \ingroup gdcmParser
125 * \brief Prints the Header Entries (Dicom Elements)
126 * from the chained list
127 * and skips the elements belonging to a SeQuence
130 void gdcmParser::PrintEntryNoSQ(std::ostream & os) {
132 for (ListTag::iterator i = listEntries.begin();
133 i != listEntries.end();
136 if ( (*i)->GetVR() == "SQ"){
140 if ( (*i)->GetGroup() == 0xfffe && (*i)->GetElement() == 0xe0dd){
146 (*i)->SetPrintLevel(printLevel);
153 * \ingroup gdcmParser
154 * \brief Prints the Header Entries (Dicom Elements)
155 * from the chained list
156 * and indents the elements belonging to a SeQuence
159 void gdcmParser::PrintEntryNiceSQ(std::ostream & os) {
161 std::ostringstream tab;
163 for (ListTag::iterator i = listEntries.begin();
164 i != listEntries.end();
167 // we ignore '0 length' SeQuences
168 if ( (*i)->GetVR() == "SQ" && (*i)->GetReadLength()!=0){
171 // a SeQuence is over when a Sequence Delimiter Item is found
172 // pb : 'actual length' Sequence have NO Sequence Delimiter
173 // --> They 'never' finish : check the global length !
174 if ( (*i)->GetGroup() == 0xfffe && (*i)->GetElement() == 0xe0dd){
181 for (int i=0;i<countSQ;i++)
184 (*i)->SetPrintLevel(printLevel);
189 * \brief Prints The Dict Entries of THE public Dicom Dictionary
192 void gdcmParser::PrintPubDict(std::ostream & os) {
193 RefPubDict->Print(os);
197 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
200 void gdcmParser::PrintShaDict(std::ostream & os) {
201 RefShaDict->Print(os);
204 //-----------------------------------------------------------------------------
207 * \brief Get the public dictionary used
209 gdcmDict *gdcmParser::GetPubDict(void) {
214 * \brief Get the shadow dictionary used
216 gdcmDict *gdcmParser::GetShaDict(void) {
221 * \brief Set the shadow dictionary used
222 * \param dict dictionary to use in shadow
224 bool gdcmParser::SetShaDict(gdcmDict *dict){
230 * \brief Set the shadow dictionary used
231 * \param dictName name of the dictionary to use in shadow
233 bool gdcmParser::SetShaDict(DictKey dictName){
234 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
239 * \brief This predicate, based on hopefully reasonable heuristics,
240 * decides whether or not the current gdcmParser was properly parsed
241 * and contains the mandatory information for being considered as
242 * a well formed and usable Dicom/Acr File.
243 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
246 bool gdcmParser::IsReadable(void) {
247 if(filetype==Unknown) {
250 if(listEntries.size()<=0) {
258 * \brief Determines if the Transfer Syntax was already encountered
259 * and if it corresponds to a ImplicitVRLittleEndian one.
260 * @return True when ImplicitVRLittleEndian found. False in all other cases.
262 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
263 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
266 LoadHeaderEntrySafe(Element);
268 std::string Transfer = Element->GetValue();
269 if ( Transfer == UI1_2_840_10008_1_2 )
275 * \ingroup gdcmParser
276 * \brief Determines if the Transfer Syntax was already encountered
277 * and if it corresponds to a ExplicitVRLittleEndian one.
278 * @return True when ExplicitVRLittleEndian found. False in all other cases.
280 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
281 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
284 LoadHeaderEntrySafe(Element);
286 std::string Transfer = Element->GetValue();
287 if ( Transfer == UI1_2_840_10008_1_2_1 )
293 * \brief Determines if the Transfer Syntax was already encountered
294 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
295 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
297 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
298 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
301 LoadHeaderEntrySafe(Element);
303 std::string Transfer = Element->GetValue();
304 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
310 * \brief Determines if the Transfer Syntax was already encountered
311 * and if it corresponds to a Explicit VR Big Endian one.
312 * @return True when big endian found. False in all other cases.
314 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
315 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
318 LoadHeaderEntrySafe(Element);
320 std::string Transfer = Element->GetValue();
321 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
327 * \brief returns the File Type
328 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
329 * @return the FileType code
331 FileType gdcmParser::GetFileType(void) {
336 * \brief opens the file
337 * @param exception_on_error
340 FILE *gdcmParser::OpenFile(bool exception_on_error)
343 fp=fopen(filename.c_str(),"rb");
344 if(exception_on_error)
347 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
353 fread(&zero, (size_t)2, (size_t)1, fp);
355 //ACR -- or DICOM with no Preamble --
356 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
360 fseek(fp, 126L, SEEK_CUR);
362 fread(dicm, (size_t)4, (size_t)1, fp);
363 if( memcmp(dicm, "DICM", 4) == 0 )
367 dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
370 dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
376 * \brief closes the file
377 * @return TRUE if the close was successfull
379 bool gdcmParser::CloseFile(void) {
380 int closed = fclose(fp);
388 * \brief Writes in a file all the Header Entries (Dicom Elements)
389 * of the Chained List
390 * @param fp file pointer on an already open file
391 * @param type Type of the File to be written
392 * (ACR-NEMA, ExplicitVR, ImplicitVR)
393 * \return Always true.
395 bool gdcmParser::Write(FILE *fp, FileType type) {
397 // TODO The stuff was rewritten using the chained list instead
399 // so we could remove the GroupHT from the gdcmParser
403 // TODO : move the following lines (and a lot of others, to be written)
404 // to a future function CheckAndCorrectHeader
407 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier
408 // DicomV3 ou non (FileType est un champ de gdcmParser ...)
409 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
411 // a moins de se livrer a un tres complique ajout des champs manquants.
412 // 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, if really usefull
440 --> Warning : un-updated odd groups lengths can causes pb
442 --> to be re- written with future org.
444 if ( (type == ImplicitVR) || (type == ExplicitVR) )
445 UpdateGroupLength(false,type);
447 UpdateGroupLength(true,ACR);
450 WriteEntries(fp,type);
455 * \brief Modifies the value of a given Header Entry (Dicom Element)
456 * when it exists. Create it with the given value when unexistant.
457 * \warning Adds the Header Entry to the HTable, NOT to the chained List
458 * @param Value Value to be set
459 * @param Group Group of the Entry
460 * @param Elem Element of the Entry
461 * \return pointer to the modified/created Header Entry (NULL when creation
464 gdcmHeaderEntry * gdcmParser::ReplaceOrCreateByNumber(
469 a = GetHeaderEntryByNumber( Group, Elem);
471 a =NewHeaderEntryByNumber(Group, Elem);
476 //CLEANME SetEntryByNumber(Value, Group, Elem);
482 * \brief Set a new value if the invoked element exists
483 * Seems to be useless !!!
484 * @param Value new element value
485 * @param Group group of the Entry
486 * @param Elem element of the Entry
489 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
491 std::string v = Value;
492 SetEntryByNumber(v, Group, Elem);
496 //-----------------------------------------------------------------------------
500 * \brief Checks if a given Dicom Element exists
502 * @param group Group number of the searched Dicom Element
503 * @param element Element number of the searched Dicom Element
504 * @return number of occurences
506 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
507 std::string key = gdcmDictEntry::TranslateToKey(group, element );
508 return (tagHT.count(key));
512 * \ingroup gdcmParser
513 * \brief Searches within Header Entries (Dicom Elements) parsed with
514 * the public and private dictionaries
515 * for the element value of a given tag.
516 * \warning Don't use any longer : use GetPubEntryByName
517 * @param tagName name of the searched element.
518 * @return Corresponding element value when it exists,
519 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
521 std::string gdcmParser::GetEntryByName(std::string tagName) {
522 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
523 if( dictEntry == NULL)
526 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
530 * \ingroup gdcmParser
531 * \brief Searches within Header Entries (Dicom Elements) parsed with
532 * the public and private dictionaries
533 * for the element value representation of a given tag.
535 * Obtaining the VR (Value Representation) might be needed by caller
536 * to convert the string typed content to caller's native type
537 * (think of C++ vs Python). The VR is actually of a higher level
538 * of semantics than just the native C++ type.
539 * @param tagName name of the searched element.
540 * @return Corresponding element value representation when it exists,
541 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
543 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
544 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
545 if( dictEntry == NULL)
548 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
549 dictEntry->GetElement());
550 return elem->GetVR();
555 * \ingroup gdcmParser
556 * \brief Searches within Header Entries (Dicom Elements) parsed with
557 * the public and private dictionaries
558 * for the element value representation of a given tag.
559 * @param group Group of the searched tag.
560 * @param element Element of the searched tag.
561 * @return Corresponding element value representation when it exists,
562 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
564 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
565 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
566 if ( ! tagHT.count(key))
568 return tagHT.find(key)->second->GetValue();
572 * \ingroup gdcmParser
573 * \brief Searches within Header Entries (Dicom Elements) parsed with
574 * the public and private dictionaries
575 * for the element value representation of a given tag..
577 * Obtaining the VR (Value Representation) might be needed by caller
578 * to convert the string typed content to caller's native type
579 * (think of C++ vs Python). The VR is actually of a higher level
580 * of semantics than just the native C++ type.
581 * @param group Group of the searched tag.
582 * @param element Element of the searched tag.
583 * @return Corresponding element value representation when it exists,
584 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
586 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
587 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
590 return elem->GetVR();
594 * \ingroup gdcmParser
595 * \brief Searches within Header Entries (Dicom Elements) parsed with
596 * the public and private dictionaries
597 * for the value length of a given tag..
598 * @param group Group of the searched tag.
599 * @param element Element of the searched tag.
600 * @return Corresponding element length; -2 if not found
602 int gdcmParser::GetEntryLengthByNumber(guint16 group, guint16 element) {
603 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
606 return elem->GetLength();
609 * \ingroup gdcmParser
610 * \brief Sets the value (string) of the Header Entry (Dicom Element)
611 * @param content string value of the Dicom Element
612 * @param tagName name of the searched Dicom Element.
613 * @return true when found
615 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
616 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
617 if( dictEntry == NULL)
620 return(SetEntryByNumber(content,dictEntry->GetGroup(),
621 dictEntry->GetElement()));
625 * \ingroup gdcmParser
626 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
627 * through it's (group, element) and modifies it's content with
629 * \warning Don't use any longer : use SetPubEntryByNumber
630 * @param content new value to substitute with
631 * @param group group of the Dicom Element to modify
632 * @param element element of the Dicom Element to modify
634 bool gdcmParser::SetEntryByNumber(std::string content,
638 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
639 if ( ! tagHT.count(key))
641 int l = content.length();
642 if(l%2) // Non even length are padded with a space (020H).
645 content = content + '\0';
650 TagHeaderEntryHT::iterator p2;
651 // DO NOT remove the following lines : they explain the stuff
652 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
653 //p2=p.first; // iterator on the first synonym
654 //a=p2->second; // H Table target column (2-nd col)
657 a = ((tagHT.equal_range(key)).first)->second;
659 a-> SetValue(content);
661 std::string vr = a->GetVR();
664 if( (vr == "US") || (vr == "SS") )
666 else if( (vr == "UL") || (vr == "SL") )
676 * \ingroup gdcmParser
677 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
678 * in the PubHeaderEntrySet of this instance
679 * through it's (group, element) and modifies it's length with
681 * \warning Use with extreme caution.
682 * @param l new length to substitute with
683 * @param group group of the Entry to modify
684 * @param element element of the Entry to modify
685 * @return true on success, false otherwise.
687 bool gdcmParser::SetEntryLengthByNumber(guint32 l,
691 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
692 if ( ! tagHT.count(key))
694 if (l%2) l++; // length must be even
695 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
701 * \ingroup gdcmParser
702 * \brief Gets (from Header) the offset of a 'non string' element value
703 * (LoadElementValues has already be executed)
704 * @param Group group of the Entry
705 * @param Elem element of the Entry
706 * @return File Offset of the Element Value
708 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
710 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
713 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
714 "failed to Locate gdcmHeaderEntry");
717 return Entry->GetOffset();
721 * \ingroup gdcmParser
722 * \brief Gets (from Header) a 'non string' element value
723 * (LoadElementValues has already be executed)
724 * @param Group group of the Entry
725 * @param Elem element of the Entry
726 * @return Pointer to the 'non string' area
728 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
730 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
733 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
734 "failed to Locate gdcmHeaderEntry");
737 return Entry->GetVoidArea();
741 * \brief Loads (from disk) the element content
742 * when a string is not suitable
743 * @param Group group of the Entry
744 * @param Elem element of the Entry
746 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
748 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
751 size_t o =(size_t)Element->GetOffset();
752 fseek(fp, o, SEEK_SET);
753 int l=Element->GetLength();
754 void * a = malloc(l);
758 SetEntryVoidAreaByNumber(a, Group, Elem);
759 // TODO check the result
760 size_t l2 = fread(a, 1, l ,fp);
771 * \ingroup gdcmParser
772 * \brief Sets a 'non string' value to a given Dicom Element
774 * @param group Group number of the searched Dicom Element
775 * @param element Element number of the searched Dicom Element
778 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
782 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
783 if ( ! tagHT.count(key))
785 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
790 * \ingroup gdcmParser
791 * \brief Update the entries with the shadow dictionary.
792 * Only non even entries are analyzed
794 void gdcmParser::UpdateShaEntries(void) {
795 gdcmDictEntry *entry;
798 for(ListTag::iterator it=listEntries.begin();
799 it!=listEntries.end();
802 // Odd group => from public dictionary
803 if((*it)->GetGroup()%2==0)
806 // Peer group => search the corresponding dict entry
808 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
812 if((*it)->IsImplicitVR())
817 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
819 // Set the new entry and the new value
820 (*it)->SetDictEntry(entry);
821 CheckHeaderEntryVR(*it,vr);
823 (*it)->SetValue(GetHeaderEntryValue(*it));
827 // Remove precedent value transformation
828 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
834 * \ingroup gdcmParser
835 * \brief Searches within the Header Entries for a Dicom Element of
837 * @param tagName name of the searched Dicom Element.
838 * @return Corresponding Dicom Element when it exists, and NULL
841 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
842 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
843 if( dictEntry == NULL)
846 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
850 * \ingroup gdcmParser
851 * \brief retrieves a Dicom Element (the first one) using (group, element)
852 * \warning (group, element) IS NOT an identifier inside the Dicom Header
853 * if you think it's NOT UNIQUE, check the count number
854 * and use iterators to retrieve ALL the Dicoms Elements within
855 * a given couple (group, element)
856 * @param group Group number of the searched Dicom Element
857 * @param element Element number of the searched Dicom Element
860 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
862 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
863 if ( ! tagHT.count(key))
865 return tagHT.find(key)->second;
869 * \ingroup gdcmParser
870 * \brief retrieves the Dicom Elements (all of them) using (group, element)
871 * @param group Group number of the searched Dicom Element.
872 * @param element Element number of the searched Dicom Element.
873 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
876 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
877 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
878 return (tagHT.equal_range(key));
882 * \ingroup gdcmParser
883 * \brief Loads the element while preserving the current
884 * underlying file position indicator as opposed to
885 * to LoadHeaderEntry that modifies it.
886 * @param entry Header Entry whose value shall be loaded.
889 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
890 long PositionOnEntry = ftell(fp);
891 LoadHeaderEntry(entry);
892 fseek(fp, PositionOnEntry, SEEK_SET);
896 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
897 * \warning : to be re-written using the chained list instead of the H table.
898 * \warning : DO NOT use (doesn't work any longer because of the multimap)
899 * \todo : to be re-written using the chained list instead of the H table
900 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
901 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
903 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
907 gdcmHeaderEntry *elem;
909 std::string str_trash;
912 GroupHT groupHt; // to hold the length of each group
915 // typedef std::map<GroupKey, int> GroupHT;
917 gdcmHeaderEntry *elemZ;
919 // for each Tag in the DCM Header
921 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
926 gr = elem->GetGroup();
927 el = elem->GetElement();
930 sprintf(trash, "%04x", gr);
931 key = trash; // generate 'group tag'
933 // if the caller decided not to take SEQUENCEs into account
934 // e.g : he wants to write an ACR-NEMA File
936 if (SkipSequence && vr == "SQ")
939 // Still unsolved problem :
940 // we cannot find the 'Sequence Delimitation Item'
941 // since it's at the end of the Hash Table
944 // there is SEQUENCE in ACR-NEMA
946 // --> la descente a l'interieur' des SQ
947 // devrait etre faite avec une liste chainee, pas avec une HTable...
949 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
951 if (el == 0x0000) // the first elem is 0x0000
953 groupHt[key] = 0; // initialize group length
957 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
960 else // any elem but the first
962 if (type == ExplicitVR)
964 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
966 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
969 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
973 unsigned short int gr_bid;
975 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
979 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
980 // warning: unsigned int format, different type arg
981 sscanf(g->first.c_str(),"%x",&gr_bid);
982 tk = g->first + "|0000"; // generate the element full tag
984 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
986 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
987 elemZ = new gdcmHeaderEntry(tagZ);
989 AddHeaderEntry(elemZ); // create it
993 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
995 sprintf(trash ,"%d",g->second);
997 elemZ->SetValue(str_trash);
1002 * \brief Writes in a file (according to the requested format)
1003 * the group, the element, the value representation and the length
1004 * of a single gdcmHeaderEntry passed as argument.
1005 * @param tag pointer on the gdcmHeaderEntry to be written
1006 * @param _fp already open file pointer
1007 * @param type type of the File to be written
1009 void gdcmParser::WriteEntryTagVRLength(gdcmHeaderEntry *tag,
1013 guint16 group = tag->GetGroup();
1014 std::string vr = tag->GetVR();
1015 guint16 el = tag->GetElement();
1016 guint32 lgr = tag->GetReadLength();
1018 if ( (group == 0xfffe) && (el == 0x0000) )
1019 // Fix in order to make some MR PHILIPS images e-film readable
1020 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1021 // we just *always* ignore spurious fffe|0000 tag !
1024 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1025 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1027 if ( type == ExplicitVR ) {
1029 // Special case of delimiters:
1030 if (group == 0xfffe) {
1031 // Delimiters have NO Value Representation and have NO length.
1032 // Hence we skip writing the VR and length and we pad by writing
1036 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1041 guint16 shortLgr = lgr;
1042 if (vr == "unkn") { // Unknown was 'written'
1043 // deal with Little Endian
1044 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1045 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1047 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1048 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1050 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1051 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1053 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1059 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1064 * \brief Writes in a file (according to the requested format)
1065 * the value of a single gdcmHeaderEntry passed as argument.
1066 * @param tag Pointer on the gdcmHeaderEntry to be written
1067 * @param _fp Already open file pointer
1068 * @param type type of the File to be written
1070 void gdcmParser::WriteEntryValue(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1072 guint16 group = tag->GetGroup();
1073 std::string vr = tag->GetVR();
1074 guint32 lgr = tag->GetReadLength();
1077 // SeQuences have no value:
1079 if (group == 0xfffe)
1080 // Delimiters have no associated value:
1084 voidArea = tag->GetVoidArea();
1085 if (voidArea != NULL)
1086 { // there is a 'non string' LUT, overlay, etc
1087 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1091 if (vr == "US" || vr == "SS")
1093 // some 'Short integer' fields may be mulivaluated
1094 // each single value is separated from the next one by \
1095 // we split the string and write each value as a short int
1096 std::vector<std::string> tokens;
1097 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1098 Tokenize (tag->GetValue(), tokens, "\\");
1099 for (unsigned int i=0; i<tokens.size();i++)
1101 guint16 val_uint16 = atoi(tokens[i].c_str());
1102 void *ptr = &val_uint16;
1103 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1108 // some 'Integer' fields may be mulivaluated
1109 // each single value is separated from the next one by \
1110 // we split the string and write each value as an int
1111 if (vr == "UL" || vr == "SL")
1113 std::vector<std::string> tokens;
1114 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1115 Tokenize (tag->GetValue(), tokens, "\\");
1116 for (unsigned int i=0; i<tokens.size();i++)
1118 guint32 val_uint32 = atoi(tokens[i].c_str());
1119 void *ptr = &val_uint32;
1120 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1125 fwrite (tag->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1129 * \brief Writes in a file (according to the requested format)
1130 * a single gdcmHeaderEntry passed as argument.
1131 * \sa WriteEntryValue, WriteEntryTagVRLength.
1132 * @param tag Pointer on the gdcmHeaderEntry to be written
1133 * @param _fp Already open file pointer
1134 * @param type type of the File to be written
1137 bool gdcmParser::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1139 guint32 length = tag->GetLength();
1141 // The value of a tag MUST (see the DICOM norm) be an odd number of
1142 // bytes. When this is not the case, pad with an additional byte:
1145 tag->SetValue(tag->GetValue()+"\0");
1146 tag->SetLength(tag->GetReadLength()+1);
1149 WriteEntryTagVRLength(tag, _fp, type);
1150 WriteEntryValue(tag, _fp, type);
1155 * \brief writes on disc according to the requested format
1156 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1157 * using the Chained List
1158 * \warning does NOT add the missing elements in the header :
1159 * it's up to the user doing it !
1160 * (function CheckHeaderCoherence to be written)
1161 * \warning DON'T try, right now, to write a DICOM image
1162 * from an ACR Header (meta elements will be missing!)
1163 * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1164 * @param type type of the File to be written
1165 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1166 * @param _fp already open file pointer
1169 bool gdcmParser::WriteEntries(FILE *_fp,FileType type)
1171 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1173 for (ListTag::iterator tag2=listEntries.begin();
1174 tag2 != listEntries.end();
1178 if ((*tag2)->GetGroup() < 0x0008)
1179 // Ignore pure DICOM V3 groups
1181 if ((*tag2)->GetElement() %2)
1182 // Ignore the "shadow" groups
1184 if ((*tag2)->GetVR() == "SQ" )
1185 // For the time being sequences are simply ignored
1186 // TODO : find a trick not to *skip* the SeQuences !
1188 if ((*tag2)->GetGroup() == 0xfffe )
1189 // Ignore the documented delimiter
1192 if (! WriteEntry(*tag2,_fp,type) )
1199 * \ingroup gdcmParser
1200 * \brief writes on disc according to the requested format
1201 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1202 * using only the last synonym of each mutimap H Table post.
1203 * \warning Uses the H Table, instead of the Chained List
1204 * in order to be compliant with the old way to proceed
1205 * (added elements taken in to account)
1206 * Only THERALYS, during a transitory phase is supposed
1207 * to use this method !!!
1208 * \warning DON'T try, right now, to write a DICOM image
1209 * from an ACR Header (meta elements will be missing!)
1211 * @param _fp already open file pointer
1212 * @param type type of the File to be written
1213 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1215 void gdcmParser::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1217 // restent a tester les echecs en ecriture (apres chaque fwrite)
1219 for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1220 tag2 != tagHT.end();
1223 if ((*tag2->second).GetGroup() < 0x0008) continue; // ignore pure DICOM V3 groups
1224 if ((*tag2->second).GetElement() %2) continue; // ignore shadow groups
1225 if ((*tag2->second).GetVR() == "SQ" ) continue; // ignore Sequences
1226 // TODO : find a trick to *skip* the SeQuences !
1227 // Not only ignore the SQ element
1228 // --> will be done with the next organization
1229 if ((*tag2->second).GetGroup() == 0xfffe ) continue; // ignore delimiters
1231 if ( ! WriteEntry(tag2->second,_fp,type))
1237 * \ingroup gdcmParser
1238 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1240 * @return The properly swaped 32 bits integer.
1242 guint32 gdcmParser::SwapLong(guint32 a) {
1247 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1248 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1252 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1256 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1259 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1266 * \ingroup gdcmParser
1267 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1269 * @return The properly unswaped 32 bits integer.
1271 guint32 gdcmParser::UnswapLong(guint32 a) {
1272 return (SwapLong(a));
1276 * \ingroup gdcmParser
1277 * \brief Swaps the bytes so they agree with the processor order
1278 * @return The properly swaped 16 bits integer.
1280 guint16 gdcmParser::SwapShort(guint16 a) {
1281 if ( (sw==4321) || (sw==2143) )
1282 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1287 * \ingroup gdcmParser
1288 * \brief Unswaps the bytes so they agree with the processor order
1289 * @return The properly unswaped 16 bits integer.
1291 guint16 gdcmParser::UnswapShort(guint16 a) {
1292 return (SwapShort(a));
1295 //-----------------------------------------------------------------------------
1298 * \ingroup gdcmParser
1299 * \brief Parses the header of the file but WITHOUT loading element values.
1300 * @return false if file is not ACR-NEMA / DICOM
1302 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1308 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1309 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1310 SkipHeaderEntry(newHeaderEntry);
1311 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1312 AddHeaderEntry(newHeaderEntry);
1319 * \ingroup gdcmParser
1320 * \brief Loads the element values of all the Header Entries pointed in the
1321 * public Chained List.
1323 void gdcmParser::LoadHeaderEntries(void) {
1325 for (ListTag::iterator i = GetListEntry().begin();
1326 i != GetListEntry().end();
1329 LoadHeaderEntry(*i);
1334 // Load 'non string' values
1335 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1336 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1337 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1338 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1339 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1340 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1342 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1343 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1344 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1346 //FIXME : how to use it?
1347 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1349 // --------------------------------------------------------------
1350 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1352 // if recognition code tells us we deal with a LibIDO image
1353 // we switch lineNumber and columnNumber
1355 std::string RecCode;
1356 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1357 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1358 RecCode == "CANRME_AILIBOD1_1." )
1360 filetype = ACR_LIBIDO;
1361 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1362 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1363 SetEntryByNumber(columns, 0x0028, 0x0010);
1364 SetEntryByNumber(rows , 0x0028, 0x0011);
1366 // ----------------- End of Special Patch ----------------
1370 * \ingroup gdcmParser
1371 * \brief Loads the element content if its length doesn't exceed
1372 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1373 * @param Entry Header Entry (Dicom Element) to be dealt with
1375 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1377 guint16 group = Entry->GetGroup();
1378 std::string vr= Entry->GetVR();
1379 guint32 length = Entry->GetLength();
1380 bool SkipLoad = false;
1382 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1384 // the test was commented out to 'go inside' the SeQuences
1385 // we don't any longer skip them !
1387 // if( vr == "SQ" ) // (DO NOT remove this comment)
1390 // A SeQuence "contains" a set of Elements.
1391 // (fffe e000) tells us an Element is beginning
1392 // (fffe e00d) tells us an Element just ended
1393 // (fffe e0dd) tells us the current SeQuence just ended
1394 if( group == 0xfffe )
1398 Entry->SetLength(0);
1399 Entry->SetValue("gdcm::Skipped");
1403 // When the length is zero things are easy:
1404 if ( length == 0 ) {
1405 Entry->SetValue("");
1409 // The elements whose length is bigger than the specified upper bound
1410 // are not loaded. Instead we leave a short notice of the offset of
1411 // the element content and it's length.
1412 if (length > MaxSizeLoadEntry) {
1413 std::ostringstream s;
1414 s << "gdcm::NotLoaded.";
1415 s << " Address:" << (long)Entry->GetOffset();
1416 s << " Length:" << Entry->GetLength();
1417 s << " x(" << std::hex << Entry->GetLength() << ")";
1418 Entry->SetValue(s.str());
1422 // Any compacter code suggested (?)
1423 if ( IsHeaderEntryAnInteger(Entry) ) {
1425 std::ostringstream s;
1427 // When short integer(s) are expected, read and convert the following
1428 // n *two characters properly i.e. as short integers as opposed to strings.
1429 // Elements with Value Multiplicity > 1
1430 // contain a set of integers (not a single one)
1431 if (vr == "US" || vr == "SS") {
1433 NewInt = ReadInt16();
1436 for (int i=1; i < nbInt; i++) {
1438 NewInt = ReadInt16();
1443 // When integer(s) are expected, read and convert the following
1444 // n * four characters properly i.e. as integers as opposed to strings.
1445 // Elements with Value Multiplicity > 1
1446 // contain a set of integers (not a single one)
1447 else if (vr == "UL" || vr == "SL") {
1449 NewInt = ReadInt32();
1452 for (int i=1; i < nbInt; i++) {
1454 NewInt = ReadInt32();
1459 #ifdef GDCM_NO_ANSI_STRING_STREAM
1460 s << std::ends; // to avoid oddities on Solaris
1461 #endif //GDCM_NO_ANSI_STRING_STREAM
1463 Entry->SetValue(s.str());
1467 // We need an additional byte for storing \0 that is not on disk
1468 std::string NewValue(length,0);
1469 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1470 if ( item_read != 1 ) {
1471 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1472 Entry->SetValue("gdcm::UnRead");
1476 if( (vr == "UI") ) // Because of correspondance with the VR dic
1477 Entry->SetValue(NewValue.c_str());
1479 Entry->SetValue(NewValue);
1483 * \ingroup gdcmParser
1484 * \brief add a new Dicom Element pointer to
1485 * the H Table and at the end of the chained List
1486 * \warning push_bash in listEntries ONLY during ParseHeader
1487 * \todo something to allow further Elements addition,
1488 * (at their right place in the chained list)
1489 * when position to be taken care of
1490 * @param newHeaderEntry
1492 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1493 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1494 listEntries.push_back(newHeaderEntry);
1499 * \ingroup gdcmParser
1500 * \brief Find the value Length of the passed Header Entry
1501 * @param Entry Header Entry whose length of the value shall be loaded.
1503 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1504 guint16 element = Entry->GetElement();
1505 guint16 group = Entry->GetGroup();
1506 std::string vr = Entry->GetVR();
1509 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1511 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1513 // The following reserved two bytes (see PS 3.5-2001, section
1514 // 7.1.2 Data element structure with explicit vr p27) must be
1515 // skipped before proceeding on reading the length on 4 bytes.
1516 fseek(fp, 2L, SEEK_CUR);
1517 guint32 length32 = ReadInt32();
1519 if ( (vr == "OB") && (length32 == 0xffffffff) )
1521 Entry->SetLength(FindHeaderEntryLengthOB());
1524 FixHeaderEntryFoundLength(Entry, length32);
1528 // Length is encoded on 2 bytes.
1529 length16 = ReadInt16();
1531 // We can tell the current file is encoded in big endian (like
1532 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1533 // and it's value is the one of the encoding of a big endian file.
1534 // In order to deal with such big endian encoded files, we have
1535 // (at least) two strategies:
1536 // * when we load the "Transfer Syntax" tag with value of big endian
1537 // encoding, we raise the proper flags. Then we wait for the end
1538 // of the META group (0x0002) among which is "Transfer Syntax",
1539 // before switching the swap code to big endian. We have to postpone
1540 // the switching of the swap code since the META group is fully encoded
1541 // in little endian, and big endian coding only starts at the next
1542 // group. The corresponding code can be hard to analyse and adds
1543 // many additional unnecessary tests for regular tags.
1544 // * the second strategy consists in waiting for trouble, that shall
1545 // appear when we find the first group with big endian encoding. This
1546 // is easy to detect since the length of a "Group Length" tag (the
1547 // ones with zero as element number) has to be of 4 (0x0004). When we
1548 // encounter 1024 (0x0400) chances are the encoding changed and we
1549 // found a group with big endian encoding.
1550 // We shall use this second strategy. In order to make sure that we
1551 // can interpret the presence of an apparently big endian encoded
1552 // length of a "Group Length" without committing a big mistake, we
1553 // add an additional check: we look in the already parsed elements
1554 // for the presence of a "Transfer Syntax" whose value has to be "big
1555 // endian encoding". When this is the case, chances are we have got our
1556 // hands on a big endian encoded file: we switch the swap code to
1557 // big endian and proceed...
1558 if ( (element == 0x0000) && (length16 == 0x0400) )
1560 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1562 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1567 SwitchSwapToBigEndian();
1568 // Restore the unproperly loaded values i.e. the group, the element
1569 // and the dictionary entry depending on them.
1570 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1571 guint16 CorrectElem = SwapShort(Entry->GetElement());
1572 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1576 // This correct tag is not in the dictionary. Create a new one.
1577 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1579 // FIXME this can create a memory leaks on the old entry that be
1580 // left unreferenced.
1581 Entry->SetDictEntry(NewTag);
1584 // Heuristic: well some files are really ill-formed.
1585 if ( length16 == 0xffff)
1588 //dbg.Verbose(0, "gdcmParser::FindLength",
1589 // "Erroneous element length fixed.");
1590 // Actually, length= 0xffff means that we deal with
1591 // Unknown Sequence Length
1593 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1598 // Either implicit VR or a non DICOM conformal (see note below) explicit
1599 // VR that ommited the VR of (at least) this element. Farts happen.
1600 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1601 // on Data elements "Implicit and Explicit VR Data Elements shall
1602 // not coexist in a Data Set and Data Sets nested within it".]
1603 // Length is on 4 bytes.
1605 FixHeaderEntryFoundLength(Entry, ReadInt32());
1611 * \ingroup gdcmParser
1612 * \brief Find the Value Representation of the current Dicom Element.
1615 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1617 if (filetype != ExplicitVR)
1622 long PositionOnEntry = ftell(fp);
1623 // Warning: we believe this is explicit VR (Value Representation) because
1624 // we used a heuristic that found "UL" in the first tag. Alas this
1625 // doesn't guarantee that all the tags will be in explicit VR. In some
1626 // cases (see e-film filtered files) one finds implicit VR tags mixed
1627 // within an explicit VR file. Hence we make sure the present tag
1628 // is in explicit VR and try to fix things if it happens not to be
1631 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1633 if(!CheckHeaderEntryVR(Entry,VR))
1635 fseek(fp, PositionOnEntry, SEEK_SET);
1636 // When this element is known in the dictionary we shall use, e.g. for
1637 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1638 // dictionary entry. Still we have to flag the element as implicit since
1639 // we know now our assumption on expliciteness is not furfilled.
1641 if ( Entry->IsVRUnknown() )
1642 Entry->SetVR("Implicit");
1643 Entry->SetImplicitVR();
1648 * \ingroup gdcmParser
1649 * \brief Check the correspondance between the VR of the header entry
1650 * and the taken VR. If they are different, the header entry is
1651 * updated with the new VR.
1652 * @param Entry Header Entry to check
1653 * @param vr Dicom Value Representation
1654 * @return false if the VR is incorrect of if the VR isn't referenced
1655 * otherwise, it returns true
1657 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1659 char msg[100]; // for sprintf
1660 bool RealExplicit = true;
1662 // Assume we are reading a falsely explicit VR file i.e. we reached
1663 // a tag where we expect reading a VR but are in fact we read the
1664 // first to bytes of the length. Then we will interogate (through find)
1665 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1666 // both GCC and VC++ implementations of the STL map. Hence when the
1667 // expected VR read happens to be non-ascii characters we consider
1668 // we hit falsely explicit VR tag.
1670 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1671 RealExplicit = false;
1673 // CLEANME searching the dicom_vr at each occurence is expensive.
1674 // PostPone this test in an optional integrity check at the end
1675 // of parsing or only in debug mode.
1676 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1677 RealExplicit= false;
1679 if ( !RealExplicit )
1681 // We thought this was explicit VR, but we end up with an
1682 // implicit VR tag. Let's backtrack.
1683 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1684 Entry->GetGroup(),Entry->GetElement());
1685 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1686 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1687 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1688 Entry->GetGroup(),Entry->GetElement(),
1689 "UL","FIXME","Group Length");
1690 Entry->SetDictEntry(NewEntry);
1695 if ( Entry->IsVRUnknown() )
1697 // When not a dictionary entry, we can safely overwrite the VR.
1698 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1704 else if ( Entry->GetVR() != vr )
1706 // The VR present in the file and the dictionary disagree. We assume
1707 // the file writer knew best and use the VR of the file. Since it would
1708 // be unwise to overwrite the VR of a dictionary (since it would
1709 // compromise it's next user), we need to clone the actual DictEntry
1710 // and change the VR for the read one.
1711 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1712 Entry->GetGroup(),Entry->GetElement(),
1713 vr,"FIXME",Entry->GetName());
1714 Entry->SetDictEntry(NewEntry);
1720 * \ingroup gdcmParser
1721 * \brief Get the transformed value of the header entry. The VR value
1722 * is used to define the transformation to operate on the value
1723 * \warning NOT end user intended method !
1725 * @return Transformed entry value
1727 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1729 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1731 std::string val=Entry->GetValue();
1732 std::string vr=Entry->GetVR();
1733 guint32 length = Entry->GetLength();
1734 std::ostringstream s;
1737 // When short integer(s) are expected, read and convert the following
1738 // n * 2 bytes properly i.e. as a multivaluated strings
1739 // (each single value is separated fromthe next one by \
1740 // as usual for standard multivaluated filels
1741 // Elements with Value Multiplicity > 1
1742 // contain a set of short integers (not a single one)
1744 if (vr == "US" || vr == "SS")
1749 for (int i=0; i < nbInt; i++)
1753 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1754 NewInt16 = SwapShort(NewInt16);
1759 // When integer(s) are expected, read and convert the following
1760 // n * 4 bytes properly i.e. as a multivaluated strings
1761 // (each single value is separated fromthe next one by \
1762 // as usual for standard multivaluated filels
1763 // Elements with Value Multiplicity > 1
1764 // contain a set of integers (not a single one)
1765 else if (vr == "UL" || vr == "SL")
1770 for (int i=0; i < nbInt; i++)
1774 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1775 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1776 NewInt32=SwapLong(NewInt32);
1780 #ifdef GDCM_NO_ANSI_STRING_STREAM
1781 s << std::ends; // to avoid oddities on Solaris
1782 #endif //GDCM_NO_ANSI_STRING_STREAM
1786 return(Entry->GetValue());
1790 * \ingroup gdcmParser
1791 * \brief Get the reverse transformed value of the header entry. The VR
1792 * value is used to define the reverse transformation to operate on
1794 * \warning NOT end user intended method !
1796 * @return Reverse transformed entry value
1798 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1800 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1802 std::string vr=Entry->GetVR();
1803 std::ostringstream s;
1804 std::vector<std::string> tokens;
1806 if (vr == "US" || vr == "SS")
1810 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1811 Tokenize (Entry->GetValue(), tokens, "\\");
1812 for (unsigned int i=0; i<tokens.size();i++)
1814 NewInt16 = atoi(tokens[i].c_str());
1815 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1819 if (vr == "UL" || vr == "SL")
1823 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1824 Tokenize (Entry->GetValue(), tokens, "\\");
1825 for (unsigned int i=0; i<tokens.size();i++)
1827 NewInt32 = atoi(tokens[i].c_str());
1828 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1829 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1834 #ifdef GDCM_NO_ANSI_STRING_STREAM
1835 s << std::ends; // to avoid oddities on Solaris
1836 #endif //GDCM_NO_ANSI_STRING_STREAM
1840 return(Entry->GetValue());
1844 * \ingroup gdcmParser
1845 * \brief Skip a given Header Entry
1846 * \warning NOT end user intended method !
1849 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1851 SkipBytes(entry->GetLength());
1855 * \ingroup gdcmParser
1856 * \brief When the length of an element value is obviously wrong (because
1857 * the parser went Jabberwocky) one can hope improving things by
1858 * applying this heuristic.
1860 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1862 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1864 if ( FoundLength == 0xffffffff) {
1868 guint16 gr =Entry->GetGroup();
1869 guint16 el =Entry->GetElement();
1871 if (FoundLength%2) {
1872 std::ostringstream s;
1873 s << "Warning : Tag with uneven length " << FoundLength
1874 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1875 dbg.Verbose(0,s.str().c_str());
1878 // Sorry for the patch!
1879 // XMedCom did the trick to read some nasty GE images ...
1880 if (FoundLength == 13) {
1881 // The following 'if' will be removed when there is no more
1882 // images on Creatis HDs with a 13 length for Manufacturer...
1883 if ( (Entry->GetGroup() != 0x0008) ||
1884 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1885 // end of remove area
1887 Entry->SetReadLength(10); // a bug is to be fixed
1891 // to fix some garbage 'Leonardo' Siemens images
1892 // May be commented out to avoid overhead
1893 else if ( (Entry->GetGroup() == 0x0009) &&
1894 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1896 Entry->SetReadLength(4); // a bug is to be fixed
1900 // to try to 'go inside' SeQuences (with length), and not to skip them
1901 else if ( Entry->GetVR() == "SQ")
1903 if (enableSequences) // only if the user does want to !
1904 FoundLength =0; // ReadLength is unchanged
1907 // a SeQuence Element is beginning
1908 // fffe|e000 is just a marker, its length *should be* zero
1909 else if(Entry->GetGroup() == 0xfffe)
1911 // *normally, fffe|0000 doesn't exist !
1912 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1913 // causes extra troubles :-(
1916 Entry->SetUsableLength(FoundLength);
1920 * \ingroup gdcmParser
1921 * \brief Apply some heuristics to predict whether the considered
1922 * element value contains/represents an integer or not.
1923 * @param Entry The element value on which to apply the predicate.
1924 * @return The result of the heuristical predicate.
1926 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1927 guint16 element = Entry->GetElement();
1928 guint16 group = Entry->GetGroup();
1929 std::string vr = Entry->GetVR();
1930 guint32 length = Entry->GetLength();
1931 // When we have some semantics on the element we just read, and if we
1932 // a priori know we are dealing with an integer, then we shall be
1933 // able to swap it's element value properly.
1934 if ( element == 0 ) // This is the group length of the group
1940 std::ostringstream s;
1941 int filePosition = ftell(fp);
1942 s << "Erroneous Group Length element length on : (" \
1943 << std::hex << group << " , " << element
1944 << ") -before- position x(" << filePosition << ")"
1945 << "lgt : " << length;
1946 // These 2 lines commented out : a *very dirty* patch
1947 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1948 // have a glance at offset x(8336) ...
1949 // For *regular* headers, the test is useless..
1950 // lets's print a warning message and go on,
1951 // instead of giving up with an error message
1953 //std::cout << s.str().c_str() << std::endl;
1954 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1955 // s.str().c_str());
1958 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1964 * \ingroup gdcmParser
1965 * \brief Find the Length till the next sequence delimiter
1966 * \warning NOT end user intended method !
1970 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1971 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1974 long PositionOnEntry = ftell(fp);
1975 bool FoundSequenceDelimiter = false;
1976 guint32 TotalLength = 0;
1979 while ( ! FoundSequenceDelimiter)
1985 TotalLength += 4; // We even have to decount the group and element
1987 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1989 char msg[100]; // for sprintf. Sorry
1990 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1991 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1995 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1996 FoundSequenceDelimiter = true;
1997 else if ( n != 0xe000 )
1999 char msg[100]; // for sprintf. Sorry
2000 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2002 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
2006 ItemLength = ReadInt32();
2007 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2008 // the ItemLength with ReadInt32
2009 SkipBytes(ItemLength);
2011 fseek(fp, PositionOnEntry, SEEK_SET);
2016 * \ingroup gdcmParser
2017 * \brief Reads a supposed to be 16 Bits integer
2018 * (swaps it depending on processor endianity)
2019 * @return read value
2021 guint16 gdcmParser::ReadInt16(void) {
2024 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2025 if ( item_read != 1 ) {
2027 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
2037 * \ingroup gdcmParser
2038 * \brief Reads a supposed to be 32 Bits integer
2039 * (swaps it depending on processor endianity)
2040 * @return read value
2042 guint32 gdcmParser::ReadInt32(void) {
2045 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2046 if ( item_read != 1 ) {
2048 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
2058 * \ingroup gdcmParser
2059 * \brief skips bytes inside the source file
2060 * \warning NOT end user intended method !
2063 void gdcmParser::SkipBytes(guint32 NBytes) {
2064 //FIXME don't dump the returned value
2065 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2069 * \ingroup gdcmParser
2070 * \brief Loads all the needed Dictionaries
2071 * \warning NOT end user intended method !
2073 void gdcmParser::Initialise(void)
2075 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2076 RefShaDict = (gdcmDict*)0;
2080 * \ingroup gdcmParser
2081 * \brief Discover what the swap code is (among little endian, big endian,
2082 * bad little endian, bad big endian).
2084 * @return false when we are absolutely sure
2085 * it's neither ACR-NEMA nor DICOM
2086 * true when we hope ours assuptions are OK
2088 bool gdcmParser::CheckSwap() {
2090 // The only guaranted way of finding the swap code is to find a
2091 // group tag since we know it's length has to be of four bytes i.e.
2092 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2093 // occurs when we can't find such group...
2095 guint32 x=4; // x : for ntohs
2096 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2102 char deb[HEADER_LENGTH_TO_READ];
2104 // First, compare HostByteOrder and NetworkByteOrder in order to
2105 // determine if we shall need to swap bytes (i.e. the Endian type).
2111 // The easiest case is the one of a DICOM header, since it possesses a
2112 // file preamble where it suffice to look for the string "DICM".
2113 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2116 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2117 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2119 // Next, determine the value representation (VR). Let's skip to the
2120 // first element (0002, 0000) and check there if we find "UL"
2121 // - or "OB" if the 1st one is (0002,0001) -,
2122 // in which case we (almost) know it is explicit VR.
2123 // WARNING: if it happens to be implicit VR then what we will read
2124 // is the length of the group. If this ascii representation of this
2125 // length happens to be "UL" then we shall believe it is explicit VR.
2126 // FIXME: in order to fix the above warning, we could read the next
2127 // element value (or a couple of elements values) in order to make
2128 // sure we are not commiting a big mistake.
2129 // We need to skip :
2130 // * the 128 bytes of File Preamble (often padded with zeroes),
2131 // * the 4 bytes of "DICM" string,
2132 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2133 // i.e. a total of 136 bytes.
2137 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2138 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2139 // *Implicit* VR. -and it is !-
2141 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2142 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2143 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2144 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2145 // when Write DCM *adds*
2147 // Use gdcmParser::dicom_vr to test all the possibilities
2148 // instead of just checking for UL, OB and UI !? group 0000
2150 filetype = ExplicitVR;
2151 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2152 "explicit Value Representation");
2156 filetype = ImplicitVR;
2157 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2158 "not an explicit Value Representation");
2164 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2165 "HostByteOrder != NetworkByteOrder");
2170 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2171 "HostByteOrder = NetworkByteOrder");
2174 // Position the file position indicator at first tag (i.e.
2175 // after the file preamble and the "DICM" string).
2177 fseek (fp, 132L, SEEK_SET);
2181 // Alas, this is not a DicomV3 file and whatever happens there is no file
2182 // preamble. We can reset the file position indicator to where the data
2183 // is (i.e. the beginning of the file).
2184 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2187 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2188 // By clean we mean that the length of the first tag is written down.
2189 // If this is the case and since the length of the first group HAS to be
2190 // four (bytes), then determining the proper swap code is straightforward.
2193 // We assume the array of char we are considering contains the binary
2194 // representation of a 32 bits integer. Hence the following dirty
2196 s32 = *((guint32 *)(entCur));
2217 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2218 // It is time for despaired wild guesses.
2219 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2220 // i.e. the 'group length' element is not present :
2222 // check the supposed to be 'group number'
2223 // 0x0002 or 0x0004 or 0x0008
2224 // to determine ' sw' value .
2225 // Only 0 or 4321 will be possible
2226 // (no oportunity to check for the formerly well known
2227 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2228 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2229 // the file IS NOT ACR-NEMA nor DICOM V3
2230 // Find a trick to tell it the caller...
2232 s16 = *((guint16 *)(deb));
2248 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2249 "ACR/NEMA unfound swap info (Really hopeless !)");
2254 // Then the only info we have is the net2host one.
2264 * \ingroup gdcmParser
2265 * \brief Restore the unproperly loaded values i.e. the group, the element
2266 * and the dictionary entry depending on them.
2268 void gdcmParser::SwitchSwapToBigEndian(void)
2270 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2271 "Switching to BigEndian mode.");
2292 * \ingroup gdcmParser
2293 * \brief during parsing, Header Elements too long are not loaded in memory
2296 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2300 if ((guint32)NewSize >= (guint32)0xffffffff)
2302 MaxSizeLoadEntry = 0xffffffff;
2305 MaxSizeLoadEntry = NewSize;
2310 * \ingroup gdcmParser
2311 * \brief Header Elements too long will not be printed
2313 * \todo : not yet usable
2314 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2315 * in gdcmHeaderEntry gdcmLoadEntry)
2319 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2323 if ((guint32)NewSize >= (guint32)0xffffffff)
2325 MaxSizePrintEntry = 0xffffffff;
2328 MaxSizePrintEntry = NewSize;
2332 * \ingroup gdcmParser
2333 * \brief Searches both the public and the shadow dictionary (when they
2334 * exist) for the presence of the DictEntry with given name.
2335 * The public dictionary has precedence on the shadow one.
2336 * @param Name name of the searched DictEntry
2337 * @return Corresponding DictEntry when it exists, NULL otherwise.
2339 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2341 gdcmDictEntry *found = (gdcmDictEntry *)0;
2342 if (!RefPubDict && !RefShaDict)
2344 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2345 "we SHOULD have a default dictionary");
2349 found = RefPubDict->GetDictEntryByName(Name);
2355 found = RefShaDict->GetDictEntryByName(Name);
2363 * \ingroup gdcmParser
2364 * \brief Searches both the public and the shadow dictionary (when they
2365 * exist) for the presence of the DictEntry with given
2366 * group and element. The public dictionary has precedence on the
2368 * @param group group of the searched DictEntry
2369 * @param element element of the searched DictEntry
2370 * @return Corresponding DictEntry when it exists, NULL otherwise.
2372 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2374 gdcmDictEntry *found = (gdcmDictEntry *)0;
2375 if (!RefPubDict && !RefShaDict)
2377 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2378 "we SHOULD have a default dictionary");
2382 found = RefPubDict->GetDictEntryByNumber(group, element);
2388 found = RefShaDict->GetDictEntryByNumber(group, element);
2396 * \ingroup gdcmParser
2397 * \brief Read the next tag but WITHOUT loading it's value
2398 * @return On succes the newly created HeaderEntry, NULL on failure.
2400 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2402 gdcmHeaderEntry *NewEntry;
2407 // We reached the EOF (or an error occured) therefore
2408 // header parsing has to be considered as finished.
2409 return (gdcmHeaderEntry *)0;
2411 // Pb : how to propagate the element length (used in SkipHeaderEntry)
2412 // direct call to SkipBytes ?
2414 // if (ignoreShadow == 1 && g%2 ==1)
2415 // if user wants to skip shadow groups
2416 // and current element *is* a shadow element
2417 // we don't create anything
2418 // return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2420 NewEntry = NewHeaderEntryByNumber(g, n);
2421 FindHeaderEntryVR(NewEntry);
2422 FindHeaderEntryLength(NewEntry);
2428 NewEntry->SetOffset(ftell(fp));
2433 * \ingroup gdcmParser
2434 * \brief Build a new Element Value from all the low level arguments.
2435 * Check for existence of dictionary entry, and build
2436 * a default one when absent.
2437 * @param Name Name of the underlying DictEntry
2439 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2441 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2443 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2445 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2448 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2449 "failed to allocate gdcmHeaderEntry");
2450 return (gdcmHeaderEntry *)0;
2456 * \ingroup gdcmParser
2457 * \brief Request a new virtual dict entry to the dict set
2458 * @param group group of the underlying DictEntry
2459 * @param element element of the underlying DictEntry
2460 * @param vr VR of the underlying DictEntry
2461 * @param fourth owner group
2462 * @param name english name
2464 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2469 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2473 * \ingroup gdcmParser
2474 * \brief Build a new Element Value from all the low level arguments.
2475 * Check for existence of dictionary entry, and build
2476 * a default one when absent.
2477 * @param Group group of the underlying DictEntry
2478 * @param Elem element of the underlying DictEntry
2480 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2482 // Find out if the tag we encountered is in the dictionaries:
2483 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2485 DictEntry = NewVirtualDictEntry(Group, Elem);
2487 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2490 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2491 "failed to allocate gdcmHeaderEntry");
2497 // Never used; commented out, waiting for removal.
2499 * \ingroup gdcmParser
2500 * \brief Small utility function that creates a new manually crafted
2501 * (as opposed as read from the file) gdcmHeaderEntry with user
2502 * specified name and adds it to the public tag hash table.
2503 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2504 * @param NewTagName The name to be given to this new tag.
2505 * @param VR The Value Representation to be given to this new tag.
2506 * @return The newly hand crafted Element Value.
2508 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2511 // gdcmHeaderEntry *NewEntry = NULL;
2512 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2513 // guint32 FreeElem = 0;
2514 // gdcmDictEntry *DictEntry = NULL;
2516 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2517 // if (FreeElem == UINT32_MAX)
2519 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2520 // "Group 0xffff in Public Dict is full");
2524 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2525 // VR, "GDCM", NewTagName);
2526 // NewEntry = new gdcmHeaderEntry(DictEntry);
2527 // AddHeaderEntry(NewEntry);
2532 * \ingroup gdcmParser
2533 * \brief Generate a free TagKey i.e. a TagKey that is not present
2534 * in the TagHt dictionary.
2535 * @param group The generated tag must belong to this group.
2536 * @return The element of tag with given group which is fee.
2538 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2540 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2542 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2543 if (tagHT.count(key) == 0)
2549 //-----------------------------------------------------------------------------