2 //-----------------------------------------------------------------------------
4 #include "gdcmDocument.h"
5 #include "gdcmValEntry.h"
6 #include "gdcmBinEntry.h"
7 #include "gdcmSeqEntry.h"
9 #include "gdcmGlobal.h"
11 #include "gdcmDebug.h"
20 #include <netinet/in.h>
25 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
26 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
27 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
28 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
31 guint32 totalSQlength;
32 guint32 alreadyParsedlength;
35 //-----------------------------------------------------------------------------
36 // Refer to gdcmDocument::CheckSwap()
37 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
39 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
40 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
42 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
44 //-----------------------------------------------------------------------------
45 // Constructor / Destructor
49 * @param inFilename file to be opened for parsing
50 * @param exception_on_error whether we throw an exception or not
51 * @param enable_sequences = true to allow the header
52 * to be parsed *inside* the SeQuences,
53 * when they have an actual length
54 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
55 * @param ignore_shadow to allow skipping the shadow elements,
56 * to save memory space.
57 * \warning The TRUE value for this param has to be used
58 * with a FALSE value for the 'enable_sequence' param.
59 * ('public elements' may be embedded in 'shadow Sequences')
61 gdcmDocument::gdcmDocument(const char *inFilename,
62 bool exception_on_error,
63 bool enable_sequences,
65 enableSequences=enable_sequences;
66 ignoreShadow =ignore_shadow;
68 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
69 filename = inFilename;
72 if ( !OpenFile(exception_on_error))
77 // return false; // to go on compiling
79 fseek(fp,0L,SEEK_END);
87 //std::cout << "beg, lgt : " << beg << " " << lgt << std::endl;
89 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
92 printLevel = 1; // 'Medium' print level by default
97 * @param exception_on_error
99 gdcmDocument::gdcmDocument(bool exception_on_error) {
100 (void)exception_on_error;
103 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
106 printLevel = 1; // 'Medium' print level by default
110 * \brief Canonical destructor.
112 gdcmDocument::~gdcmDocument (void) {
117 //-----------------------------------------------------------------------------
123 * \brief Prints The Dict Entries of THE public Dicom Dictionary
126 void gdcmDocument::PrintPubDict(std::ostream & os) {
127 RefPubDict->Print(os);
131 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
134 void gdcmDocument::PrintShaDict(std::ostream & os) {
135 RefShaDict->Print(os);
138 //-----------------------------------------------------------------------------
141 * \brief Get the public dictionary used
143 gdcmDict *gdcmDocument::GetPubDict(void) {
148 * \brief Get the shadow dictionary used
150 gdcmDict *gdcmDocument::GetShaDict(void) {
155 * \brief Set the shadow dictionary used
156 * \param dict dictionary to use in shadow
158 bool gdcmDocument::SetShaDict(gdcmDict *dict){
164 * \brief Set the shadow dictionary used
165 * \param dictName name of the dictionary to use in shadow
167 bool gdcmDocument::SetShaDict(DictKey dictName){
168 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
173 * \brief This predicate, based on hopefully reasonable heuristics,
174 * decides whether or not the current gdcmDocument was properly parsed
175 * and contains the mandatory information for being considered as
176 * a well formed and usable Dicom/Acr File.
177 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
180 bool gdcmDocument::IsReadable(void) {
181 if(filetype==gdcmUnknown) {
184 if(listEntries.size()<=0) {
192 * \brief Determines if the Transfer Syntax was already encountered
193 * and if it corresponds to a ImplicitVRLittleEndian one.
194 * @return True when ImplicitVRLittleEndian found. False in all other cases.
196 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void) {
197 gdcmDocEntry *Element = GetDocEntryByNumber(0x0002, 0x0010);
200 LoadDocEntrySafe(Element);
202 std::string Transfer = Element->GetValue();
203 if ( Transfer == UI1_2_840_10008_1_2 )
209 * \brief Determines if the Transfer Syntax was already encountered
210 * and if it corresponds to a ExplicitVRLittleEndian one.
211 * @return True when ExplicitVRLittleEndian found. False in all other cases.
213 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void) {
214 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
217 LoadDocEntrySafe(Element);
219 std::string Transfer = Element->GetValue();
220 if ( Transfer == UI1_2_840_10008_1_2_1 )
226 * \brief Determines if the Transfer Syntax was already encountered
227 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
228 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
230 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
231 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
234 LoadDocEntrySafe(Element);
236 std::string Transfer = Element->GetValue();
237 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
243 * \brief Determines if the Transfer Syntax was already encountered
244 * and if it corresponds to a Explicit VR Big Endian one.
245 * @return True when big endian found. False in all other cases.
247 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void) {
248 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
251 LoadDocEntrySafe(Element);
253 std::string Transfer = Element->GetValue();
254 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
260 * \brief returns the File Type
261 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
262 * @return the FileType code
264 FileType gdcmDocument::GetFileType(void) {
269 * \brief opens the file
270 * @param exception_on_error
273 FILE *gdcmDocument::OpenFile(bool exception_on_error)
276 fp=fopen(filename.c_str(),"rb");
277 if(exception_on_error)
280 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
286 fread(&zero, (size_t)2, (size_t)1, fp);
288 //ACR -- or DICOM with no Preamble --
289 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
293 fseek(fp, 126L, SEEK_CUR);
295 fread(dicm, (size_t)4, (size_t)1, fp);
296 if( memcmp(dicm, "DICM", 4) == 0 )
300 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
303 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
309 * \brief closes the file
310 * @return TRUE if the close was successfull
312 bool gdcmDocument::CloseFile(void) {
313 int closed = fclose(fp);
321 * \brief Writes in a file all the Header Entries (Dicom Elements)
322 * of the Chained List
323 * @param fp file pointer on an already open file
324 * @param type Type of the File to be written
325 * (ACR-NEMA, ExplicitVR, ImplicitVR)
326 * \return Always true.
328 bool gdcmDocument::Write(FILE *fp, FileType type) {
331 /// The stuff will have to be rewritten using the SeQuence based
332 /// tree-like stucture instead of the chained list .
333 /// (so we shall remove the GroupHT from the gdcmDocument)
337 /// \todo move the following lines (and a lot of others, to be written)
338 /// to a future function CheckAndCorrectHeader
342 /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
343 /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
344 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
346 /// a moins de se livrer a un tres complique ajout des champs manquants.
347 /// faire un CheckAndCorrectHeader (?)
349 if (type == gdcmImplicitVR)
351 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
352 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
354 /// \todo Refer to standards on page 21, chapter 6.2
355 /// "Value representation": values with a VR of UI shall be
356 /// padded with a single trailing null
357 /// Dans le cas suivant on doit pader manuellement avec un 0
359 SetEntryLengthByNumber(18, 0x0002, 0x0010);
362 if (type == gdcmExplicitVR)
364 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
365 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
367 /// \todo Refer to standards on page 21, chapter 6.2
368 /// "Value representation": values with a VR of UI shall be
369 /// padded with a single trailing null
370 /// Dans le cas suivant on doit pader manuellement avec un 0
372 SetEntryLengthByNumber(20, 0x0002, 0x0010);
376 * \todo rewrite later, if really usefull
378 * --> Warning : un-updated odd groups lengths can causes pb
379 * --> (xmedcon breaks)
380 * --> to be re- written with future org.
382 * if ( (type == ImplicitVR) || (type == ExplicitVR) )
383 * UpdateGroupLength(false,type);
385 * UpdateGroupLength(true,ACR);
388 WriteEntries(fp,type);
393 * \brief Modifies the value of a given Header Entry (Dicom Element)
394 * when it exists. Create it with the given value when unexistant.
395 * \warning Adds the Header Entry to the HTable, NOT to the chained List
396 * @param Value Value to be set
397 * @param Group Group of the Entry
398 * @param Elem Element of the Entry
399 * \return pointer to the modified/created Header Entry (NULL when creation
404 gdcmDocEntry * gdcmDocument::ReplaceOrCreateByNumber(
409 a = GetDocEntryByNumber( Group, Elem);
411 a =NewDocEntryByNumber(Group, Elem);
416 SetEntryByNumber(Value, Group, Elem);
417 //a->SetValue(Value);
422 * \brief Set a new value if the invoked element exists
423 * Seems to be useless !!!
424 * @param Value new element value
425 * @param Group group of the Entry
426 * @param Elem element of the Entry
429 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
431 std::string v = Value;
432 SetEntryByNumber(v, Group, Elem);
436 //-----------------------------------------------------------------------------
440 * \brief Checks if a given Dicom Element exists
442 * @param group Group number of the searched Dicom Element
443 * @param element Element number of the searched Dicom Element
444 * @return number of occurences
446 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
447 std::string key = gdcmDictEntry::TranslateToKey(group, element );
448 return (tagHT.count(key));
452 * \brief Searches within Header Entries (Dicom Elements) parsed with
453 * the public and private dictionaries
454 * for the element value of a given tag.
455 * \warning Don't use any longer : use GetPubEntryByName
456 * @param tagName name of the searched element.
457 * @return Corresponding element value when it exists,
458 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
460 std::string gdcmDocument::GetEntryByName(std::string tagName) {
461 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
462 if( dictEntry == NULL)
465 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
469 * \brief Searches within Header Entries (Dicom Elements) parsed with
470 * the public and private dictionaries
471 * for the element value representation of a given tag.
473 * Obtaining the VR (Value Representation) might be needed by caller
474 * to convert the string typed content to caller's native type
475 * (think of C++ vs Python). The VR is actually of a higher level
476 * of semantics than just the native C++ type.
477 * @param tagName name of the searched element.
478 * @return Corresponding element value representation when it exists,
479 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
481 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
482 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
483 if( dictEntry == NULL)
486 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
487 dictEntry->GetElement());
488 return elem->GetVR();
493 * \brief Searches within Header Entries (Dicom Elements) parsed with
494 * the public and private dictionaries
495 * for the element value representation of a given tag.
496 * @param group Group of the searched tag.
497 * @param element Element of the searched tag.
498 * @return Corresponding element value representation when it exists,
499 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
501 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
502 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
503 if ( ! tagHT.count(key))
505 return tagHT.find(key)->second->GetValue();
509 * \brief Searches within Header Entries (Dicom Elements) parsed with
510 * the public and private dictionaries
511 * for the element value representation of a given tag..
513 * Obtaining the VR (Value Representation) might be needed by caller
514 * to convert the string typed content to caller's native type
515 * (think of C++ vs Python). The VR is actually of a higher level
516 * of semantics than just the native C++ type.
517 * @param group Group of the searched tag.
518 * @param element Element of the searched tag.
519 * @return Corresponding element value representation when it exists,
520 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
522 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
523 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
526 return elem->GetVR();
530 * \brief Searches within Header Entries (Dicom Elements) parsed with
531 * the public and private dictionaries
532 * for the value length of a given tag..
533 * @param group Group of the searched tag.
534 * @param element Element of the searched tag.
535 * @return Corresponding element length; -2 if not found
537 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
538 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
541 return elem->GetLength();
544 * \brief Sets the value (string) of the Header Entry (Dicom Element)
545 * @param content string value of the Dicom Element
546 * @param tagName name of the searched Dicom Element.
547 * @return true when found
549 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
550 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
551 if( dictEntry == NULL)
554 return(SetEntryByNumber(content,dictEntry->GetGroup(),
555 dictEntry->GetElement()));
559 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
560 * through it's (group, element) and modifies it's content with
562 * @param content new value to substitute with
563 * @param group group of the Dicom Element to modify
564 * @param element element of the Dicom Element to modify
566 bool gdcmDocument::SetEntryByNumber(std::string content,
570 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
571 if ( ! tagHT.count(key))
573 int l = content.length();
574 if(l%2) // Non even length are padded with a space (020H).
577 content = content + '\0';
582 TagDocEntryHT::iterator p2;
583 // DO NOT remove the following lines : they explain the stuff
584 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
585 //p2=p.first; // iterator on the first synonym
586 //a=p2->second; // H Table target column (2-nd col)
590 // Oops ! this was for multimap, right ?
591 a = ((tagHT.equal_range(key)).first)->second;
593 ((gdcmValEntry*)a)->SetValue(content);
595 std::string vr = a->GetVR();
598 if( (vr == "US") || (vr == "SS") )
600 else if( (vr == "UL") || (vr == "SL") )
610 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
611 * in the PubDocEntrySet of this instance
612 * through it's (group, element) and modifies it's length with
614 * \warning Use with extreme caution.
615 * @param l new length to substitute with
616 * @param group group of the Entry to modify
617 * @param element element of the Entry to modify
618 * @return true on success, false otherwise.
620 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
624 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
625 if ( ! tagHT.count(key))
627 if (l%2) l++; // length must be even
628 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
634 * \brief Gets (from Header) the offset of a 'non string' element value
635 * (LoadElementValues has already be executed)
636 * @param Group group of the Entry
637 * @param Elem element of the Entry
638 * @return File Offset of the Element Value
640 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
642 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
645 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
646 "failed to Locate gdcmDocEntry");
649 return Entry->GetOffset();
653 * \brief Gets (from Header) a 'non string' element value
654 * (LoadElementValues has already be executed)
655 * @param Group group of the Entry
656 * @param Elem element of the Entry
657 * @return Pointer to the 'non string' area
659 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
661 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
664 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
665 "failed to Locate gdcmDocEntry");
668 return ((gdcmBinEntry *)Entry)->GetVoidArea();
672 * \brief Loads (from disk) the element content
673 * when a string is not suitable
674 * @param Group group of the Entry
675 * @param Elem element of the Entry
677 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
679 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
682 size_t o =(size_t)Element->GetOffset();
683 fseek(fp, o, SEEK_SET);
684 size_t l=Element->GetLength();
685 char* a = new char[l];
689 SetEntryVoidAreaByNumber(a, Group, Elem);
690 /// \todo check the result
691 size_t l2 = fread(a, 1, l ,fp);
702 * \brief Sets a 'non string' value to a given Dicom Element
704 * @param group Group number of the searched Dicom Element
705 * @param element Element number of the searched Dicom Element
708 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
712 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
713 if ( ! tagHT.count(key))
715 // This was for multimap ?
716 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
722 * \brief Update the entries with the shadow dictionary.
723 * Only non even entries are analyzed
725 void gdcmDocument::UpdateShaEntries(void) {
726 gdcmDictEntry *entry;
729 for(ListTag::iterator it=listEntries.begin();
730 it!=listEntries.end();
733 // Odd group => from public dictionary
734 if((*it)->GetGroup()%2==0)
737 // Peer group => search the corresponding dict entry
739 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
743 if((*it)->IsImplicitVR())
748 //(*it)->SetValue(GetDocEntryUnvalue(*it));
749 // to go on compiling
751 // Set the new entry and the new value
752 (*it)->SetDictEntry(entry);
753 CheckDocEntryVR(*it,vr);
755 //(*it)->SetValue(GetDocEntryValue(*it));
756 // to go on compiling
761 // Remove precedent value transformation
762 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
768 * \brief Searches within the Header Entries for a Dicom Element of
770 * @param tagName name of the searched Dicom Element.
771 * @return Corresponding Dicom Element when it exists, and NULL
774 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
775 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
776 if( dictEntry == NULL)
779 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
783 * \brief retrieves a Dicom Element (the first one) using (group, element)
784 * \warning (group, element) IS NOT an identifier inside the Dicom Header
785 * if you think it's NOT UNIQUE, check the count number
786 * and use iterators to retrieve ALL the Dicoms Elements within
787 * a given couple (group, element)
788 * @param group Group number of the searched Dicom Element
789 * @param element Element number of the searched Dicom Element
792 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
794 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
795 if ( ! tagHT.count(key))
797 return tagHT.find(key)->second;
801 * \brief retrieves the Dicom Elements (all of them) using (group, element)
802 * @param group Group number of the searched Dicom Element.
803 * @param element Element number of the searched Dicom Element.
804 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
807 IterHT gdcmDocument::GetDocEntrySameNumber(guint16 group, guint16 element){
808 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
809 return (tagHT.equal_range(key));
813 * \brief Loads the element while preserving the current
814 * underlying file position indicator as opposed to
815 * to LoadDocEntry that modifies it.
816 * @param entry Header Entry whose value shall be loaded.
819 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
820 long PositionOnEntry = ftell(fp);
822 fseek(fp, PositionOnEntry, SEEK_SET);
826 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
827 * \warning : to be re-written using the chained list instead of the H table.
828 * \warning : DO NOT use (doesn't work any longer because of the multimap)
829 * \todo : to be re-written using the chained list instead of the H table
830 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
831 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
834 /* Probabely useless, now !
836 void gdcmDocument::UpdateGroupLength(bool SkipSequence, FileType type) {
842 std::string str_trash;
845 GroupHT groupHt; // to hold the length of each group
848 // typedef std::map<GroupKey, int> GroupHT;
852 // for each Tag in the DCM Header
854 for (TagDocEntryHT::iterator tag2 = tagHT.begin();
859 gr = elem->GetGroup();
860 el = elem->GetElement();
863 sprintf(trash, "%04x", gr);
864 key = trash; // generate 'group tag'
866 // if the caller decided not to take SEQUENCEs into account
867 // e.g : he wants to write an ACR-NEMA File
869 if (SkipSequence && vr == "SQ")
872 // Still unsolved problem :
873 // we cannot find the 'Sequence Delimitation Item'
874 // since it's at the end of the Hash Table
877 // there is SEQUENCE in ACR-NEMA
879 // --> la descente a l'interieur' des SQ
880 // devrait etre faite avec une liste chainee, pas avec une HTable...
882 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
884 if (el == 0x0000) // the first elem is 0x0000
886 groupHt[key] = 0; // initialize group length
890 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
893 else // any elem but the first
895 if (type == ExplicitVR)
897 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
899 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
902 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
906 unsigned short int gr_bid;
908 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
912 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
913 // warning: unsigned int format, different type arg
914 sscanf(g->first.c_str(),"%x",&gr_bid); //FIXME
915 tk = g->first + "|0000"; // generate the element full tag
917 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
919 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
920 elemZ = new gdcmDocEntry(tagZ);
922 AddEntry(elemZ); // create it
926 elemZ=GetDocEntryByNumber(gr_bid, 0x0000);
928 sprintf(trash ,"%d",g->second);
930 //elemZ->SetValue(str_trash); // to go on compiling
937 * \brief Writes in a file (according to the requested format)
938 * the group, the element, the value representation and the length
939 * of a single gdcmDocEntry passed as argument.
940 * @param tag pointer on the gdcmDocEntry to be written
941 * @param _fp already open file pointer
942 * @param type type of the File to be written
944 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
948 guint16 group = tag->GetGroup();
949 std::string vr = tag->GetVR();
950 guint16 el = tag->GetElement();
951 guint32 lgr = tag->GetReadLength();
953 if ( (group == 0xfffe) && (el == 0x0000) )
954 // Fix in order to make some MR PHILIPS images e-film readable
955 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
956 // we just *always* ignore spurious fffe|0000 tag !
959 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
960 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
962 if ( type == gdcmExplicitVR ) {
964 // Special case of delimiters:
965 if (group == 0xfffe) {
966 // Delimiters have NO Value Representation and have NO length.
967 // Hence we skip writing the VR and length and we pad by writing
971 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
976 guint16 shortLgr = lgr;
977 if (vr == "unkn") { // Unknown was 'written'
978 // deal with Little Endian
979 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
980 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
982 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
983 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
985 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
986 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
988 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
994 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
999 * \brief Writes in a file (according to the requested format)
1000 * the value of a single gdcmDocEntry passed as argument.
1001 * @param tag Pointer on the gdcmDocEntry to be written
1002 * @param _fp Already open file pointer
1003 * @param type type of the File to be written
1006 // TODO : to be re -written recursively !
1008 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1011 guint16 group = tag->GetGroup();
1012 std::string vr = tag->GetVR();
1013 guint32 lgr = tag->GetReadLength();
1016 // SeQuences have no value:
1018 if (group == 0xfffe)
1019 // Delimiters have no associated value:
1023 // voidArea = tag->GetVoidArea();
1024 // to go on compiling
1025 if (voidArea != NULL)
1026 { // there is a 'non string' LUT, overlay, etc
1027 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1031 if (vr == "US" || vr == "SS")
1033 // some 'Short integer' fields may be mulivaluated
1034 // each single value is separated from the next one by '\'
1035 // we split the string and write each value as a short int
1036 std::vector<std::string> tokens;
1037 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1038 Tokenize (tag->GetValue(), tokens, "\\");
1039 for (unsigned int i=0; i<tokens.size();i++)
1041 guint16 val_uint16 = atoi(tokens[i].c_str());
1042 void *ptr = &val_uint16;
1043 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1048 // some 'Integer' fields may be mulivaluated
1049 // each single value is separated from the next one by '\'
1050 // we split the string and write each value as an int
1051 if (vr == "UL" || vr == "SL")
1053 std::vector<std::string> tokens;
1054 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1055 Tokenize (tag->GetValue(), tokens, "\\");
1056 for (unsigned int i=0; i<tokens.size();i++)
1058 guint32 val_uint32 = atoi(tokens[i].c_str());
1059 void *ptr = &val_uint32;
1060 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1065 fwrite (tag->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1069 * \brief Writes in a file (according to the requested format)
1070 * a single gdcmDocEntry passed as argument.
1071 * \sa WriteEntryValue, WriteEntryTagVRLength.
1072 * @param tag Pointer on the gdcmDocEntry to be written
1073 * @param _fp Already open file pointer
1074 * @param type type of the File to be written
1077 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1079 guint32 length = tag->GetLength();
1081 // The value of a tag MUST (see the DICOM norm) be an odd number of
1082 // bytes. When this is not the case, pad with an additional byte:
1085 // tag->SetValue(tag->GetValue()+"\0");
1086 // to go on compiling
1087 tag->SetLength(tag->GetReadLength()+1);
1090 WriteEntryTagVRLength(tag, _fp, type);
1091 WriteEntryValue(tag, _fp, type);
1096 * \brief writes on disc according to the requested format
1097 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1098 * using the Chained List
1099 * \warning does NOT add the missing elements in the header :
1100 * it's up to the user doing it !
1101 * (function CheckHeaderCoherence to be written)
1102 * \warning DON'T try, right now, to write a DICOM image
1103 * from an ACR Header (meta elements will be missing!)
1104 * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1105 * @param type type of the File to be written
1106 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1107 * @param _fp already open file pointer
1110 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1112 /// \todo (?) check write failures (after *each* fwrite)
1114 for (ListTag::iterator tag2=listEntries.begin();
1115 tag2 != listEntries.end();
1118 if ( type == gdcmACR ){
1119 if ((*tag2)->GetGroup() < 0x0008)
1120 // Ignore pure DICOM V3 groups
1122 if ((*tag2)->GetElement() %2)
1123 // Ignore the "shadow" groups
1125 if ((*tag2)->GetVR() == "SQ" ) // ignore Sequences
1127 if ((*tag2)->GetSQDepthLevel() != 0) // Not only ignore the SQ element
1130 if (! WriteEntry(*tag2,_fp,type) )
1137 * \brief writes on disc according to the requested format
1138 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1139 * using only the last synonym of each mutimap H Table post.
1140 * \warning Uses the H Table, instead of the Chained List
1141 * in order to be compliant with the old way to proceed
1142 * (added elements taken in to account)
1143 * Only THERALYS, during a transitory phase is supposed
1144 * to use this method !!!
1145 * \warning DON'T try, right now, to write a DICOM image
1146 * from an ACR Header (meta elements will be missing!)
1148 * @param _fp already open file pointer
1149 * @param type type of the File to be written
1150 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1152 void gdcmDocument::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1154 // restent a tester les echecs en ecriture (apres chaque fwrite)
1156 for (TagDocEntryHT::iterator tag2=tagHT.begin();
1157 tag2 != tagHT.end();
1159 if ( type == gdcmACR ){
1160 if ((*tag2->second).GetGroup() < 0x0008) continue; // ignore pure DICOM V3 groups
1161 if ((*tag2->second).GetElement() %2) continue; // ignore shadow groups
1162 if ((*tag2->second).GetVR() == "SQ" ) continue; // ignore Sequences
1163 if ((*tag2->second).GetSQDepthLevel() != 0) continue; // Not only ignore the SQ element
1165 if ( ! WriteEntry(tag2->second,_fp,type))
1171 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1173 * @return The properly swaped 32 bits integer.
1175 guint32 gdcmDocument::SwapLong(guint32 a) {
1180 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1181 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1185 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1189 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1192 std::cout << "swapCode= " << sw << std::endl;
1193 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1200 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1202 * @return The properly unswaped 32 bits integer.
1204 guint32 gdcmDocument::UnswapLong(guint32 a) {
1205 return (SwapLong(a));
1209 * \brief Swaps the bytes so they agree with the processor order
1210 * @return The properly swaped 16 bits integer.
1212 guint16 gdcmDocument::SwapShort(guint16 a) {
1213 if ( (sw==4321) || (sw==2143) )
1214 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1219 * \brief Unswaps the bytes so they agree with the processor order
1220 * @return The properly unswaped 16 bits integer.
1222 guint16 gdcmDocument::UnswapShort(guint16 a) {
1223 return (SwapShort(a));
1226 //-----------------------------------------------------------------------------
1232 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1233 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1236 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1238 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1245 NewDocEntry = ReadNextDocEntry( );
1249 std::cout << hex << NewDocEntry->GetGroup()
1251 << NewDocEntry->GetElement()
1253 << NewDocEntry->GetVR()
1255 << NewDocEntry->GetReadLength()
1257 << NewDocEntry->GetOffset()
1260 vr = NewDocEntry->GetVR();
1263 if (vr == "AE" || vr == "AS" || vr == "DA" || vr == "PN" ||
1264 vr == "UI" || vr == "TM" || vr == "SH" || vr == "LO" ||
1265 vr == "CS" || vr == "IS" || vr == "LO" || vr == "LT" ||
1266 vr == "SH" || vr == "ST" ||
1267 vr == "SL" || vr == "SS" || vr == "UL" || vr == "US"
1270 vl= new gdcmValEntry(NewDocEntry->GetDictEntry());
1271 vl->Copy(NewDocEntry);
1274 std::cout << "value [" << vl->GetValue() << "]" << std::endl;
1275 if (!delim_mode && vl->isItemDelimitor())
1277 } else { // BinEntry
1279 // Hope the following VR *do* correspond to a BinEntry
1281 //AT Attribute Tag; // 2 16-bit unsigned short integers
1282 //FL Floating Point Single; // 32-bit IEEE 754:1985 float
1283 //FD Floating Point Double; // 64-bit IEEE 754:1985 double
1284 //UN Unknown; // Any length of bytes
1285 //UT Unlimited Text; // At most 2^32 -1 chars
1286 //OB Other Byte String; // String of bytes (VR independant)
1287 //OW Other Word String; // String of 16-bit words (VR dependant)
1289 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1290 bn->Copy(NewDocEntry);
1292 std::cout << "value [" << "Bin Entry, in voidArea" << "]" << std::endl;
1295 SkipToNextDocEntry(NewDocEntry); // to be sure to be at the beginning
1296 l = NewDocEntry->GetFullLength();
1298 } else { // VR = "SQ"
1300 //SkipDocEntry(NewDocEntry);
1302 std::cout << "gdcmDocument::ParseDES : SQ found " << std::endl;
1303 l=NewDocEntry->GetReadLength();
1304 if (l == 0xffffffff)
1308 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry());
1309 sq->Copy(NewDocEntry);
1310 sq->SetDelimitorMode(delim_mode);
1311 long lgt = ParseSQ((gdcmDocEntrySet *)sq, offset, l, delim_mode);
1312 // FIXME : on en fait quoi, de lgt ?
1314 if ( !delim_mode && ftell(fp)-offset >= l_max)
1326 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1327 * @return parsed length for this level
1331 long gdcmDocument::ParseSQ(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1333 std::cout << "Entree ds gdcmDocument::ParseSQ" << std::endl;
1335 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1339 cout << "=============== on entre ds une Sequence" <<endl;
1342 std::cout << "gdcmDocument::ParseSQ on itere" << std::endl;
1345 NewDocEntry = ReadNextDocEntry();
1346 if (NewDocEntry->isSequenceDelimitor()) {
1347 // add the Sequence Delimitor // TODO : find the trick to put it proprerly !
1348 // ((gdcmSeqEntry *)set)->SetSequenceDelimitationItem(NewDocEntry);
1352 if (!delim_mode && (ftell(fp)-offset) >= l_max){
1355 itemSQ = new gdcmSQItem();
1356 itemSQ->AddEntry(NewDocEntry); // no value, no voidArea. Think of it while printing !
1357 l= NewDocEntry->GetLength();
1363 lgr=ParseDES(itemSQ, offset, l, dlm_mod);
1364 ((gdcmSeqEntry *)set)->AddEntry(itemSQ);
1367 lgth = ftell(fp) - offset;
1368 cout << "=============== lgr Sequence :" << lgth <<endl;
1374 * \brief Parses the header of the file and load element values.
1375 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1378 /* =======================================================================
1379 // Replaced by ParseSQ
1381 bool gdcmDocument::LoadHeaderEntries(bool exception_on_error) throw(gdcmFormatError) {
1382 (void)exception_on_error;
1387 gdcmDocEntry *newDocEntry = (gdcmDocEntry *)0;
1388 while ( (newDocEntry = ReadNextDocEntry()) ) {
1389 SkipDocEntry(newDocEntry);
1390 if ( (ignoreShadow==0) || (newDocEntry->GetGroup()%2) == 0) {
1391 AddEntry(newDocEntry);
1395 // Be carefull : merging this two loops may cause troubles ...
1396 for (ListTag::iterator i = GetListEntry().begin();
1397 i != GetListEntry().end();
1404 // Load 'non string' values
1407 // --------------------------------------------------------------
1408 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1410 // if recognition code tells us we deal with a LibIDO image
1411 // we switch lineNumber and columnNumber
1413 std::string RecCode;
1414 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1415 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1416 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
1417 // with "little-endian strings"
1419 filetype = ACR_LIBIDO;
1420 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1421 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1422 SetEntryByNumber(columns, 0x0028, 0x0010);
1423 SetEntryByNumber(rows , 0x0028, 0x0011);
1425 // ----------------- End of Special Patch ----------------
1428 ======================================================================= */
1432 * \brief Loads the element content if its length doesn't exceed
1433 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1434 * @param Entry Header Entry (Dicom Element) to be dealt with
1436 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry) {
1438 guint16 group = Entry->GetGroup();
1439 std::string vr= Entry->GetVR();
1440 guint32 length = Entry->GetLength();
1442 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1444 // A SeQuence "contains" a set of Elements.
1445 // (fffe e000) tells us an Element is beginning
1446 // (fffe e00d) tells us an Element just ended
1447 // (fffe e0dd) tells us the current SeQuence just ended
1448 if( group == 0xfffe ) {
1449 // NO more value field for SQ !
1450 //Entry->SetValue("gdcm::Skipped");
1451 // appel recursif de Load Value
1452 // (meme pb que pour le parsing)
1456 // When the length is zero things are easy:
1457 if ( length == 0 ) {
1458 ((gdcmValEntry *)Entry)->SetValue("");
1462 // The elements whose length is bigger than the specified upper bound
1463 // are not loaded. Instead we leave a short notice of the offset of
1464 // the element content and it's length.
1465 if (length > MaxSizeLoadEntry) {
1466 std::ostringstream s;
1467 s << "gdcm::NotLoaded.";
1468 s << " Address:" << (long)Entry->GetOffset();
1469 s << " Length:" << Entry->GetLength();
1470 s << " x(" << std::hex << Entry->GetLength() << ")";
1471 ((gdcmValEntry *)Entry)->SetValue(s.str());
1475 // Any compacter code suggested (?)
1476 if ( IsDocEntryAnInteger(Entry) ) {
1478 std::ostringstream s;
1480 // When short integer(s) are expected, read and convert the following
1481 // n *two characters properly i.e. as short integers as opposed to strings.
1482 // Elements with Value Multiplicity > 1
1483 // contain a set of integers (not a single one)
1484 if (vr == "US" || vr == "SS") {
1486 NewInt = ReadInt16();
1489 for (int i=1; i < nbInt; i++) {
1491 NewInt = ReadInt16();
1496 // When integer(s) are expected, read and convert the following
1497 // n * four characters properly i.e. as integers as opposed to strings.
1498 // Elements with Value Multiplicity > 1
1499 // contain a set of integers (not a single one)
1500 else if (vr == "UL" || vr == "SL") {
1502 NewInt = ReadInt32();
1505 for (int i=1; i < nbInt; i++) {
1507 NewInt = ReadInt32();
1512 #ifdef GDCM_NO_ANSI_STRING_STREAM
1513 s << std::ends; // to avoid oddities on Solaris
1514 #endif //GDCM_NO_ANSI_STRING_STREAM
1516 ((gdcmValEntry *)Entry)->SetValue(s.str());
1520 // We need an additional byte for storing \0 that is not on disk
1521 std::string NewValue(length,0);
1522 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1523 if ( item_read != 1 ) {
1524 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1525 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1529 if( (vr == "UI") ) // Because of correspondance with the VR dic
1530 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1532 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1537 * \brief Find the value Length of the passed Header Entry
1538 * @param Entry Header Entry whose length of the value shall be loaded.
1540 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1541 guint16 element = Entry->GetElement();
1542 //guint16 group = Entry->GetGroup(); //FIXME
1543 std::string vr = Entry->GetVR();
1547 if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1549 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1551 // The following reserved two bytes (see PS 3.5-2001, section
1552 // 7.1.2 Data element structure with explicit vr p27) must be
1553 // skipped before proceeding on reading the length on 4 bytes.
1554 fseek(fp, 2L, SEEK_CUR);
1555 guint32 length32 = ReadInt32();
1557 if ( (vr == "OB") && (length32 == 0xffffffff) )
1559 Entry->SetLength(FindDocEntryLengthOB());
1562 FixDocEntryFoundLength(Entry, length32);
1566 // Length is encoded on 2 bytes.
1567 length16 = ReadInt16();
1569 // We can tell the current file is encoded in big endian (like
1570 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1571 // and it's value is the one of the encoding of a big endian file.
1572 // In order to deal with such big endian encoded files, we have
1573 // (at least) two strategies:
1574 // * when we load the "Transfer Syntax" tag with value of big endian
1575 // encoding, we raise the proper flags. Then we wait for the end
1576 // of the META group (0x0002) among which is "Transfer Syntax",
1577 // before switching the swap code to big endian. We have to postpone
1578 // the switching of the swap code since the META group is fully encoded
1579 // in little endian, and big endian coding only starts at the next
1580 // group. The corresponding code can be hard to analyse and adds
1581 // many additional unnecessary tests for regular tags.
1582 // * the second strategy consists in waiting for trouble, that shall
1583 // appear when we find the first group with big endian encoding. This
1584 // is easy to detect since the length of a "Group Length" tag (the
1585 // ones with zero as element number) has to be of 4 (0x0004). When we
1586 // encounter 1024 (0x0400) chances are the encoding changed and we
1587 // found a group with big endian encoding.
1588 // We shall use this second strategy. In order to make sure that we
1589 // can interpret the presence of an apparently big endian encoded
1590 // length of a "Group Length" without committing a big mistake, we
1591 // add an additional check: we look in the already parsed elements
1592 // for the presence of a "Transfer Syntax" whose value has to be "big
1593 // endian encoding". When this is the case, chances are we have got our
1594 // hands on a big endian encoded file: we switch the swap code to
1595 // big endian and proceed...
1596 if ( (element == 0x0000) && (length16 == 0x0400) )
1598 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1600 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1605 SwitchSwapToBigEndian();
1606 // Restore the unproperly loaded values i.e. the group, the element
1607 // and the dictionary entry depending on them.
1608 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1609 guint16 CorrectElem = SwapShort(Entry->GetElement());
1610 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1614 // This correct tag is not in the dictionary. Create a new one.
1615 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1617 // FIXME this can create a memory leaks on the old entry that be
1618 // left unreferenced.
1619 Entry->SetDictEntry(NewTag);
1622 // Heuristic: well some files are really ill-formed.
1623 if ( length16 == 0xffff)
1626 //dbg.Verbose(0, "gdcmDocument::FindLength",
1627 // "Erroneous element length fixed.");
1628 // Actually, length= 0xffff means that we deal with
1629 // Unknown Sequence Length
1631 FixDocEntryFoundLength(Entry, (guint32)length16);
1636 // Either implicit VR or a non DICOM conformal (see note below) explicit
1637 // VR that ommited the VR of (at least) this element. Farts happen.
1638 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1639 // on Data elements "Implicit and Explicit VR Data Elements shall
1640 // not coexist in a Data Set and Data Sets nested within it".]
1641 // Length is on 4 bytes.
1643 FixDocEntryFoundLength(Entry, ReadInt32());
1649 * \brief Find the Value Representation of the current Dicom Element.
1652 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1654 if (filetype != gdcmExplicitVR)
1659 long PositionOnEntry = ftell(fp);
1660 // Warning: we believe this is explicit VR (Value Representation) because
1661 // we used a heuristic that found "UL" in the first tag. Alas this
1662 // doesn't guarantee that all the tags will be in explicit VR. In some
1663 // cases (see e-film filtered files) one finds implicit VR tags mixed
1664 // within an explicit VR file. Hence we make sure the present tag
1665 // is in explicit VR and try to fix things if it happens not to be
1668 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1670 if(!CheckDocEntryVR(Entry,VR))
1672 fseek(fp, PositionOnEntry, SEEK_SET);
1673 // When this element is known in the dictionary we shall use, e.g. for
1674 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1675 // dictionary entry. Still we have to flag the element as implicit since
1676 // we know now our assumption on expliciteness is not furfilled.
1678 if ( Entry->IsVRUnknown() )
1679 Entry->SetVR("Implicit");
1680 Entry->SetImplicitVR();
1685 * \brief Check the correspondance between the VR of the header entry
1686 * and the taken VR. If they are different, the header entry is
1687 * updated with the new VR.
1688 * @param Entry Header Entry to check
1689 * @param vr Dicom Value Representation
1690 * @return false if the VR is incorrect of if the VR isn't referenced
1691 * otherwise, it returns true
1693 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1695 char msg[100]; // for sprintf
1696 bool RealExplicit = true;
1698 // Assume we are reading a falsely explicit VR file i.e. we reached
1699 // a tag where we expect reading a VR but are in fact we read the
1700 // first to bytes of the length. Then we will interogate (through find)
1701 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1702 // both GCC and VC++ implementations of the STL map. Hence when the
1703 // expected VR read happens to be non-ascii characters we consider
1704 // we hit falsely explicit VR tag.
1706 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1707 RealExplicit = false;
1709 // CLEANME searching the dicom_vr at each occurence is expensive.
1710 // PostPone this test in an optional integrity check at the end
1711 // of parsing or only in debug mode.
1712 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1713 RealExplicit= false;
1715 if ( !RealExplicit )
1717 // We thought this was explicit VR, but we end up with an
1718 // implicit VR tag. Let's backtrack.
1719 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1720 Entry->GetGroup(),Entry->GetElement());
1721 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1722 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1723 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1724 Entry->GetGroup(),Entry->GetElement(),
1725 "UL","FIXME","Group Length");
1726 Entry->SetDictEntry(NewEntry);
1731 if ( Entry->IsVRUnknown() )
1733 // When not a dictionary entry, we can safely overwrite the VR.
1734 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1740 else if ( Entry->GetVR() != vr )
1742 // The VR present in the file and the dictionary disagree. We assume
1743 // the file writer knew best and use the VR of the file. Since it would
1744 // be unwise to overwrite the VR of a dictionary (since it would
1745 // compromise it's next user), we need to clone the actual DictEntry
1746 // and change the VR for the read one.
1747 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1748 Entry->GetGroup(),Entry->GetElement(),
1749 vr,"FIXME",Entry->GetName());
1750 Entry->SetDictEntry(NewEntry);
1756 * \brief Get the transformed value of the header entry. The VR value
1757 * is used to define the transformation to operate on the value
1758 * \warning NOT end user intended method !
1760 * @return Transformed entry value
1762 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1764 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1766 std::string val=Entry->GetValue();
1767 std::string vr=Entry->GetVR();
1768 guint32 length = Entry->GetLength();
1769 std::ostringstream s;
1772 // When short integer(s) are expected, read and convert the following
1773 // n * 2 bytes properly i.e. as a multivaluated strings
1774 // (each single value is separated fromthe next one by '\'
1775 // as usual for standard multivaluated filels
1776 // Elements with Value Multiplicity > 1
1777 // contain a set of short integers (not a single one)
1779 if (vr == "US" || vr == "SS")
1784 for (int i=0; i < nbInt; i++)
1788 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1789 NewInt16 = SwapShort(NewInt16);
1794 // When integer(s) are expected, read and convert the following
1795 // n * 4 bytes properly i.e. as a multivaluated strings
1796 // (each single value is separated fromthe next one by '\'
1797 // as usual for standard multivaluated filels
1798 // Elements with Value Multiplicity > 1
1799 // contain a set of integers (not a single one)
1800 else if (vr == "UL" || vr == "SL")
1805 for (int i=0; i < nbInt; i++)
1809 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1810 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1811 NewInt32=SwapLong(NewInt32);
1815 #ifdef GDCM_NO_ANSI_STRING_STREAM
1816 s << std::ends; // to avoid oddities on Solaris
1817 #endif //GDCM_NO_ANSI_STRING_STREAM
1821 return(Entry->GetValue());
1825 * \brief Get the reverse transformed value of the header entry. The VR
1826 * value is used to define the reverse transformation to operate on
1828 * \warning NOT end user intended method !
1830 * @return Reverse transformed entry value
1832 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1834 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1836 std::string vr=Entry->GetVR();
1837 std::ostringstream s;
1838 std::vector<std::string> tokens;
1840 if (vr == "US" || vr == "SS")
1844 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1845 Tokenize (Entry->GetValue(), tokens, "\\");
1846 for (unsigned int i=0; i<tokens.size();i++)
1848 NewInt16 = atoi(tokens[i].c_str());
1849 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1853 if (vr == "UL" || vr == "SL")
1857 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1858 Tokenize (Entry->GetValue(), tokens, "\\");
1859 for (unsigned int i=0; i<tokens.size();i++)
1861 NewInt32 = atoi(tokens[i].c_str());
1862 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1863 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1868 #ifdef GDCM_NO_ANSI_STRING_STREAM
1869 s << std::ends; // to avoid oddities on Solaris
1870 #endif //GDCM_NO_ANSI_STRING_STREAM
1874 return(Entry->GetValue());
1878 * \brief Skip a given Header Entry
1879 * \warning NOT end user intended method !
1882 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1884 SkipBytes(entry->GetLength());
1888 * \brief Skips to the begining of the next Header Entry
1889 * \warning NOT end user intended method !
1892 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1894 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1895 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1899 * \brief Loads the value for a a given VLEntry
1900 * \warning NOT end user intended method !
1903 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
1905 //SkipBytes(entry->GetLength());
1906 LoadDocEntry(entry);
1909 * \brief When the length of an element value is obviously wrong (because
1910 * the parser went Jabberwocky) one can hope improving things by
1911 * applying this heuristic.
1913 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry, guint32 FoundLength)
1915 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1916 if ( FoundLength == 0xffffffff) {
1920 guint16 gr =Entry->GetGroup();
1921 guint16 el =Entry->GetElement();
1923 if (FoundLength%2) {
1924 std::ostringstream s;
1925 s << "Warning : Tag with uneven length " << FoundLength
1926 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1927 dbg.Verbose(0,s.str().c_str());
1930 // Sorry for the patch!
1931 // XMedCom did the trick to read some naughty GE images ...
1932 if (FoundLength == 13) {
1933 // The following 'if' will be removed when there is no more
1934 // images on Creatis HDs with a 13 length for Manufacturer...
1935 if ( (Entry->GetGroup() != 0x0008) ||
1936 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1937 // end of remove area
1939 Entry->SetReadLength(10); // a bug is to be fixed
1943 // to fix some garbage 'Leonardo' Siemens images
1944 // May be commented out to avoid overhead
1945 else if ( (Entry->GetGroup() == 0x0009) &&
1946 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1948 Entry->SetReadLength(4); // a bug is to be fixed
1952 // to try to 'go inside' SeQuences (with length), and not to skip them
1953 else if ( Entry->GetVR() == "SQ")
1955 if (enableSequences) // only if the user does want to !
1956 FoundLength =0; // ReadLength is unchanged
1959 // we found a 'delimiter' element
1960 // fffe|xxxx is just a marker, we don't take its length into account
1961 else if(Entry->GetGroup() == 0xfffe)
1963 // *normally, fffe|0000 doesn't exist !
1964 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1965 // causes extra troubles :-(
1969 Entry->SetUsableLength(FoundLength);
1973 * \brief Apply some heuristics to predict whether the considered
1974 * element value contains/represents an integer or not.
1975 * @param Entry The element value on which to apply the predicate.
1976 * @return The result of the heuristical predicate.
1978 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1979 guint16 element = Entry->GetElement();
1980 guint16 group = Entry->GetGroup();
1981 std::string vr = Entry->GetVR();
1982 guint32 length = Entry->GetLength();
1983 // When we have some semantics on the element we just read, and if we
1984 // a priori know we are dealing with an integer, then we shall be
1985 // able to swap it's element value properly.
1986 if ( element == 0 ) // This is the group length of the group
1992 std::ostringstream s;
1993 int filePosition = ftell(fp);
1994 s << "Erroneous Group Length element length on : (" \
1995 << std::hex << group << " , " << element
1996 << ") -before- position x(" << filePosition << ")"
1997 << "lgt : " << length;
1998 // These 2 lines commented out : a *very dirty* patch
1999 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
2000 // have a glance at offset x(8336) ...
2001 // For *regular* headers, the test is useless..
2002 // lets's print a warning message and go on,
2003 // instead of giving up with an error message
2005 //std::cout << s.str().c_str() << std::endl;
2006 // dbg.Error("gdcmDocument::IsDocEntryAnInteger",
2007 // s.str().c_str());
2010 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2016 * \brief Find the Length till the next sequence delimiter
2017 * \warning NOT end user intended method !
2021 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2022 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2025 long PositionOnEntry = ftell(fp);
2026 bool FoundSequenceDelimiter = false;
2027 guint32 TotalLength = 0;
2030 while ( ! FoundSequenceDelimiter)
2036 TotalLength += 4; // We even have to decount the group and element
2038 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2040 char msg[100]; // for sprintf. Sorry
2041 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2042 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2046 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2047 FoundSequenceDelimiter = true;
2048 else if ( n != 0xe000 )
2050 char msg[100]; // for sprintf. Sorry
2051 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2053 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2057 ItemLength = ReadInt32();
2058 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2059 // the ItemLength with ReadInt32
2060 SkipBytes(ItemLength);
2062 fseek(fp, PositionOnEntry, SEEK_SET);
2067 * \brief Reads a supposed to be 16 Bits integer
2068 * (swaps it depending on processor endianity)
2069 * @return read value
2071 guint16 gdcmDocument::ReadInt16(void) {
2074 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2075 if ( item_read != 1 ) {
2077 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2087 * \brief Reads a supposed to be 32 Bits integer
2088 * (swaps it depending on processor endianity)
2089 * @return read value
2091 guint32 gdcmDocument::ReadInt32(void) {
2094 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2095 if ( item_read != 1 ) {
2097 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2107 * \brief skips bytes inside the source file
2108 * \warning NOT end user intended method !
2111 void gdcmDocument::SkipBytes(guint32 NBytes) {
2112 //FIXME don't dump the returned value
2113 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2117 * \brief Loads all the needed Dictionaries
2118 * \warning NOT end user intended method !
2120 void gdcmDocument::Initialise(void)
2122 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2123 RefShaDict = (gdcmDict*)0;
2127 * \brief Discover what the swap code is (among little endian, big endian,
2128 * bad little endian, bad big endian).
2130 * @return false when we are absolutely sure
2131 * it's neither ACR-NEMA nor DICOM
2132 * true when we hope ours assuptions are OK
2134 bool gdcmDocument::CheckSwap() {
2136 // The only guaranted way of finding the swap code is to find a
2137 // group tag since we know it's length has to be of four bytes i.e.
2138 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2139 // occurs when we can't find such group...
2141 guint32 x=4; // x : for ntohs
2142 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2148 char deb[HEADER_LENGTH_TO_READ];
2150 // First, compare HostByteOrder and NetworkByteOrder in order to
2151 // determine if we shall need to swap bytes (i.e. the Endian type).
2157 // The easiest case is the one of a DICOM header, since it possesses a
2158 // file preamble where it suffice to look for the string "DICM".
2159 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2162 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2163 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2165 // Next, determine the value representation (VR). Let's skip to the
2166 // first element (0002, 0000) and check there if we find "UL"
2167 // - or "OB" if the 1st one is (0002,0001) -,
2168 // in which case we (almost) know it is explicit VR.
2169 // WARNING: if it happens to be implicit VR then what we will read
2170 // is the length of the group. If this ascii representation of this
2171 // length happens to be "UL" then we shall believe it is explicit VR.
2172 // FIXME: in order to fix the above warning, we could read the next
2173 // element value (or a couple of elements values) in order to make
2174 // sure we are not commiting a big mistake.
2175 // We need to skip :
2176 // * the 128 bytes of File Preamble (often padded with zeroes),
2177 // * the 4 bytes of "DICM" string,
2178 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2179 // i.e. a total of 136 bytes.
2183 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2184 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2185 // *Implicit* VR. -and it is !-
2187 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2188 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2189 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2190 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2191 // when Write DCM *adds*
2193 // Use gdcmDocument::dicom_vr to test all the possibilities
2194 // instead of just checking for UL, OB and UI !? group 0000
2196 filetype = gdcmExplicitVR;
2197 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2198 "explicit Value Representation");
2202 filetype = gdcmImplicitVR;
2203 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2204 "not an explicit Value Representation");
2210 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2211 "HostByteOrder != NetworkByteOrder");
2216 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2217 "HostByteOrder = NetworkByteOrder");
2220 // Position the file position indicator at first tag (i.e.
2221 // after the file preamble and the "DICM" string).
2223 fseek (fp, 132L, SEEK_SET);
2227 // Alas, this is not a DicomV3 file and whatever happens there is no file
2228 // preamble. We can reset the file position indicator to where the data
2229 // is (i.e. the beginning of the file).
2230 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2233 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2234 // By clean we mean that the length of the first tag is written down.
2235 // If this is the case and since the length of the first group HAS to be
2236 // four (bytes), then determining the proper swap code is straightforward.
2239 // We assume the array of char we are considering contains the binary
2240 // representation of a 32 bits integer. Hence the following dirty
2242 s32 = *((guint32 *)(entCur));
2263 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2264 // It is time for despaired wild guesses.
2265 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2266 // i.e. the 'group length' element is not present :
2268 // check the supposed to be 'group number'
2269 // 0x0002 or 0x0004 or 0x0008
2270 // to determine ' sw' value .
2271 // Only 0 or 4321 will be possible
2272 // (no oportunity to check for the formerly well known
2273 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2274 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2275 // the file IS NOT ACR-NEMA nor DICOM V3
2276 // Find a trick to tell it the caller...
2278 s16 = *((guint16 *)(deb));
2294 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2295 "ACR/NEMA unfound swap info (Really hopeless !)");
2296 filetype = gdcmUnknown;
2300 // Then the only info we have is the net2host one.
2310 * \brief Restore the unproperly loaded values i.e. the group, the element
2311 * and the dictionary entry depending on them.
2313 void gdcmDocument::SwitchSwapToBigEndian(void)
2315 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2316 "Switching to BigEndian mode.");
2337 * \brief during parsing, Header Elements too long are not loaded in memory
2340 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2344 if ((guint32)NewSize >= (guint32)0xffffffff)
2346 MaxSizeLoadEntry = 0xffffffff;
2349 MaxSizeLoadEntry = NewSize;
2354 * \brief Header Elements too long will not be printed
2355 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2358 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2362 if ((guint32)NewSize >= (guint32)0xffffffff)
2364 MaxSizePrintEntry = 0xffffffff;
2367 MaxSizePrintEntry = NewSize;
2373 * \brief Read the next tag but WITHOUT loading it's value
2374 * (read the 'Group Number', the 'Element Number',
2375 * gets the Dict Entry
2376 * gets the VR, gets the length, gets the offset value)
2377 * @return On succes the newly created DocEntry, NULL on failure.
2379 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2381 gdcmDocEntry *NewEntry;
2386 // We reached the EOF (or an error occured) therefore
2387 // header parsing has to be considered as finished.
2388 return (gdcmDocEntry *)0;
2390 // Pb : how to propagate the element length (used in SkipDocEntry)
2391 // direct call to SkipBytes ?
2393 // if (ignoreShadow == 1 && g%2 ==1)
2394 // if user wants to skip shadow groups
2395 // and current element *is* a shadow element
2396 // we don't create anything
2397 // return (gdcmDocEntry *)1; // to tell caller it's NOT finished
2399 NewEntry = NewDocEntryByNumber(g, n);
2400 FindDocEntryVR(NewEntry);
2401 FindDocEntryLength(NewEntry);
2408 NewEntry->SetOffset(ftell(fp));
2413 * \brief Build a new Element Value from all the low level arguments.
2414 * Check for existence of dictionary entry, and build
2415 * a default one when absent.
2416 * @param Name Name of the underlying DictEntry
2418 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2420 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2422 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2424 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2427 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2428 "failed to allocate gdcmDocEntry");
2429 return (gdcmDocEntry *)0;
2435 * \brief Request a new virtual dict entry to the dict set
2436 * @param group group of the underlying DictEntry
2437 * @param element element of the underlying DictEntry
2438 * @param vr VR of the underlying DictEntry
2439 * @param fourth owner group
2440 * @param name english name
2442 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2447 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2451 * \brief Build a new Element Value from all the low level arguments.
2452 * Check for existence of dictionary entry, and build
2453 * a default one when absent.
2454 * @param Group group of the underlying DictEntry
2455 * @param Elem element of the underlying DictEntry
2457 gdcmDocEntry *gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2459 // Find out if the tag we encountered is in the dictionaries:
2460 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2462 DictEntry = NewVirtualDictEntry(Group, Elem);
2464 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2467 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2468 "failed to allocate gdcmDocEntry");
2474 /// \todo Never used; commented out, waiting for removal.
2476 * \brief Small utility function that creates a new manually crafted
2477 * (as opposed as read from the file) gdcmDocEntry with user
2478 * specified name and adds it to the public tag hash table.
2479 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2480 * @param NewTagName The name to be given to this new tag.
2481 * @param VR The Value Representation to be given to this new tag.
2482 * @return The newly hand crafted Element Value.
2484 //gdcmDocEntry *gdcmDocument::NewManualDocEntryToPubDict(std::string NewTagName,
2487 // gdcmDocEntry *NewEntry = NULL;
2488 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2489 // guint32 FreeElem = 0;
2490 // gdcmDictEntry *DictEntry = NULL;
2492 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2493 // if (FreeElem == UINT32_MAX)
2495 // dbg.Verbose(1, "gdcmHeader::NewManualDocEntryToPubDict",
2496 // "Group 0xffff in Public Dict is full");
2500 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2501 // VR, "GDCM", NewTagName);
2502 // NewEntry = new gdcmDocEntry(DictEntry);
2503 // AddEntry(NewEntry);
2508 * \brief Generate a free TagKey i.e. a TagKey that is not present
2509 * in the TagHt dictionary.
2510 * @param group The generated tag must belong to this group.
2511 * @return The element of tag with given group which is fee.
2513 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2515 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2517 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2518 if (tagHT.count(key) == 0)
2526 * \brief Searches both the public and the shadow dictionary (when they
2527 * exist) for the presence of the DictEntry with given name.
2528 * The public dictionary has precedence on the shadow one.
2529 * @param Name name of the searched DictEntry
2530 * @return Corresponding DictEntry when it exists, NULL otherwise.
2532 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2534 gdcmDictEntry *found = (gdcmDictEntry *)0;
2535 if (!RefPubDict && !RefShaDict)
2537 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2538 "we SHOULD have a default dictionary");
2542 found = RefPubDict->GetDictEntryByName(Name);
2548 found = RefShaDict->GetDictEntryByName(Name);
2556 * \brief Searches both the public and the shadow dictionary (when they
2557 * exist) for the presence of the DictEntry with given
2558 * group and element. The public dictionary has precedence on the
2560 * @param group group of the searched DictEntry
2561 * @param element element of the searched DictEntry
2562 * @return Corresponding DictEntry when it exists, NULL otherwise.
2564 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2566 gdcmDictEntry *found = (gdcmDictEntry *)0;
2567 if (!RefPubDict && !RefShaDict)
2569 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2570 "we SHOULD have a default dictionary");
2574 found = RefPubDict->GetDictEntryByNumber(group, element);
2580 found = RefShaDict->GetDictEntryByNumber(group, element);
2589 //-----------------------------------------------------------------------------