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) {
87 (void)exception_on_error;
90 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
93 wasUpdated = 0; // will be set to 1 if user adds an entry
94 printLevel = 1; // 'Medium' print level by default
99 * \brief Canonical destructor.
101 gdcmParser::~gdcmParser (void) {
106 //-----------------------------------------------------------------------------
109 * \ingroup gdcmParser
110 * \brief Prints the Header Entries (Dicom Elements)
111 * from the chained list
114 void gdcmParser::PrintEntry(std::ostream & os) {
116 for (ListTag::iterator i = listEntries.begin();
117 i != listEntries.end();
120 (*i)->SetPrintLevel(printLevel);
126 * \ingroup gdcmParser
127 * \brief Prints the Header Entries (Dicom Elements)
128 * from the chained list
129 * and skips the elements belonging to a SeQuence
132 void gdcmParser::PrintEntryNoSQ(std::ostream & os) {
134 for (ListTag::iterator i = listEntries.begin();
135 i != listEntries.end();
138 if ( (*i)->GetVR() == "SQ"){
142 if ( (*i)->GetGroup() == 0xfffe && (*i)->GetElement() == 0xe0dd){
148 (*i)->SetPrintLevel(printLevel);
155 * \ingroup gdcmParser
156 * \brief Prints the Header Entries (Dicom Elements)
157 * from the chained list
158 * and indents the elements belonging to a SeQuence
161 void gdcmParser::PrintEntryNiceSQ(std::ostream & os) {
163 std::ostringstream tab;
165 for (ListTag::iterator i = listEntries.begin();
166 i != listEntries.end();
169 // we ignore '0 length' SeQuences
170 if ( (*i)->GetVR() == "SQ" && (*i)->GetReadLength()!=0){
173 // a SeQuence is over when a Sequence Delimiter Item is found
174 // pb : 'actual length' Sequence have NO Sequence Delimiter
175 // --> They 'never' finish : check the global length !
176 if ( (*i)->GetGroup() == 0xfffe && (*i)->GetElement() == 0xe0dd){
183 for (int i=0;i<countSQ;i++)
186 (*i)->SetPrintLevel(printLevel);
191 * \brief Prints The Dict Entries of THE public Dicom Dictionary
194 void gdcmParser::PrintPubDict(std::ostream & os) {
195 RefPubDict->Print(os);
199 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
202 void gdcmParser::PrintShaDict(std::ostream & os) {
203 RefShaDict->Print(os);
206 //-----------------------------------------------------------------------------
209 * \brief Get the public dictionary used
211 gdcmDict *gdcmParser::GetPubDict(void) {
216 * \brief Get the shadow dictionary used
218 gdcmDict *gdcmParser::GetShaDict(void) {
223 * \brief Set the shadow dictionary used
224 * \param dict dictionary to use in shadow
226 bool gdcmParser::SetShaDict(gdcmDict *dict){
232 * \brief Set the shadow dictionary used
233 * \param dictName name of the dictionary to use in shadow
235 bool gdcmParser::SetShaDict(DictKey dictName){
236 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
241 * \brief This predicate, based on hopefully reasonable heuristics,
242 * decides whether or not the current gdcmParser was properly parsed
243 * and contains the mandatory information for being considered as
244 * a well formed and usable Dicom/Acr File.
245 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
248 bool gdcmParser::IsReadable(void) {
249 if(filetype==Unknown) {
252 if(listEntries.size()<=0) {
260 * \brief Determines if the Transfer Syntax was already encountered
261 * and if it corresponds to a ImplicitVRLittleEndian one.
262 * @return True when ImplicitVRLittleEndian found. False in all other cases.
264 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
265 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
268 LoadHeaderEntrySafe(Element);
270 std::string Transfer = Element->GetValue();
271 if ( Transfer == UI1_2_840_10008_1_2 )
277 * \ingroup gdcmParser
278 * \brief Determines if the Transfer Syntax was already encountered
279 * and if it corresponds to a ExplicitVRLittleEndian one.
280 * @return True when ExplicitVRLittleEndian found. False in all other cases.
282 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
283 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
286 LoadHeaderEntrySafe(Element);
288 std::string Transfer = Element->GetValue();
289 if ( Transfer == UI1_2_840_10008_1_2_1 )
295 * \brief Determines if the Transfer Syntax was already encountered
296 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
297 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
299 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
300 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
303 LoadHeaderEntrySafe(Element);
305 std::string Transfer = Element->GetValue();
306 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
312 * \brief Determines if the Transfer Syntax was already encountered
313 * and if it corresponds to a Explicit VR Big Endian one.
314 * @return True when big endian found. False in all other cases.
316 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
317 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
320 LoadHeaderEntrySafe(Element);
322 std::string Transfer = Element->GetValue();
323 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
329 * \brief returns the File Type
330 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
331 * @return the FileType code
333 FileType gdcmParser::GetFileType(void) {
338 * \brief opens the file
339 * @param exception_on_error
342 FILE *gdcmParser::OpenFile(bool exception_on_error)
345 fp=fopen(filename.c_str(),"rb");
346 if(exception_on_error)
349 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
355 fread(&zero, (size_t)2, (size_t)1, fp);
357 //ACR -- or DICOM with no Preamble --
358 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
362 fseek(fp, 126L, SEEK_CUR);
364 fread(dicm, (size_t)4, (size_t)1, fp);
365 if( memcmp(dicm, "DICM", 4) == 0 )
369 dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
372 dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
378 * \brief closes the file
379 * @return TRUE if the close was successfull
381 bool gdcmParser::CloseFile(void) {
382 int closed = fclose(fp);
390 * \brief Writes in a file all the Header Entries (Dicom Elements)
391 * of the Chained List
392 * @param fp file pointer on an already open file
393 * @param type Type of the File to be written
394 * (ACR-NEMA, ExplicitVR, ImplicitVR)
395 * \return Always true.
397 bool gdcmParser::Write(FILE *fp, FileType type) {
399 // TODO The stuff was rewritten using the chained list instead
401 // so we could remove the GroupHT from the gdcmParser
405 // TODO : move the following lines (and a lot of others, to be written)
406 // to a future function CheckAndCorrectHeader
409 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier
410 // DicomV3 ou non (FileType est un champ de gdcmParser ...)
411 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
413 // a moins de se livrer a un tres complique ajout des champs manquants.
414 // faire un CheckAndCorrectHeader (?)
416 if (type == ImplicitVR)
418 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
419 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
421 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
422 // values with a VR of UI shall be padded with a single trailing null
423 // Dans le cas suivant on doit pader manuellement avec un 0
425 SetEntryLengthByNumber(18, 0x0002, 0x0010);
428 if (type == ExplicitVR)
430 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
431 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
433 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
434 // values with a VR of UI shall be padded with a single trailing null
435 // Dans le cas suivant on doit pader manuellement avec un 0
437 SetEntryLengthByNumber(20, 0x0002, 0x0010);
440 /* TODO : rewrite later, if really usefull
442 --> Warning : un-updated odd groups lengths can causes pb
444 --> to be re- written with future org.
446 if ( (type == ImplicitVR) || (type == ExplicitVR) )
447 UpdateGroupLength(false,type);
449 UpdateGroupLength(true,ACR);
452 WriteEntries(fp,type);
457 * \brief Modifies the value of a given Header Entry (Dicom Element)
458 * when it exists. Create it with the given value when unexistant.
459 * \warning Adds the Header Entry to the HTable, NOT to the chained List
460 * @param Value Value to be set
461 * @param Group Group of the Entry
462 * @param Elem Element of the Entry
463 * \return pointer to the modified/created Header Entry (NULL when creation
466 gdcmHeaderEntry * gdcmParser::ReplaceOrCreateByNumber(
471 a = GetHeaderEntryByNumber( Group, Elem);
473 a =NewHeaderEntryByNumber(Group, Elem);
478 //CLEANME SetEntryByNumber(Value, Group, Elem);
484 * \brief Set a new value if the invoked element exists
485 * Seems to be useless !!!
486 * @param Value new element value
487 * @param Group group of the Entry
488 * @param Elem element of the Entry
491 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
493 std::string v = Value;
494 SetEntryByNumber(v, Group, Elem);
498 //-----------------------------------------------------------------------------
502 * \brief Checks if a given Dicom Element exists
504 * @param group Group number of the searched Dicom Element
505 * @param element Element number of the searched Dicom Element
506 * @return number of occurences
508 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
509 std::string key = gdcmDictEntry::TranslateToKey(group, element );
510 return (tagHT.count(key));
514 * \ingroup gdcmParser
515 * \brief Searches within Header Entries (Dicom Elements) parsed with
516 * the public and private dictionaries
517 * for the element value of a given tag.
518 * \warning Don't use any longer : use GetPubEntryByName
519 * @param tagName name of the searched element.
520 * @return Corresponding element value when it exists,
521 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
523 std::string gdcmParser::GetEntryByName(std::string tagName) {
524 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
525 if( dictEntry == NULL)
528 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
532 * \ingroup gdcmParser
533 * \brief Searches within Header Entries (Dicom Elements) parsed with
534 * the public and private dictionaries
535 * for the element value representation of a given tag.
537 * Obtaining the VR (Value Representation) might be needed by caller
538 * to convert the string typed content to caller's native type
539 * (think of C++ vs Python). The VR is actually of a higher level
540 * of semantics than just the native C++ type.
541 * @param tagName name of the searched element.
542 * @return Corresponding element value representation when it exists,
543 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
545 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
546 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
547 if( dictEntry == NULL)
550 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
551 dictEntry->GetElement());
552 return elem->GetVR();
557 * \ingroup gdcmParser
558 * \brief Searches within Header Entries (Dicom Elements) parsed with
559 * the public and private dictionaries
560 * for the element value representation of a given tag.
561 * @param group Group of the searched tag.
562 * @param element Element of the searched tag.
563 * @return Corresponding element value representation when it exists,
564 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
566 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
567 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
568 if ( ! tagHT.count(key))
570 return tagHT.find(key)->second->GetValue();
574 * \ingroup gdcmParser
575 * \brief Searches within Header Entries (Dicom Elements) parsed with
576 * the public and private dictionaries
577 * for the element value representation of a given tag..
579 * Obtaining the VR (Value Representation) might be needed by caller
580 * to convert the string typed content to caller's native type
581 * (think of C++ vs Python). The VR is actually of a higher level
582 * of semantics than just the native C++ type.
583 * @param group Group of the searched tag.
584 * @param element Element of the searched tag.
585 * @return Corresponding element value representation when it exists,
586 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
588 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
589 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
592 return elem->GetVR();
596 * \ingroup gdcmParser
597 * \brief Searches within Header Entries (Dicom Elements) parsed with
598 * the public and private dictionaries
599 * for the value length of a given tag..
600 * @param group Group of the searched tag.
601 * @param element Element of the searched tag.
602 * @return Corresponding element length; -2 if not found
604 int gdcmParser::GetEntryLengthByNumber(guint16 group, guint16 element) {
605 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
608 return elem->GetLength();
611 * \ingroup gdcmParser
612 * \brief Sets the value (string) of the Header Entry (Dicom Element)
613 * @param content string value of the Dicom Element
614 * @param tagName name of the searched Dicom Element.
615 * @return true when found
617 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
618 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
619 if( dictEntry == NULL)
622 return(SetEntryByNumber(content,dictEntry->GetGroup(),
623 dictEntry->GetElement()));
627 * \ingroup gdcmParser
628 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
629 * through it's (group, element) and modifies it's content with
631 * \warning Don't use any longer : use SetPubEntryByNumber
632 * @param content new value to substitute with
633 * @param group group of the Dicom Element to modify
634 * @param element element of the Dicom Element to modify
636 bool gdcmParser::SetEntryByNumber(std::string content,
640 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
641 if ( ! tagHT.count(key))
643 int l = content.length();
644 if(l%2) // Non even length are padded with a space (020H).
647 content = content + '\0';
652 TagHeaderEntryHT::iterator p2;
653 // DO NOT remove the following lines : they explain the stuff
654 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
655 //p2=p.first; // iterator on the first synonym
656 //a=p2->second; // H Table target column (2-nd col)
659 a = ((tagHT.equal_range(key)).first)->second;
661 a-> SetValue(content);
663 std::string vr = a->GetVR();
666 if( (vr == "US") || (vr == "SS") )
668 else if( (vr == "UL") || (vr == "SL") )
678 * \ingroup gdcmParser
679 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
680 * in the PubHeaderEntrySet of this instance
681 * through it's (group, element) and modifies it's length with
683 * \warning Use with extreme caution.
684 * @param l new length to substitute with
685 * @param group group of the Entry to modify
686 * @param element element of the Entry to modify
687 * @return true on success, false otherwise.
689 bool gdcmParser::SetEntryLengthByNumber(guint32 l,
693 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
694 if ( ! tagHT.count(key))
696 if (l%2) l++; // length must be even
697 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
703 * \ingroup gdcmParser
704 * \brief Gets (from Header) the offset of a 'non string' element value
705 * (LoadElementValues has already be executed)
706 * @param Group group of the Entry
707 * @param Elem element of the Entry
708 * @return File Offset of the Element Value
710 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
712 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
715 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
716 "failed to Locate gdcmHeaderEntry");
719 return Entry->GetOffset();
723 * \ingroup gdcmParser
724 * \brief Gets (from Header) a 'non string' element value
725 * (LoadElementValues has already be executed)
726 * @param Group group of the Entry
727 * @param Elem element of the Entry
728 * @return Pointer to the 'non string' area
730 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
732 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
735 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
736 "failed to Locate gdcmHeaderEntry");
739 return Entry->GetVoidArea();
743 * \brief Loads (from disk) the element content
744 * when a string is not suitable
745 * @param Group group of the Entry
746 * @param Elem element of the Entry
748 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
750 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
753 size_t o =(size_t)Element->GetOffset();
754 fseek(fp, o, SEEK_SET);
755 size_t l=Element->GetLength();
756 char* a = new char[l];
760 SetEntryVoidAreaByNumber(a, Group, Elem);
761 // TODO check the result
762 size_t l2 = fread(a, 1, l ,fp);
773 * \ingroup gdcmParser
774 * \brief Sets a 'non string' value to a given Dicom Element
776 * @param group Group number of the searched Dicom Element
777 * @param element Element number of the searched Dicom Element
780 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
784 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
785 if ( ! tagHT.count(key))
787 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
792 * \ingroup gdcmParser
793 * \brief Update the entries with the shadow dictionary.
794 * Only non even entries are analyzed
796 void gdcmParser::UpdateShaEntries(void) {
797 gdcmDictEntry *entry;
800 for(ListTag::iterator it=listEntries.begin();
801 it!=listEntries.end();
804 // Odd group => from public dictionary
805 if((*it)->GetGroup()%2==0)
808 // Peer group => search the corresponding dict entry
810 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
814 if((*it)->IsImplicitVR())
819 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
821 // Set the new entry and the new value
822 (*it)->SetDictEntry(entry);
823 CheckHeaderEntryVR(*it,vr);
825 (*it)->SetValue(GetHeaderEntryValue(*it));
829 // Remove precedent value transformation
830 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
836 * \ingroup gdcmParser
837 * \brief Searches within the Header Entries for a Dicom Element of
839 * @param tagName name of the searched Dicom Element.
840 * @return Corresponding Dicom Element when it exists, and NULL
843 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
844 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
845 if( dictEntry == NULL)
848 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
852 * \ingroup gdcmParser
853 * \brief retrieves a Dicom Element (the first one) using (group, element)
854 * \warning (group, element) IS NOT an identifier inside the Dicom Header
855 * if you think it's NOT UNIQUE, check the count number
856 * and use iterators to retrieve ALL the Dicoms Elements within
857 * a given couple (group, element)
858 * @param group Group number of the searched Dicom Element
859 * @param element Element number of the searched Dicom Element
862 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
864 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
865 if ( ! tagHT.count(key))
867 return tagHT.find(key)->second;
871 * \ingroup gdcmParser
872 * \brief retrieves the Dicom Elements (all of them) using (group, element)
873 * @param group Group number of the searched Dicom Element.
874 * @param element Element number of the searched Dicom Element.
875 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
878 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
879 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
880 return (tagHT.equal_range(key));
884 * \ingroup gdcmParser
885 * \brief Loads the element while preserving the current
886 * underlying file position indicator as opposed to
887 * to LoadHeaderEntry that modifies it.
888 * @param entry Header Entry whose value shall be loaded.
891 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
892 long PositionOnEntry = ftell(fp);
893 LoadHeaderEntry(entry);
894 fseek(fp, PositionOnEntry, SEEK_SET);
898 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
899 * \warning : to be re-written using the chained list instead of the H table.
900 * \warning : DO NOT use (doesn't work any longer because of the multimap)
901 * \todo : to be re-written using the chained list instead of the H table
902 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
903 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
905 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
909 gdcmHeaderEntry *elem;
911 std::string str_trash;
914 GroupHT groupHt; // to hold the length of each group
917 // typedef std::map<GroupKey, int> GroupHT;
919 gdcmHeaderEntry *elemZ;
921 // for each Tag in the DCM Header
923 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
928 gr = elem->GetGroup();
929 el = elem->GetElement();
932 sprintf(trash, "%04x", gr);
933 key = trash; // generate 'group tag'
935 // if the caller decided not to take SEQUENCEs into account
936 // e.g : he wants to write an ACR-NEMA File
938 if (SkipSequence && vr == "SQ")
941 // Still unsolved problem :
942 // we cannot find the 'Sequence Delimitation Item'
943 // since it's at the end of the Hash Table
946 // there is SEQUENCE in ACR-NEMA
948 // --> la descente a l'interieur' des SQ
949 // devrait etre faite avec une liste chainee, pas avec une HTable...
951 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
953 if (el == 0x0000) // the first elem is 0x0000
955 groupHt[key] = 0; // initialize group length
959 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
962 else // any elem but the first
964 if (type == ExplicitVR)
966 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
968 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
971 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
975 unsigned short int gr_bid;
977 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
981 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
982 // warning: unsigned int format, different type arg
983 sscanf(g->first.c_str(),"%x",&gr_bid); //FIXME
984 tk = g->first + "|0000"; // generate the element full tag
986 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
988 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
989 elemZ = new gdcmHeaderEntry(tagZ);
991 AddHeaderEntry(elemZ); // create it
995 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
997 sprintf(trash ,"%d",g->second);
999 elemZ->SetValue(str_trash);
1004 * \brief Writes in a file (according to the requested format)
1005 * the group, the element, the value representation and the length
1006 * of a single gdcmHeaderEntry passed as argument.
1007 * @param tag pointer on the gdcmHeaderEntry to be written
1008 * @param _fp already open file pointer
1009 * @param type type of the File to be written
1011 void gdcmParser::WriteEntryTagVRLength(gdcmHeaderEntry *tag,
1015 guint16 group = tag->GetGroup();
1016 std::string vr = tag->GetVR();
1017 guint16 el = tag->GetElement();
1018 guint32 lgr = tag->GetReadLength();
1020 if ( (group == 0xfffe) && (el == 0x0000) )
1021 // Fix in order to make some MR PHILIPS images e-film readable
1022 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1023 // we just *always* ignore spurious fffe|0000 tag !
1026 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1027 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1029 if ( type == ExplicitVR ) {
1031 // Special case of delimiters:
1032 if (group == 0xfffe) {
1033 // Delimiters have NO Value Representation and have NO length.
1034 // Hence we skip writing the VR and length and we pad by writing
1038 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1043 guint16 shortLgr = lgr;
1044 if (vr == "unkn") { // Unknown was 'written'
1045 // deal with Little Endian
1046 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1047 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1049 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1050 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1052 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1053 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1055 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1061 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1066 * \brief Writes in a file (according to the requested format)
1067 * the value of a single gdcmHeaderEntry passed as argument.
1068 * @param tag Pointer on the gdcmHeaderEntry to be written
1069 * @param _fp Already open file pointer
1070 * @param type type of the File to be written
1072 void gdcmParser::WriteEntryValue(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1075 guint16 group = tag->GetGroup();
1076 std::string vr = tag->GetVR();
1077 guint32 lgr = tag->GetReadLength();
1080 // SeQuences have no value:
1082 if (group == 0xfffe)
1083 // Delimiters have no associated value:
1087 voidArea = tag->GetVoidArea();
1088 if (voidArea != NULL)
1089 { // there is a 'non string' LUT, overlay, etc
1090 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1094 if (vr == "US" || vr == "SS")
1096 // some 'Short integer' fields may be mulivaluated
1097 // each single value is separated from the next one by '\'
1098 // we split the string and write each value as a short int
1099 std::vector<std::string> tokens;
1100 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1101 Tokenize (tag->GetValue(), tokens, "\\");
1102 for (unsigned int i=0; i<tokens.size();i++)
1104 guint16 val_uint16 = atoi(tokens[i].c_str());
1105 void *ptr = &val_uint16;
1106 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1111 // some 'Integer' fields may be mulivaluated
1112 // each single value is separated from the next one by '\'
1113 // we split the string and write each value as an int
1114 if (vr == "UL" || vr == "SL")
1116 std::vector<std::string> tokens;
1117 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1118 Tokenize (tag->GetValue(), tokens, "\\");
1119 for (unsigned int i=0; i<tokens.size();i++)
1121 guint32 val_uint32 = atoi(tokens[i].c_str());
1122 void *ptr = &val_uint32;
1123 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1128 fwrite (tag->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1132 * \brief Writes in a file (according to the requested format)
1133 * a single gdcmHeaderEntry passed as argument.
1134 * \sa WriteEntryValue, WriteEntryTagVRLength.
1135 * @param tag Pointer on the gdcmHeaderEntry to be written
1136 * @param _fp Already open file pointer
1137 * @param type type of the File to be written
1140 bool gdcmParser::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1142 guint32 length = tag->GetLength();
1144 // The value of a tag MUST (see the DICOM norm) be an odd number of
1145 // bytes. When this is not the case, pad with an additional byte:
1148 tag->SetValue(tag->GetValue()+"\0");
1149 tag->SetLength(tag->GetReadLength()+1);
1152 WriteEntryTagVRLength(tag, _fp, type);
1153 WriteEntryValue(tag, _fp, type);
1158 * \brief writes on disc according to the requested format
1159 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1160 * using the Chained List
1161 * \warning does NOT add the missing elements in the header :
1162 * it's up to the user doing it !
1163 * (function CheckHeaderCoherence to be written)
1164 * \warning DON'T try, right now, to write a DICOM image
1165 * from an ACR Header (meta elements will be missing!)
1166 * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1167 * @param type type of the File to be written
1168 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1169 * @param _fp already open file pointer
1172 bool gdcmParser::WriteEntries(FILE *_fp,FileType type)
1174 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1176 for (ListTag::iterator tag2=listEntries.begin();
1177 tag2 != listEntries.end();
1181 if ((*tag2)->GetGroup() < 0x0008)
1182 // Ignore pure DICOM V3 groups
1184 if ((*tag2)->GetElement() %2)
1185 // Ignore the "shadow" groups
1187 if ((*tag2)->GetVR() == "SQ" )
1188 // For the time being sequences are simply ignored
1189 // TODO : find a trick not to *skip* the SeQuences !
1191 if ((*tag2)->GetGroup() == 0xfffe )
1192 // Ignore the documented delimiter
1195 if (! WriteEntry(*tag2,_fp,type) )
1202 * \ingroup gdcmParser
1203 * \brief writes on disc according to the requested format
1204 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1205 * using only the last synonym of each mutimap H Table post.
1206 * \warning Uses the H Table, instead of the Chained List
1207 * in order to be compliant with the old way to proceed
1208 * (added elements taken in to account)
1209 * Only THERALYS, during a transitory phase is supposed
1210 * to use this method !!!
1211 * \warning DON'T try, right now, to write a DICOM image
1212 * from an ACR Header (meta elements will be missing!)
1214 * @param _fp already open file pointer
1215 * @param type type of the File to be written
1216 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1218 void gdcmParser::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1220 // restent a tester les echecs en ecriture (apres chaque fwrite)
1222 for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1223 tag2 != tagHT.end();
1226 if ((*tag2->second).GetGroup() < 0x0008) continue; // ignore pure DICOM V3 groups
1227 if ((*tag2->second).GetElement() %2) continue; // ignore shadow groups
1228 if ((*tag2->second).GetVR() == "SQ" ) continue; // ignore Sequences
1229 // TODO : find a trick to *skip* the SeQuences !
1230 // Not only ignore the SQ element
1231 // --> will be done with the next organization
1232 if ((*tag2->second).GetGroup() == 0xfffe ) continue; // ignore delimiters
1234 if ( ! WriteEntry(tag2->second,_fp,type))
1240 * \ingroup gdcmParser
1241 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1243 * @return The properly swaped 32 bits integer.
1245 guint32 gdcmParser::SwapLong(guint32 a) {
1250 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1251 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1255 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1259 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1262 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1269 * \ingroup gdcmParser
1270 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1272 * @return The properly unswaped 32 bits integer.
1274 guint32 gdcmParser::UnswapLong(guint32 a) {
1275 return (SwapLong(a));
1279 * \ingroup gdcmParser
1280 * \brief Swaps the bytes so they agree with the processor order
1281 * @return The properly swaped 16 bits integer.
1283 guint16 gdcmParser::SwapShort(guint16 a) {
1284 if ( (sw==4321) || (sw==2143) )
1285 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1290 * \ingroup gdcmParser
1291 * \brief Unswaps the bytes so they agree with the processor order
1292 * @return The properly unswaped 16 bits integer.
1294 guint16 gdcmParser::UnswapShort(guint16 a) {
1295 return (SwapShort(a));
1298 //-----------------------------------------------------------------------------
1301 * \ingroup gdcmParser
1302 * \brief Parses the header of the file but WITHOUT loading element values.
1303 * @return false if file is not ACR-NEMA / DICOM
1305 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1306 (void)exception_on_error;
1311 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1312 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1313 SkipHeaderEntry(newHeaderEntry);
1314 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1315 AddHeaderEntry(newHeaderEntry);
1322 * \ingroup gdcmParser
1323 * \brief Loads the element values of all the Header Entries pointed in the
1324 * public Chained List.
1326 void gdcmParser::LoadHeaderEntries(void) {
1328 for (ListTag::iterator i = GetListEntry().begin();
1329 i != GetListEntry().end();
1332 LoadHeaderEntry(*i);
1337 // Load 'non string' values
1338 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1339 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1340 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1341 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1342 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1343 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1345 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1346 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1347 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1349 //FIXME : how to use it?
1350 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1352 // --------------------------------------------------------------
1353 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1355 // if recognition code tells us we deal with a LibIDO image
1356 // we switch lineNumber and columnNumber
1358 std::string RecCode;
1359 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1360 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1361 RecCode == "CANRME_AILIBOD1_1." )
1363 filetype = ACR_LIBIDO;
1364 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1365 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1366 SetEntryByNumber(columns, 0x0028, 0x0010);
1367 SetEntryByNumber(rows , 0x0028, 0x0011);
1369 // ----------------- End of Special Patch ----------------
1373 * \ingroup gdcmParser
1374 * \brief Loads the element content if its length doesn't exceed
1375 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1376 * @param Entry Header Entry (Dicom Element) to be dealt with
1378 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1380 guint16 group = Entry->GetGroup();
1381 std::string vr= Entry->GetVR();
1382 guint32 length = Entry->GetLength();
1383 bool SkipLoad = false;
1385 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1387 // the test was commented out to 'go inside' the SeQuences
1388 // we don't any longer skip them !
1390 // if( vr == "SQ" ) // (DO NOT remove this comment)
1393 // A SeQuence "contains" a set of Elements.
1394 // (fffe e000) tells us an Element is beginning
1395 // (fffe e00d) tells us an Element just ended
1396 // (fffe e0dd) tells us the current SeQuence just ended
1397 if( group == 0xfffe )
1401 Entry->SetLength(0);
1402 Entry->SetValue("gdcm::Skipped");
1406 // When the length is zero things are easy:
1407 if ( length == 0 ) {
1408 Entry->SetValue("");
1412 // The elements whose length is bigger than the specified upper bound
1413 // are not loaded. Instead we leave a short notice of the offset of
1414 // the element content and it's length.
1415 if (length > MaxSizeLoadEntry) {
1416 std::ostringstream s;
1417 s << "gdcm::NotLoaded.";
1418 s << " Address:" << (long)Entry->GetOffset();
1419 s << " Length:" << Entry->GetLength();
1420 s << " x(" << std::hex << Entry->GetLength() << ")";
1421 Entry->SetValue(s.str());
1425 // Any compacter code suggested (?)
1426 if ( IsHeaderEntryAnInteger(Entry) ) {
1428 std::ostringstream s;
1430 // When short integer(s) are expected, read and convert the following
1431 // n *two characters properly i.e. as short integers as opposed to strings.
1432 // Elements with Value Multiplicity > 1
1433 // contain a set of integers (not a single one)
1434 if (vr == "US" || vr == "SS") {
1436 NewInt = ReadInt16();
1439 for (int i=1; i < nbInt; i++) {
1441 NewInt = ReadInt16();
1446 // When integer(s) are expected, read and convert the following
1447 // n * four characters properly i.e. as integers as opposed to strings.
1448 // Elements with Value Multiplicity > 1
1449 // contain a set of integers (not a single one)
1450 else if (vr == "UL" || vr == "SL") {
1452 NewInt = ReadInt32();
1455 for (int i=1; i < nbInt; i++) {
1457 NewInt = ReadInt32();
1462 #ifdef GDCM_NO_ANSI_STRING_STREAM
1463 s << std::ends; // to avoid oddities on Solaris
1464 #endif //GDCM_NO_ANSI_STRING_STREAM
1466 Entry->SetValue(s.str());
1470 // We need an additional byte for storing \0 that is not on disk
1471 std::string NewValue(length,0);
1472 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1473 if ( item_read != 1 ) {
1474 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1475 Entry->SetValue("gdcm::UnRead");
1479 if( (vr == "UI") ) // Because of correspondance with the VR dic
1480 Entry->SetValue(NewValue.c_str());
1482 Entry->SetValue(NewValue);
1486 * \ingroup gdcmParser
1487 * \brief add a new Dicom Element pointer to
1488 * the H Table and at the end of the chained List
1489 * \warning push_bash in listEntries ONLY during ParseHeader
1490 * \todo something to allow further Elements addition,
1491 * (at their right place in the chained list)
1492 * when position to be taken care of
1493 * @param newHeaderEntry
1495 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1496 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1497 listEntries.push_back(newHeaderEntry);
1502 * \ingroup gdcmParser
1503 * \brief Find the value Length of the passed Header Entry
1504 * @param Entry Header Entry whose length of the value shall be loaded.
1506 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1507 guint16 element = Entry->GetElement();
1508 //guint16 group = Entry->GetGroup(); //FIXME
1509 std::string vr = Entry->GetVR();
1512 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1514 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1516 // The following reserved two bytes (see PS 3.5-2001, section
1517 // 7.1.2 Data element structure with explicit vr p27) must be
1518 // skipped before proceeding on reading the length on 4 bytes.
1519 fseek(fp, 2L, SEEK_CUR);
1520 guint32 length32 = ReadInt32();
1522 if ( (vr == "OB") && (length32 == 0xffffffff) )
1524 Entry->SetLength(FindHeaderEntryLengthOB());
1527 FixHeaderEntryFoundLength(Entry, length32);
1531 // Length is encoded on 2 bytes.
1532 length16 = ReadInt16();
1534 // We can tell the current file is encoded in big endian (like
1535 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1536 // and it's value is the one of the encoding of a big endian file.
1537 // In order to deal with such big endian encoded files, we have
1538 // (at least) two strategies:
1539 // * when we load the "Transfer Syntax" tag with value of big endian
1540 // encoding, we raise the proper flags. Then we wait for the end
1541 // of the META group (0x0002) among which is "Transfer Syntax",
1542 // before switching the swap code to big endian. We have to postpone
1543 // the switching of the swap code since the META group is fully encoded
1544 // in little endian, and big endian coding only starts at the next
1545 // group. The corresponding code can be hard to analyse and adds
1546 // many additional unnecessary tests for regular tags.
1547 // * the second strategy consists in waiting for trouble, that shall
1548 // appear when we find the first group with big endian encoding. This
1549 // is easy to detect since the length of a "Group Length" tag (the
1550 // ones with zero as element number) has to be of 4 (0x0004). When we
1551 // encounter 1024 (0x0400) chances are the encoding changed and we
1552 // found a group with big endian encoding.
1553 // We shall use this second strategy. In order to make sure that we
1554 // can interpret the presence of an apparently big endian encoded
1555 // length of a "Group Length" without committing a big mistake, we
1556 // add an additional check: we look in the already parsed elements
1557 // for the presence of a "Transfer Syntax" whose value has to be "big
1558 // endian encoding". When this is the case, chances are we have got our
1559 // hands on a big endian encoded file: we switch the swap code to
1560 // big endian and proceed...
1561 if ( (element == 0x0000) && (length16 == 0x0400) )
1563 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1565 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1570 SwitchSwapToBigEndian();
1571 // Restore the unproperly loaded values i.e. the group, the element
1572 // and the dictionary entry depending on them.
1573 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1574 guint16 CorrectElem = SwapShort(Entry->GetElement());
1575 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1579 // This correct tag is not in the dictionary. Create a new one.
1580 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1582 // FIXME this can create a memory leaks on the old entry that be
1583 // left unreferenced.
1584 Entry->SetDictEntry(NewTag);
1587 // Heuristic: well some files are really ill-formed.
1588 if ( length16 == 0xffff)
1591 //dbg.Verbose(0, "gdcmParser::FindLength",
1592 // "Erroneous element length fixed.");
1593 // Actually, length= 0xffff means that we deal with
1594 // Unknown Sequence Length
1596 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1601 // Either implicit VR or a non DICOM conformal (see note below) explicit
1602 // VR that ommited the VR of (at least) this element. Farts happen.
1603 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1604 // on Data elements "Implicit and Explicit VR Data Elements shall
1605 // not coexist in a Data Set and Data Sets nested within it".]
1606 // Length is on 4 bytes.
1608 FixHeaderEntryFoundLength(Entry, ReadInt32());
1614 * \ingroup gdcmParser
1615 * \brief Find the Value Representation of the current Dicom Element.
1618 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1620 if (filetype != ExplicitVR)
1625 long PositionOnEntry = ftell(fp);
1626 // Warning: we believe this is explicit VR (Value Representation) because
1627 // we used a heuristic that found "UL" in the first tag. Alas this
1628 // doesn't guarantee that all the tags will be in explicit VR. In some
1629 // cases (see e-film filtered files) one finds implicit VR tags mixed
1630 // within an explicit VR file. Hence we make sure the present tag
1631 // is in explicit VR and try to fix things if it happens not to be
1634 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1636 if(!CheckHeaderEntryVR(Entry,VR))
1638 fseek(fp, PositionOnEntry, SEEK_SET);
1639 // When this element is known in the dictionary we shall use, e.g. for
1640 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1641 // dictionary entry. Still we have to flag the element as implicit since
1642 // we know now our assumption on expliciteness is not furfilled.
1644 if ( Entry->IsVRUnknown() )
1645 Entry->SetVR("Implicit");
1646 Entry->SetImplicitVR();
1651 * \ingroup gdcmParser
1652 * \brief Check the correspondance between the VR of the header entry
1653 * and the taken VR. If they are different, the header entry is
1654 * updated with the new VR.
1655 * @param Entry Header Entry to check
1656 * @param vr Dicom Value Representation
1657 * @return false if the VR is incorrect of if the VR isn't referenced
1658 * otherwise, it returns true
1660 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1662 char msg[100]; // for sprintf
1663 bool RealExplicit = true;
1665 // Assume we are reading a falsely explicit VR file i.e. we reached
1666 // a tag where we expect reading a VR but are in fact we read the
1667 // first to bytes of the length. Then we will interogate (through find)
1668 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1669 // both GCC and VC++ implementations of the STL map. Hence when the
1670 // expected VR read happens to be non-ascii characters we consider
1671 // we hit falsely explicit VR tag.
1673 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1674 RealExplicit = false;
1676 // CLEANME searching the dicom_vr at each occurence is expensive.
1677 // PostPone this test in an optional integrity check at the end
1678 // of parsing or only in debug mode.
1679 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1680 RealExplicit= false;
1682 if ( !RealExplicit )
1684 // We thought this was explicit VR, but we end up with an
1685 // implicit VR tag. Let's backtrack.
1686 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1687 Entry->GetGroup(),Entry->GetElement());
1688 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1689 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1690 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1691 Entry->GetGroup(),Entry->GetElement(),
1692 "UL","FIXME","Group Length");
1693 Entry->SetDictEntry(NewEntry);
1698 if ( Entry->IsVRUnknown() )
1700 // When not a dictionary entry, we can safely overwrite the VR.
1701 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1707 else if ( Entry->GetVR() != vr )
1709 // The VR present in the file and the dictionary disagree. We assume
1710 // the file writer knew best and use the VR of the file. Since it would
1711 // be unwise to overwrite the VR of a dictionary (since it would
1712 // compromise it's next user), we need to clone the actual DictEntry
1713 // and change the VR for the read one.
1714 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1715 Entry->GetGroup(),Entry->GetElement(),
1716 vr,"FIXME",Entry->GetName());
1717 Entry->SetDictEntry(NewEntry);
1723 * \ingroup gdcmParser
1724 * \brief Get the transformed value of the header entry. The VR value
1725 * is used to define the transformation to operate on the value
1726 * \warning NOT end user intended method !
1728 * @return Transformed entry value
1730 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1732 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1734 std::string val=Entry->GetValue();
1735 std::string vr=Entry->GetVR();
1736 guint32 length = Entry->GetLength();
1737 std::ostringstream s;
1740 // When short integer(s) are expected, read and convert the following
1741 // n * 2 bytes properly i.e. as a multivaluated strings
1742 // (each single value is separated fromthe next one by '\'
1743 // as usual for standard multivaluated filels
1744 // Elements with Value Multiplicity > 1
1745 // contain a set of short integers (not a single one)
1747 if (vr == "US" || vr == "SS")
1752 for (int i=0; i < nbInt; i++)
1756 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1757 NewInt16 = SwapShort(NewInt16);
1762 // When integer(s) are expected, read and convert the following
1763 // n * 4 bytes properly i.e. as a multivaluated strings
1764 // (each single value is separated fromthe next one by '\'
1765 // as usual for standard multivaluated filels
1766 // Elements with Value Multiplicity > 1
1767 // contain a set of integers (not a single one)
1768 else if (vr == "UL" || vr == "SL")
1773 for (int i=0; i < nbInt; i++)
1777 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1778 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1779 NewInt32=SwapLong(NewInt32);
1783 #ifdef GDCM_NO_ANSI_STRING_STREAM
1784 s << std::ends; // to avoid oddities on Solaris
1785 #endif //GDCM_NO_ANSI_STRING_STREAM
1789 return(Entry->GetValue());
1793 * \ingroup gdcmParser
1794 * \brief Get the reverse transformed value of the header entry. The VR
1795 * value is used to define the reverse transformation to operate on
1797 * \warning NOT end user intended method !
1799 * @return Reverse transformed entry value
1801 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1803 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1805 std::string vr=Entry->GetVR();
1806 std::ostringstream s;
1807 std::vector<std::string> tokens;
1809 if (vr == "US" || vr == "SS")
1813 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1814 Tokenize (Entry->GetValue(), tokens, "\\");
1815 for (unsigned int i=0; i<tokens.size();i++)
1817 NewInt16 = atoi(tokens[i].c_str());
1818 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1822 if (vr == "UL" || vr == "SL")
1826 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1827 Tokenize (Entry->GetValue(), tokens, "\\");
1828 for (unsigned int i=0; i<tokens.size();i++)
1830 NewInt32 = atoi(tokens[i].c_str());
1831 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1832 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1837 #ifdef GDCM_NO_ANSI_STRING_STREAM
1838 s << std::ends; // to avoid oddities on Solaris
1839 #endif //GDCM_NO_ANSI_STRING_STREAM
1843 return(Entry->GetValue());
1847 * \ingroup gdcmParser
1848 * \brief Skip a given Header Entry
1849 * \warning NOT end user intended method !
1852 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1854 SkipBytes(entry->GetLength());
1858 * \ingroup gdcmParser
1859 * \brief When the length of an element value is obviously wrong (because
1860 * the parser went Jabberwocky) one can hope improving things by
1861 * applying this heuristic.
1863 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1865 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1867 if ( FoundLength == 0xffffffff) {
1871 guint16 gr =Entry->GetGroup();
1872 guint16 el =Entry->GetElement();
1874 if (FoundLength%2) {
1875 std::ostringstream s;
1876 s << "Warning : Tag with uneven length " << FoundLength
1877 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1878 dbg.Verbose(0,s.str().c_str());
1881 // Sorry for the patch!
1882 // XMedCom did the trick to read some nasty GE images ...
1883 if (FoundLength == 13) {
1884 // The following 'if' will be removed when there is no more
1885 // images on Creatis HDs with a 13 length for Manufacturer...
1886 if ( (Entry->GetGroup() != 0x0008) ||
1887 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1888 // end of remove area
1890 Entry->SetReadLength(10); // a bug is to be fixed
1894 // to fix some garbage 'Leonardo' Siemens images
1895 // May be commented out to avoid overhead
1896 else if ( (Entry->GetGroup() == 0x0009) &&
1897 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1899 Entry->SetReadLength(4); // a bug is to be fixed
1903 // to try to 'go inside' SeQuences (with length), and not to skip them
1904 else if ( Entry->GetVR() == "SQ")
1906 if (enableSequences) // only if the user does want to !
1907 FoundLength =0; // ReadLength is unchanged
1910 // a SeQuence Element is beginning
1911 // fffe|e000 is just a marker, its length *should be* zero
1912 else if(Entry->GetGroup() == 0xfffe)
1914 // *normally, fffe|0000 doesn't exist !
1915 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1916 // causes extra troubles :-(
1919 Entry->SetUsableLength(FoundLength);
1923 * \ingroup gdcmParser
1924 * \brief Apply some heuristics to predict whether the considered
1925 * element value contains/represents an integer or not.
1926 * @param Entry The element value on which to apply the predicate.
1927 * @return The result of the heuristical predicate.
1929 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1930 guint16 element = Entry->GetElement();
1931 guint16 group = Entry->GetGroup();
1932 std::string vr = Entry->GetVR();
1933 guint32 length = Entry->GetLength();
1934 // When we have some semantics on the element we just read, and if we
1935 // a priori know we are dealing with an integer, then we shall be
1936 // able to swap it's element value properly.
1937 if ( element == 0 ) // This is the group length of the group
1943 std::ostringstream s;
1944 int filePosition = ftell(fp);
1945 s << "Erroneous Group Length element length on : (" \
1946 << std::hex << group << " , " << element
1947 << ") -before- position x(" << filePosition << ")"
1948 << "lgt : " << length;
1949 // These 2 lines commented out : a *very dirty* patch
1950 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1951 // have a glance at offset x(8336) ...
1952 // For *regular* headers, the test is useless..
1953 // lets's print a warning message and go on,
1954 // instead of giving up with an error message
1956 //std::cout << s.str().c_str() << std::endl;
1957 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1958 // s.str().c_str());
1961 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1967 * \ingroup gdcmParser
1968 * \brief Find the Length till the next sequence delimiter
1969 * \warning NOT end user intended method !
1973 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1974 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1977 long PositionOnEntry = ftell(fp);
1978 bool FoundSequenceDelimiter = false;
1979 guint32 TotalLength = 0;
1982 while ( ! FoundSequenceDelimiter)
1988 TotalLength += 4; // We even have to decount the group and element
1990 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1992 char msg[100]; // for sprintf. Sorry
1993 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1994 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1998 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1999 FoundSequenceDelimiter = true;
2000 else if ( n != 0xe000 )
2002 char msg[100]; // for sprintf. Sorry
2003 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2005 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
2009 ItemLength = ReadInt32();
2010 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2011 // the ItemLength with ReadInt32
2012 SkipBytes(ItemLength);
2014 fseek(fp, PositionOnEntry, SEEK_SET);
2019 * \ingroup gdcmParser
2020 * \brief Reads a supposed to be 16 Bits integer
2021 * (swaps it depending on processor endianity)
2022 * @return read value
2024 guint16 gdcmParser::ReadInt16(void) {
2027 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2028 if ( item_read != 1 ) {
2030 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
2040 * \ingroup gdcmParser
2041 * \brief Reads a supposed to be 32 Bits integer
2042 * (swaps it depending on processor endianity)
2043 * @return read value
2045 guint32 gdcmParser::ReadInt32(void) {
2048 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2049 if ( item_read != 1 ) {
2051 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
2061 * \ingroup gdcmParser
2062 * \brief skips bytes inside the source file
2063 * \warning NOT end user intended method !
2066 void gdcmParser::SkipBytes(guint32 NBytes) {
2067 //FIXME don't dump the returned value
2068 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2072 * \ingroup gdcmParser
2073 * \brief Loads all the needed Dictionaries
2074 * \warning NOT end user intended method !
2076 void gdcmParser::Initialise(void)
2078 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2079 RefShaDict = (gdcmDict*)0;
2083 * \ingroup gdcmParser
2084 * \brief Discover what the swap code is (among little endian, big endian,
2085 * bad little endian, bad big endian).
2087 * @return false when we are absolutely sure
2088 * it's neither ACR-NEMA nor DICOM
2089 * true when we hope ours assuptions are OK
2091 bool gdcmParser::CheckSwap() {
2093 // The only guaranted way of finding the swap code is to find a
2094 // group tag since we know it's length has to be of four bytes i.e.
2095 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2096 // occurs when we can't find such group...
2098 guint32 x=4; // x : for ntohs
2099 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2105 char deb[HEADER_LENGTH_TO_READ];
2107 // First, compare HostByteOrder and NetworkByteOrder in order to
2108 // determine if we shall need to swap bytes (i.e. the Endian type).
2114 // The easiest case is the one of a DICOM header, since it possesses a
2115 // file preamble where it suffice to look for the string "DICM".
2116 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2119 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2120 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2122 // Next, determine the value representation (VR). Let's skip to the
2123 // first element (0002, 0000) and check there if we find "UL"
2124 // - or "OB" if the 1st one is (0002,0001) -,
2125 // in which case we (almost) know it is explicit VR.
2126 // WARNING: if it happens to be implicit VR then what we will read
2127 // is the length of the group. If this ascii representation of this
2128 // length happens to be "UL" then we shall believe it is explicit VR.
2129 // FIXME: in order to fix the above warning, we could read the next
2130 // element value (or a couple of elements values) in order to make
2131 // sure we are not commiting a big mistake.
2132 // We need to skip :
2133 // * the 128 bytes of File Preamble (often padded with zeroes),
2134 // * the 4 bytes of "DICM" string,
2135 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2136 // i.e. a total of 136 bytes.
2140 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2141 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2142 // *Implicit* VR. -and it is !-
2144 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2145 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2146 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2147 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2148 // when Write DCM *adds*
2150 // Use gdcmParser::dicom_vr to test all the possibilities
2151 // instead of just checking for UL, OB and UI !? group 0000
2153 filetype = ExplicitVR;
2154 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2155 "explicit Value Representation");
2159 filetype = ImplicitVR;
2160 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2161 "not an explicit Value Representation");
2167 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2168 "HostByteOrder != NetworkByteOrder");
2173 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2174 "HostByteOrder = NetworkByteOrder");
2177 // Position the file position indicator at first tag (i.e.
2178 // after the file preamble and the "DICM" string).
2180 fseek (fp, 132L, SEEK_SET);
2184 // Alas, this is not a DicomV3 file and whatever happens there is no file
2185 // preamble. We can reset the file position indicator to where the data
2186 // is (i.e. the beginning of the file).
2187 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2190 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2191 // By clean we mean that the length of the first tag is written down.
2192 // If this is the case and since the length of the first group HAS to be
2193 // four (bytes), then determining the proper swap code is straightforward.
2196 // We assume the array of char we are considering contains the binary
2197 // representation of a 32 bits integer. Hence the following dirty
2199 s32 = *((guint32 *)(entCur));
2220 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2221 // It is time for despaired wild guesses.
2222 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2223 // i.e. the 'group length' element is not present :
2225 // check the supposed to be 'group number'
2226 // 0x0002 or 0x0004 or 0x0008
2227 // to determine ' sw' value .
2228 // Only 0 or 4321 will be possible
2229 // (no oportunity to check for the formerly well known
2230 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2231 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2232 // the file IS NOT ACR-NEMA nor DICOM V3
2233 // Find a trick to tell it the caller...
2235 s16 = *((guint16 *)(deb));
2251 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2252 "ACR/NEMA unfound swap info (Really hopeless !)");
2257 // Then the only info we have is the net2host one.
2267 * \ingroup gdcmParser
2268 * \brief Restore the unproperly loaded values i.e. the group, the element
2269 * and the dictionary entry depending on them.
2271 void gdcmParser::SwitchSwapToBigEndian(void)
2273 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2274 "Switching to BigEndian mode.");
2295 * \ingroup gdcmParser
2296 * \brief during parsing, Header Elements too long are not loaded in memory
2299 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2303 if ((guint32)NewSize >= (guint32)0xffffffff)
2305 MaxSizeLoadEntry = 0xffffffff;
2308 MaxSizeLoadEntry = NewSize;
2313 * \ingroup gdcmParser
2314 * \brief Header Elements too long will not be printed
2316 * \todo : not yet usable
2317 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2318 * in gdcmHeaderEntry gdcmLoadEntry)
2322 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2326 if ((guint32)NewSize >= (guint32)0xffffffff)
2328 MaxSizePrintEntry = 0xffffffff;
2331 MaxSizePrintEntry = NewSize;
2335 * \ingroup gdcmParser
2336 * \brief Searches both the public and the shadow dictionary (when they
2337 * exist) for the presence of the DictEntry with given name.
2338 * The public dictionary has precedence on the shadow one.
2339 * @param Name name of the searched DictEntry
2340 * @return Corresponding DictEntry when it exists, NULL otherwise.
2342 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2344 gdcmDictEntry *found = (gdcmDictEntry *)0;
2345 if (!RefPubDict && !RefShaDict)
2347 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2348 "we SHOULD have a default dictionary");
2352 found = RefPubDict->GetDictEntryByName(Name);
2358 found = RefShaDict->GetDictEntryByName(Name);
2366 * \ingroup gdcmParser
2367 * \brief Searches both the public and the shadow dictionary (when they
2368 * exist) for the presence of the DictEntry with given
2369 * group and element. The public dictionary has precedence on the
2371 * @param group group of the searched DictEntry
2372 * @param element element of the searched DictEntry
2373 * @return Corresponding DictEntry when it exists, NULL otherwise.
2375 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2377 gdcmDictEntry *found = (gdcmDictEntry *)0;
2378 if (!RefPubDict && !RefShaDict)
2380 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2381 "we SHOULD have a default dictionary");
2385 found = RefPubDict->GetDictEntryByNumber(group, element);
2391 found = RefShaDict->GetDictEntryByNumber(group, element);
2399 * \ingroup gdcmParser
2400 * \brief Read the next tag but WITHOUT loading it's value
2401 * @return On succes the newly created HeaderEntry, NULL on failure.
2403 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2405 gdcmHeaderEntry *NewEntry;
2410 // We reached the EOF (or an error occured) therefore
2411 // header parsing has to be considered as finished.
2412 return (gdcmHeaderEntry *)0;
2414 // Pb : how to propagate the element length (used in SkipHeaderEntry)
2415 // direct call to SkipBytes ?
2417 // if (ignoreShadow == 1 && g%2 ==1)
2418 // if user wants to skip shadow groups
2419 // and current element *is* a shadow element
2420 // we don't create anything
2421 // return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2423 NewEntry = NewHeaderEntryByNumber(g, n);
2424 FindHeaderEntryVR(NewEntry);
2425 FindHeaderEntryLength(NewEntry);
2431 NewEntry->SetOffset(ftell(fp));
2436 * \ingroup gdcmParser
2437 * \brief Build a new Element Value from all the low level arguments.
2438 * Check for existence of dictionary entry, and build
2439 * a default one when absent.
2440 * @param Name Name of the underlying DictEntry
2442 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2444 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2446 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2448 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2451 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2452 "failed to allocate gdcmHeaderEntry");
2453 return (gdcmHeaderEntry *)0;
2459 * \ingroup gdcmParser
2460 * \brief Request a new virtual dict entry to the dict set
2461 * @param group group of the underlying DictEntry
2462 * @param element element of the underlying DictEntry
2463 * @param vr VR of the underlying DictEntry
2464 * @param fourth owner group
2465 * @param name english name
2467 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2472 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2476 * \ingroup gdcmParser
2477 * \brief Build a new Element Value from all the low level arguments.
2478 * Check for existence of dictionary entry, and build
2479 * a default one when absent.
2480 * @param Group group of the underlying DictEntry
2481 * @param Elem element of the underlying DictEntry
2483 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2485 // Find out if the tag we encountered is in the dictionaries:
2486 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2488 DictEntry = NewVirtualDictEntry(Group, Elem);
2490 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2493 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2494 "failed to allocate gdcmHeaderEntry");
2500 // Never used; commented out, waiting for removal.
2502 * \ingroup gdcmParser
2503 * \brief Small utility function that creates a new manually crafted
2504 * (as opposed as read from the file) gdcmHeaderEntry with user
2505 * specified name and adds it to the public tag hash table.
2506 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2507 * @param NewTagName The name to be given to this new tag.
2508 * @param VR The Value Representation to be given to this new tag.
2509 * @return The newly hand crafted Element Value.
2511 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2514 // gdcmHeaderEntry *NewEntry = NULL;
2515 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2516 // guint32 FreeElem = 0;
2517 // gdcmDictEntry *DictEntry = NULL;
2519 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2520 // if (FreeElem == UINT32_MAX)
2522 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2523 // "Group 0xffff in Public Dict is full");
2527 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2528 // VR, "GDCM", NewTagName);
2529 // NewEntry = new gdcmHeaderEntry(DictEntry);
2530 // AddHeaderEntry(NewEntry);
2535 * \ingroup gdcmParser
2536 * \brief Generate a free TagKey i.e. a TagKey that is not present
2537 * in the TagHt dictionary.
2538 * @param group The generated tag must belong to this group.
2539 * @return The element of tag with given group which is fee.
2541 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2543 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2545 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2546 if (tagHT.count(key) == 0)
2552 //-----------------------------------------------------------------------------