]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
PLEASE : keep on waiting for the final version !
[gdcm.git] / src / gdcmDocument.cxx
1 // gdcmDocument.cxx
2 //-----------------------------------------------------------------------------
3
4 #include "gdcmDocument.h"
5 #include "gdcmValEntry.h"
6 #include "gdcmBinEntry.h"
7 #include "gdcmSeqEntry.h"
8
9 #include "gdcmGlobal.h"
10 #include "gdcmUtil.h"
11 #include "gdcmDebug.h"
12
13 #include <errno.h>
14 #include <vector>
15
16 // For nthos:
17 #ifdef _MSC_VER
18    #include <winsock.h>
19 #else
20    #include <netinet/in.h>
21 #endif
22
23 #  include <iomanip>
24
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"
29
30 typedef struct {
31    guint32 totalSQlength;
32    guint32 alreadyParsedlength;
33 } pileElem;
34
35 //-----------------------------------------------------------------------------
36 // Refer to gdcmDocument::CheckSwap()
37 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
38
39 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
40 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
41
42 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
43
44 //-----------------------------------------------------------------------------
45 // Constructor / Destructor
46
47 /**
48  * \brief   constructor  
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')
60  */
61 gdcmDocument::gdcmDocument(const char *inFilename, 
62                        bool exception_on_error,
63                        bool enable_sequences,
64                        bool ignore_shadow) {
65    enableSequences=enable_sequences;
66    ignoreShadow   =ignore_shadow;
67    
68    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE); 
69    filename = inFilename;
70    Initialise();
71
72    if ( !OpenFile(exception_on_error))
73       return;
74    
75    rewind(fp);
76    //if (!CheckSwap())
77    //   return false; // to go on compiling
78    
79    fseek(fp,0L,SEEK_END);
80    long lgt = ftell(fp);    
81            
82    rewind(fp);
83    CheckSwap();
84    long beg = ftell(fp);
85    lgt -= beg;
86    
87     //std::cout << "beg, lgt : " << beg << "  " << lgt << std::endl;        
88
89    long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
90    CloseFile();
91
92    printLevel = 1;  // 'Medium' print level by default
93 }
94
95 /**
96  * \brief  constructor 
97  * @param   exception_on_error
98  */
99 gdcmDocument::gdcmDocument(bool exception_on_error) {
100         (void)exception_on_error;
101    enableSequences=0;
102
103    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
104    Initialise();
105
106    printLevel = 1;  // 'Medium' print level by default
107 }
108
109 /**
110  * \brief   Canonical destructor.
111  */
112 gdcmDocument::~gdcmDocument (void) {
113    RefPubDict = NULL;
114    RefShaDict = NULL;
115 }
116
117 //-----------------------------------------------------------------------------
118 // Print
119 /**
120  
121
122 /**
123   * \brief   Prints The Dict Entries of THE public Dicom Dictionary
124   * @return
125   */  
126 void gdcmDocument::PrintPubDict(std::ostream & os) {
127    RefPubDict->Print(os);
128 }
129
130 /**
131   * \brief   Prints The Dict Entries of THE shadow Dicom Dictionary
132   * @return
133   */
134 void gdcmDocument::PrintShaDict(std::ostream & os) {
135    RefShaDict->Print(os);
136 }
137
138 //-----------------------------------------------------------------------------
139 // Public
140 /**
141  * \brief   Get the public dictionary used
142  */
143 gdcmDict *gdcmDocument::GetPubDict(void) {
144    return(RefPubDict);
145 }
146
147 /**
148  * \brief   Get the shadow dictionary used
149  */
150 gdcmDict *gdcmDocument::GetShaDict(void) {
151    return(RefShaDict);
152 }
153
154 /**
155  * \brief   Set the shadow dictionary used
156  * \param   dict dictionary to use in shadow
157  */
158 bool gdcmDocument::SetShaDict(gdcmDict *dict){
159    RefShaDict=dict;
160    return(!RefShaDict);
161 }
162
163 /**
164  * \brief   Set the shadow dictionary used
165  * \param   dictName name of the dictionary to use in shadow
166  */
167 bool gdcmDocument::SetShaDict(DictKey dictName){
168    RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
169    return(!RefShaDict);
170 }
171
172 /**
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,
178  *         false otherwise. 
179  */
180 bool gdcmDocument::IsReadable(void) { 
181    if(filetype==gdcmUnknown) {
182       return(false);
183    }
184    if(listEntries.size()<=0) {    
185       return(false);
186    }
187
188    return(true);
189 }
190
191 /**
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.
195  */
196 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void) {
197    gdcmDocEntry *Element = GetDocEntryByNumber(0x0002, 0x0010);
198    if ( !Element )
199       return false;
200    LoadDocEntrySafe(Element);
201
202    std::string Transfer = Element->GetValue();
203    if ( Transfer == UI1_2_840_10008_1_2 )
204       return true;
205    return false;
206 }
207
208 /**
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.
212  */
213 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void) {
214    gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
215    if ( !Element )
216       return false;
217    LoadDocEntrySafe(Element);
218
219    std::string Transfer = Element->GetValue();
220    if ( Transfer == UI1_2_840_10008_1_2_1 )
221       return true;
222    return false;
223 }
224
225 /**
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.
229  */
230 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
231    gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
232    if ( !Element )
233       return false;
234    LoadDocEntrySafe(Element);
235
236    std::string Transfer = Element->GetValue();
237    if ( Transfer == UI1_2_840_10008_1_2_1_99 )
238       return true;
239    return false;
240 }
241
242 /**
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.
246  */
247 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void) {
248    gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
249    if ( !Element )
250       return false;
251    LoadDocEntrySafe(Element);
252
253    std::string Transfer = Element->GetValue();
254    if ( Transfer == UI1_2_840_10008_1_2_2 )  //1.2.2 ??? A verifier !
255       return true;
256    return false;
257 }
258
259 /**
260  * \brief  returns the File Type 
261  *         (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
262  * @return the FileType code
263  */
264 FileType gdcmDocument::GetFileType(void) {
265    return(filetype);
266 }
267
268 /**
269  * \brief   opens the file
270  * @param   exception_on_error
271  * @return  
272  */
273 FILE *gdcmDocument::OpenFile(bool exception_on_error)
274   throw(gdcmFileError) 
275 {
276   fp=fopen(filename.c_str(),"rb");
277   if(exception_on_error) 
278   {
279     if(!fp)
280       throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
281   }
282
283   if ( fp ) 
284   {
285      guint16 zero;
286      fread(&zero,  (size_t)2, (size_t)1, fp);
287
288     //ACR -- or DICOM with no Preamble --
289     if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
290        return(fp);
291
292     //DICOM
293     fseek(fp, 126L, SEEK_CUR);
294     char dicm[4];
295     fread(dicm,  (size_t)4, (size_t)1, fp);
296     if( memcmp(dicm, "DICM", 4) == 0 )
297        return(fp);
298
299     fclose(fp);
300     dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
301   }
302   else {
303     dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
304   }
305   return(NULL);
306 }
307
308 /**
309  * \brief closes the file  
310  * @return  TRUE if the close was successfull 
311  */
312 bool gdcmDocument::CloseFile(void) {
313   int closed = fclose(fp);
314   fp = (FILE *)0;
315   if (! closed)
316      return false;
317   return true;
318 }
319
320 /**
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.
327  */
328 bool gdcmDocument::Write(FILE *fp, FileType type) {
329 /// \todo
330 ///  ==============
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)
334 ///      To be checked
335 /// =============
336
337    /// \todo move the following lines (and a lot of others, to be written)
338    /// to a future function CheckAndCorrectHeader
339    
340    /// \todo
341    /// Question :
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
345    /// no way 
346    /// a moins de se livrer a un tres complique ajout des champs manquants.
347    /// faire un CheckAndCorrectHeader (?)  
348
349    if (type == gdcmImplicitVR) 
350    {
351       std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
352       ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
353       
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
358       
359       SetEntryLengthByNumber(18, 0x0002, 0x0010);
360    } 
361
362    if (type == gdcmExplicitVR) 
363    {
364       std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
365       ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
366       
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
371       
372       SetEntryLengthByNumber(20, 0x0002, 0x0010);
373    }
374
375 /**
376  * \todo rewrite later, if really usefull
377  *
378  *       --> Warning : un-updated odd groups lengths can causes pb 
379  *       -->           (xmedcon breaks)
380  *       --> to be re- written with future org.
381  *
382  * if ( (type == ImplicitVR) || (type == ExplicitVR) )
383  *    UpdateGroupLength(false,type);
384  * if ( type == ACR)
385  *    UpdateGroupLength(true,ACR);
386  */
387
388    WriteEntries(fp,type);
389    return(true);
390 }
391
392 /**
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
400  *          failed).
401  */
402  
403  
404 gdcmDocEntry * gdcmDocument::ReplaceOrCreateByNumber(
405                                          std::string Value, 
406                                          guint16 Group, 
407                                          guint16 Elem ){
408    gdcmDocEntry* a;
409    a = GetDocEntryByNumber( Group, Elem);
410    if (a == NULL) {
411       a =NewDocEntryByNumber(Group, Elem);
412       if (a == NULL) 
413          return NULL;
414       AddEntry(a);
415    }   
416    SetEntryByNumber(Value, Group, Elem);
417    //a->SetValue(Value);
418    return(a);
419 }   
420
421 /**
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
427  * \return  boolean 
428  */
429 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) 
430 {
431    std::string v = Value;
432    SetEntryByNumber(v, Group, Elem);
433    return true;
434
435
436 //-----------------------------------------------------------------------------
437 // Protected
438
439 /**
440  * \brief   Checks if a given Dicom Element exists
441  *          within the H table
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
445  */
446 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
447    std::string key = gdcmDictEntry::TranslateToKey(group, element );
448    return (tagHT.count(key));
449 }
450
451 /**
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.
459  */
460 std::string gdcmDocument::GetEntryByName(std::string tagName) {
461    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
462    if( dictEntry == NULL)
463       return GDCM_UNFOUND;
464
465    return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));  
466 }
467
468 /**
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.
472  *
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.
480  */
481 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
482    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
483    if( dictEntry == NULL)
484       return GDCM_UNFOUND;
485
486    gdcmDocEntry* elem =  GetDocEntryByNumber(dictEntry->GetGroup(),
487                                                    dictEntry->GetElement());
488    return elem->GetVR();
489 }
490
491
492 /**
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.
500  */
501 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
502    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
503    if ( ! tagHT.count(key))
504       return GDCM_UNFOUND;
505    return tagHT.find(key)->second->GetValue();
506 }
507
508 /**
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..
512  *
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.
521  */
522 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
523    gdcmDocEntry* elem =  GetDocEntryByNumber(group, element);
524    if ( !elem )
525       return GDCM_UNFOUND;
526    return elem->GetVR();
527 }
528
529 /**
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
536  */
537 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
538    gdcmDocEntry* elem =  GetDocEntryByNumber(group, element);
539    if ( !elem )
540       return -2;
541    return elem->GetLength();
542 }
543 /**
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
548  */
549 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
550    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
551    if( dictEntry == NULL)
552       return false;    
553
554    return(SetEntryByNumber(content,dictEntry->GetGroup(),
555                                    dictEntry->GetElement()));
556 }
557
558 /**
559  * \brief   Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
560  *          through it's (group, element) and modifies it's content with
561  *          the given value.
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
565  */
566 bool gdcmDocument::SetEntryByNumber(std::string content, 
567                                   guint16 group,
568                                   guint16 element) 
569 {
570    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
571    if ( ! tagHT.count(key))
572       return false;
573    int l = content.length();
574    if(l%2) // Non even length are padded with a space (020H).
575    {  
576       l++;
577       content = content + '\0';
578    }
579       
580    gdcmDocEntry * a;
581    IterHT p;
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)
587     
588    // or, easier :
589    
590    // Oops ! this was for multimap, right ?
591    a = ((tagHT.equal_range(key)).first)->second; 
592        
593    ((gdcmValEntry*)a)->SetValue(content);
594    
595    std::string vr = a->GetVR();
596    
597    guint32 lgr;
598    if( (vr == "US") || (vr == "SS") ) 
599       lgr = 2;
600    else if( (vr == "UL") || (vr == "SL") )
601       lgr = 4;
602    else
603       lgr = l;   
604
605    a->SetLength(lgr);   
606    return true;
607 }  
608
609 /**
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
613  *          the given value.
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.
619  */
620 bool gdcmDocument::SetEntryLengthByNumber(guint32 l, 
621                                         guint16 group, 
622                                         guint16 element) 
623 {
624    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
625    if ( ! tagHT.count(key))
626       return false;
627    if (l%2) l++; // length must be even
628    ( ((tagHT.equal_range(key)).first)->second )->SetLength(l); 
629
630    return true ;
631 }
632
633 /**
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 
639  */
640 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem) 
641 {
642    gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
643    if (!Entry) 
644    {
645       dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
646                       "failed to Locate gdcmDocEntry");
647       return (size_t)0;
648    }
649    return Entry->GetOffset();
650 }
651
652 /**
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
658  */
659 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem) 
660 {
661    gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
662    if (!Entry) 
663    {
664       dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
665                   "failed to Locate gdcmDocEntry");
666       return (NULL);
667    }
668    return ((gdcmBinEntry *)Entry)->GetVoidArea();
669 }
670
671 /**
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
676  */
677 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem) 
678 {
679    gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
680    if ( !Element )
681       return NULL;
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];
686    if(!a) 
687       return NULL;
688
689    SetEntryVoidAreaByNumber(a, Group, Elem);
690    /// \todo check the result 
691    size_t l2 = fread(a, 1, l ,fp);
692    if(l != l2) 
693    {
694       delete[] a;
695       return NULL;
696    }
697
698    return a;  
699 }
700
701 /**
702  * \brief   Sets a 'non string' value to a given Dicom Element
703  * @param   area
704  * @param   group Group number of the searched Dicom Element 
705  * @param   element Element number of the searched Dicom Element 
706  * @return  
707  */
708 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
709                                           guint16 group, 
710                                           guint16 element) 
711 {
712    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
713    if ( ! tagHT.count(key))
714       return false;
715       // This was for multimap ?
716     (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
717       
718    return true;
719 }
720
721 /**
722  * \brief   Update the entries with the shadow dictionary. 
723  *          Only non even entries are analyzed       
724  */
725 void gdcmDocument::UpdateShaEntries(void) {
726    gdcmDictEntry *entry;
727    std::string vr;
728
729    for(ListTag::iterator it=listEntries.begin();
730        it!=listEntries.end();
731        ++it)
732    {
733       // Odd group => from public dictionary
734       if((*it)->GetGroup()%2==0)
735          continue;
736
737       // Peer group => search the corresponding dict entry
738       if(RefShaDict)
739          entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
740       else
741          entry=NULL;
742
743       if((*it)->IsImplicitVR())
744          vr="Implicit";
745       else
746          vr=(*it)->GetVR();
747
748       //(*it)->SetValue(GetDocEntryUnvalue(*it));
749       // to go on compiling
750       if(entry){
751          // Set the new entry and the new value
752          (*it)->SetDictEntry(entry);
753          CheckDocEntryVR(*it,vr);
754
755          //(*it)->SetValue(GetDocEntryValue(*it));
756         // to go on compiling
757          
758       }
759       else
760       {
761          // Remove precedent value transformation
762          (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
763       }
764    }
765 }
766
767 /**
768  * \brief   Searches within the Header Entries for a Dicom Element of
769  *          a given tag.
770  * @param   tagName name of the searched Dicom Element.
771  * @return  Corresponding Dicom Element when it exists, and NULL
772  *          otherwise.
773  */
774  gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
775    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
776    if( dictEntry == NULL)
777       return NULL;
778
779   return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
780 }
781
782 /**
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 
790  * @return  
791  */
792 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element) 
793 {
794    TagKey key = gdcmDictEntry::TranslateToKey(group, element);   
795    if ( ! tagHT.count(key))
796       return NULL;
797    return tagHT.find(key)->second;
798 }
799
800 /**
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) 
805  */
806  
807 IterHT gdcmDocument::GetDocEntrySameNumber(guint16 group, guint16 element){
808    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
809    return (tagHT.equal_range(key));
810 }
811
812 /**
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. 
817  * @return  
818  */
819 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
820    long PositionOnEntry = ftell(fp);
821    LoadDocEntry(entry);
822    fseek(fp, PositionOnEntry, SEEK_SET);
823 }
824
825 /**
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, ...) 
832  */
833  
834  /* Probabely useless, now !
835  
836 void gdcmDocument::UpdateGroupLength(bool SkipSequence, FileType type) {
837    guint16 gr, el;
838    std::string vr;
839    
840    gdcmDocEntry *elem;
841    char trash[10];
842    std::string str_trash;
843    
844    GroupKey key;
845    GroupHT groupHt;  // to hold the length of each group
846    TagKey tk;
847    // remember :
848    // typedef std::map<GroupKey, int> GroupHT;
849    
850    gdcmDocEntry *elemZ;
851   
852    // for each Tag in the DCM Header
853    
854    for (TagDocEntryHT::iterator tag2 = tagHT.begin(); 
855         tag2 != tagHT.end();
856         ++tag2)
857    {
858       elem  = tag2->second;
859       gr = elem->GetGroup();
860       el = elem->GetElement();
861       vr = elem->GetVR(); 
862                  
863       sprintf(trash, "%04x", gr);
864       key = trash;   // generate 'group tag'
865       
866       // if the caller decided not to take SEQUENCEs into account 
867       // e.g : he wants to write an ACR-NEMA File 
868                 
869       if (SkipSequence && vr == "SQ") 
870          continue;
871       
872       // Still unsolved problem :
873       // we cannot find the 'Sequence Delimitation Item'
874       // since it's at the end of the Hash Table
875       // (fffe,e0dd) 
876        
877       // there is SEQUENCE in ACR-NEMA
878       // WARNING : 
879       // --> la descente a l'interieur' des SQ 
880       // devrait etre faite avec une liste chainee, pas avec une HTable...
881             
882       if ( groupHt.count(key) == 0) // we just read the first elem of a given group
883       { 
884          if (el == 0x0000) // the first elem is 0x0000
885          {
886             groupHt[key] = 0;      // initialize group length 
887          } 
888          else 
889          {
890             groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
891          } 
892       } 
893       else // any elem but the first
894       {   
895          if (type == ExplicitVR) 
896          {
897             if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) 
898             {
899                groupHt[key] +=  4; // explicit VR AND OB, OW, SQ : 4 more bytes
900             }
901          }
902          groupHt[key] += 2 + 2 + 4 + elem->GetLength(); 
903       } 
904    }
905
906    unsigned short int gr_bid;
907   
908    for (GroupHT::iterator g = groupHt.begin(); // for each group we found
909         g != groupHt.end();
910         ++g)
911    { 
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
916                      
917       if ( tagHT.count(tk) == 0) // if element 0x0000 not found
918       {
919          gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");       
920          elemZ = new gdcmDocEntry(tagZ);
921          elemZ->SetLength(4);
922          AddEntry(elemZ);   // create it
923       } 
924       else 
925       {
926          elemZ=GetDocEntryByNumber(gr_bid, 0x0000);
927       }     
928       sprintf(trash ,"%d",g->second);
929       str_trash=trash;
930       //elemZ->SetValue(str_trash); // to go on compiling
931    }   
932 }
933
934 */
935
936 /**
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 
943  */
944 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
945                                        FILE *_fp,
946                                        FileType type)
947 {
948    guint16 group  = tag->GetGroup();
949    std::string vr = tag->GetVR();
950    guint16 el     = tag->GetElement();
951    guint32 lgr    = tag->GetReadLength();
952
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 !   
957       return; 
958
959    fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp);  //group
960    fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp);     //element
961       
962    if ( type == gdcmExplicitVR ) {
963
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
968          // 0xffffffff
969
970          int ff=0xffffffff;
971          fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
972          return;
973       }
974
975       guint16 z=0;
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);
981       } else {
982          fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);                     
983          if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
984          {
985             fwrite ( &z,  (size_t)2 ,(size_t)1 ,_fp);
986             fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
987          } else {
988             fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
989          }
990       }
991    } 
992    else // IMPLICIT VR 
993    { 
994       fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
995    }
996 }
997       
998 /**
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
1004  */
1005  
1006  // TODO : to be re -written recursively !
1007  
1008 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1009 {
1010    (void)type;
1011    guint16 group  = tag->GetGroup();
1012    std::string vr = tag->GetVR();
1013    guint32 lgr    = tag->GetReadLength();
1014
1015    if (vr == "SQ")
1016       // SeQuences have no value:
1017       return;
1018    if (group == 0xfffe)
1019       // Delimiters have no associated value:
1020       return;
1021       
1022    void *voidArea;
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
1028       return;            
1029    }
1030       
1031    if (vr == "US" || vr == "SS") 
1032    {
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++) 
1040       {
1041          guint16 val_uint16 = atoi(tokens[i].c_str());
1042          void *ptr = &val_uint16;
1043          fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1044       }
1045       tokens.clear();
1046       return;
1047    }
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") 
1052    {
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++) 
1057       {
1058          guint32 val_uint32 = atoi(tokens[i].c_str());
1059          void *ptr = &val_uint32;
1060          fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1061       }
1062       tokens.clear();
1063       return;
1064    }           
1065    fwrite (tag->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1066 }
1067
1068 /**
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
1075  */
1076
1077 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1078 {
1079    guint32 length = tag->GetLength();
1080
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:
1083    if(length%2==1)
1084    { 
1085 //      tag->SetValue(tag->GetValue()+"\0");
1086 // to go on compiling
1087       tag->SetLength(tag->GetReadLength()+1);
1088    }
1089
1090    WriteEntryTagVRLength(tag, _fp, type);
1091    WriteEntryValue(tag, _fp, type);
1092    return true;
1093 }
1094
1095 /**
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
1108  */
1109
1110 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1111 {   
1112    /// \todo (?) check write failures (after *each* fwrite)
1113      
1114    for (ListTag::iterator tag2=listEntries.begin();
1115                           tag2 != listEntries.end();
1116                           ++tag2)
1117    {
1118       if ( type == gdcmACR ){ 
1119          if ((*tag2)->GetGroup() < 0x0008)
1120             // Ignore pure DICOM V3 groups
1121             continue;
1122          if ((*tag2)->GetElement() %2)
1123             // Ignore the "shadow" groups
1124             continue;
1125          if ((*tag2)->GetVR() == "SQ" ) // ignore Sequences
1126             continue;
1127          if ((*tag2)->GetSQDepthLevel() != 0) // Not only ignore the SQ element
1128             continue;       
1129       } 
1130       if (! WriteEntry(*tag2,_fp,type) )
1131          return false;
1132    }
1133    return true;
1134 }   
1135
1136 /**
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!)
1147  * \sa WriteEntries
1148  * @param   _fp already open file pointer
1149  * @param   type type of the File to be written 
1150  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
1151  */
1152 void gdcmDocument::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1153
1154    // restent a tester les echecs en ecriture (apres chaque fwrite)
1155
1156    for (TagDocEntryHT::iterator tag2=tagHT.begin();
1157         tag2 != tagHT.end();
1158         ++tag2){
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          
1164       }
1165       if ( ! WriteEntry(tag2->second,_fp,type))
1166          break;
1167    }
1168 }
1169
1170 /**
1171  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1172  *          processor order.
1173  * @return  The properly swaped 32 bits integer.
1174  */
1175 guint32 gdcmDocument::SwapLong(guint32 a) {
1176    switch (sw) {
1177       case    0 :
1178          break;
1179       case 4321 :
1180          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
1181              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1182          break;
1183    
1184       case 3412 :
1185          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1186          break;
1187    
1188       case 2143 :
1189          a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1190          break;
1191       default :
1192          std::cout << "swapCode= " << sw << std::endl;
1193          dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1194          a=0;
1195    }
1196    return(a);
1197 }
1198
1199 /**
1200  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
1201  *          processor order.
1202  * @return  The properly unswaped 32 bits integer.
1203  */
1204 guint32 gdcmDocument::UnswapLong(guint32 a) {
1205    return (SwapLong(a));
1206 }
1207
1208 /**
1209  * \brief   Swaps the bytes so they agree with the processor order
1210  * @return  The properly swaped 16 bits integer.
1211  */
1212 guint16 gdcmDocument::SwapShort(guint16 a) {
1213    if ( (sw==4321)  || (sw==2143) )
1214       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1215    return (a);
1216 }
1217
1218 /**
1219  * \brief   Unswaps the bytes so they agree with the processor order
1220  * @return  The properly unswaped 16 bits integer.
1221  */
1222 guint16 gdcmDocument::UnswapShort(guint16 a) {
1223    return (SwapShort(a));
1224 }
1225
1226 //-----------------------------------------------------------------------------
1227 // Private
1228
1229
1230
1231 /**
1232  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1233  * @return  false if file is not ACR-NEMA / PAPYRUS / DICOM 
1234  */ 
1235
1236 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1237
1238    gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1239    gdcmValEntry *vl;
1240    gdcmBinEntry *bn;   
1241    gdcmSeqEntry *sq;
1242    string vr;
1243    long l;         
1244    while (true) { 
1245       NewDocEntry = ReadNextDocEntry( );
1246       if (!NewDocEntry)
1247          break;
1248          
1249       std::cout << hex << NewDocEntry->GetGroup() 
1250                << " "
1251                << NewDocEntry->GetElement() 
1252                << " "
1253                << NewDocEntry->GetVR()
1254                << " "
1255                << NewDocEntry->GetReadLength()
1256                << " "
1257                << NewDocEntry->GetOffset()             
1258                << std::endl;
1259                
1260       vr = NewDocEntry->GetVR();         
1261       if (vr!="SQ") {
1262                
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"
1268                                                                   ) {
1269       // --- ValEntry                            
1270             vl= new gdcmValEntry(NewDocEntry->GetDictEntry());
1271             vl->Copy(NewDocEntry);
1272             set->AddEntry(vl);
1273             LoadDocEntry(vl);
1274             std::cout << "value [" << vl->GetValue() << "]" << std::endl;
1275             if (!delim_mode && vl->isItemDelimitor())
1276                break;
1277          } else { // BinEntry
1278          
1279         // Hope the following VR *do* correspond to a BinEntry 
1280                 
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)
1288                  
1289             bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1290             bn->Copy(NewDocEntry);
1291             LoadDocEntry(bn);
1292             std::cout << "value [" << "Bin Entry, in voidArea" << "]" << std::endl;                      
1293          }      
1294
1295           SkipToNextDocEntry(NewDocEntry); // to be sure to be at the beginning 
1296           l = NewDocEntry->GetFullLength(); 
1297             
1298       } else {   // VR = "SQ"
1299       
1300          //SkipDocEntry(NewDocEntry);
1301       
1302          std::cout << "gdcmDocument::ParseDES : SQ found " << std::endl;
1303          l=NewDocEntry->GetReadLength(); 
1304          if (l == 0xffffffff)
1305            delim_mode = true;
1306          else
1307            delim_mode = false;
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 ?
1313          set->AddEntry(sq);
1314          if ( !delim_mode && ftell(fp)-offset >= l_max)
1315             break;
1316       } 
1317    }
1318    cout << endl; 
1319    delete NewDocEntry;   
1320    return l; // ?? 
1321 }
1322
1323
1324
1325 /**
1326  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1327  * @return  parsed length for this level
1328  */ 
1329
1330
1331 long gdcmDocument::ParseSQ(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1332
1333          std::cout << "Entree ds gdcmDocument::ParseSQ" << std::endl;
1334
1335    gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1336    gdcmSQItem *itemSQ;
1337    bool dlm_mod;
1338    int lgr, l, lgth;
1339    cout << "=============== on entre ds une Sequence" <<endl;
1340    
1341    while (true) {
1342       std::cout << "gdcmDocument::ParseSQ on itere" << std::endl;
1343
1344       if(delim_mode) {   
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);
1349              break;
1350           }          
1351       }      
1352       if (!delim_mode && (ftell(fp)-offset) >= l_max){       
1353              break;
1354       }         
1355       itemSQ = new gdcmSQItem();
1356       itemSQ->AddEntry(NewDocEntry); // no value, no voidArea. Think of it while printing !
1357       l= NewDocEntry->GetLength();
1358       if (l ==0xffffffff)
1359          dlm_mod = true;
1360       else
1361          dlm_mod=false;
1362       
1363       lgr=ParseDES(itemSQ, offset, l, dlm_mod);
1364       ((gdcmSeqEntry *)set)->AddEntry(itemSQ);   
1365    }
1366    //Update(lgth); 
1367    lgth = ftell(fp) - offset;
1368    cout << "=============== lgr Sequence :" << lgth <<endl;
1369    return(lgth);
1370 }
1371
1372
1373 /**
1374  * \brief   Parses the header of the file and load element values.
1375  * @return  false if file is not ACR-NEMA / PAPYRUS / DICOM 
1376  */
1377
1378 /* =======================================================================
1379 // Replaced by ParseSQ
1380   
1381 bool gdcmDocument::LoadHeaderEntries(bool exception_on_error) throw(gdcmFormatError) {
1382    (void)exception_on_error;
1383    rewind(fp);
1384    if (!CheckSwap())
1385       return false;
1386       
1387    gdcmDocEntry *newDocEntry = (gdcmDocEntry *)0;   
1388    while ( (newDocEntry = ReadNextDocEntry()) ) {
1389      SkipDocEntry(newDocEntry);
1390      if ( (ignoreShadow==0) || (newDocEntry->GetGroup()%2) == 0) { 
1391         AddEntry(newDocEntry); 
1392      }     
1393    }   
1394    rewind(fp);
1395    // Be carefull : merging this two loops may cause troubles ...
1396    for (ListTag::iterator i = GetListEntry().begin();                           
1397         i != GetListEntry().end();                                                
1398         ++i)                                                                      
1399    {                                                                            
1400       LoadDocEntry(*i);                                                      
1401    }                                                                            
1402    rewind(fp);                                                                     
1403    
1404    // Load 'non string' values
1405  
1406    
1407    // --------------------------------------------------------------
1408    // Special Patch to allow gdcm to read ACR-LibIDO formated images
1409    //
1410    // if recognition code tells us we deal with a LibIDO image
1411    // we switch lineNumber and columnNumber
1412    //
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"
1418    {
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);
1424    }
1425    // ----------------- End of Special Patch ----------------   
1426    return true;
1427 }
1428 ======================================================================= */
1429
1430
1431 /**
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
1435  */
1436 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)  {
1437    size_t item_read;
1438    guint16 group  = Entry->GetGroup();
1439    std::string  vr= Entry->GetVR();
1440    guint32 length = Entry->GetLength();
1441
1442    fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1443
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)
1453       return;
1454    }
1455
1456    // When the length is zero things are easy:
1457    if ( length == 0 ) {
1458       ((gdcmValEntry *)Entry)->SetValue("");
1459       return;
1460    }
1461
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());
1472       return;
1473    }
1474     
1475    // Any compacter code suggested (?)
1476    if ( IsDocEntryAnInteger(Entry) ) {   
1477       guint32 NewInt;
1478       std::ostringstream s;
1479       int nbInt;
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") {
1485          nbInt = length / 2;
1486          NewInt = ReadInt16();
1487          s << NewInt;
1488          if (nbInt > 1){
1489             for (int i=1; i < nbInt; i++) {
1490                s << '\\';
1491                NewInt = ReadInt16();
1492                s << NewInt;
1493             }
1494          }
1495       }
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") {
1501          nbInt = length / 4;
1502          NewInt = ReadInt32();
1503          s << NewInt;
1504          if (nbInt > 1) {
1505             for (int i=1; i < nbInt; i++) {
1506                s << '\\';
1507                NewInt = ReadInt32();
1508                s << NewInt;
1509             }
1510          }
1511       }
1512 #ifdef GDCM_NO_ANSI_STRING_STREAM
1513       s << std::ends; // to avoid oddities on Solaris
1514 #endif //GDCM_NO_ANSI_STRING_STREAM
1515
1516       ((gdcmValEntry *)Entry)->SetValue(s.str());
1517       return;
1518    }
1519    
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");
1526       return;
1527    }
1528
1529    if( (vr == "UI") ) // Because of correspondance with the VR dic
1530       ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1531    else
1532       ((gdcmValEntry *)Entry)->SetValue(NewValue);
1533 }
1534
1535
1536 /**
1537  * \brief  Find the value Length of the passed Header Entry
1538  * @param  Entry Header Entry whose length of the value shall be loaded. 
1539  */
1540  void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1541    guint16 element = Entry->GetElement();
1542    //guint16 group   = Entry->GetGroup(); //FIXME
1543    std::string  vr = Entry->GetVR();
1544    guint16 length16;
1545        
1546    
1547    if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) ) 
1548    {
1549       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) 
1550       {
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();
1556
1557          if ( (vr == "OB") && (length32 == 0xffffffff) ) 
1558          {
1559             Entry->SetLength(FindDocEntryLengthOB());
1560             return;
1561          }
1562          FixDocEntryFoundLength(Entry, length32); 
1563          return;
1564       }
1565
1566       // Length is encoded on 2 bytes.
1567       length16 = ReadInt16();
1568       
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) ) 
1597       {
1598          if ( ! IsExplicitVRBigEndianTransferSyntax() ) 
1599          {
1600             dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1601             errno = 1;
1602             return;
1603          }
1604          length16 = 4;
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,
1611                                                        CorrectElem);
1612          if (!NewTag) 
1613          {
1614             // This correct tag is not in the dictionary. Create a new one.
1615             NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1616          }
1617          // FIXME this can create a memory leaks on the old entry that be
1618          // left unreferenced.
1619          Entry->SetDictEntry(NewTag);
1620       }
1621        
1622       // Heuristic: well some files are really ill-formed.
1623       if ( length16 == 0xffff) 
1624       {
1625          length16 = 0;
1626          //dbg.Verbose(0, "gdcmDocument::FindLength",
1627          //            "Erroneous element length fixed.");
1628          // Actually, length= 0xffff means that we deal with
1629          // Unknown Sequence Length 
1630       }
1631       FixDocEntryFoundLength(Entry, (guint32)length16);
1632       return;
1633    }
1634    else
1635    {
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.
1642       
1643       FixDocEntryFoundLength(Entry, ReadInt32());
1644       return;
1645    }
1646 }
1647
1648 /**
1649  * \brief     Find the Value Representation of the current Dicom Element.
1650  * @param     Entry
1651  */
1652 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry) 
1653 {
1654    if (filetype != gdcmExplicitVR)
1655       return;
1656
1657    char VR[3];
1658
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
1666    // the case.
1667    
1668    (void)fread (&VR, (size_t)2,(size_t)1, fp);
1669    VR[2]=0;
1670    if(!CheckDocEntryVR(Entry,VR))
1671    {
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.
1677       // avoid  .
1678       if ( Entry->IsVRUnknown() )
1679          Entry->SetVR("Implicit");
1680       Entry->SetImplicitVR();
1681    }
1682 }
1683
1684 /**
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
1692 */
1693 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1694 {
1695    char msg[100]; // for sprintf
1696    bool RealExplicit = true;
1697
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.
1705
1706    if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1707       RealExplicit = false;
1708
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;
1714
1715    if ( !RealExplicit ) 
1716    {
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);     
1727       }
1728       return(false);
1729    }
1730
1731    if ( Entry->IsVRUnknown() ) 
1732    {
1733       // When not a dictionary entry, we can safely overwrite the VR.
1734       if (Entry->GetElement() == 0x0000) { // Group length is UL !
1735          Entry->SetVR("UL");
1736       } else {
1737          Entry->SetVR(vr);
1738       }
1739    }
1740    else if ( Entry->GetVR() != vr ) 
1741    {
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);
1751    }
1752    return(true); 
1753 }
1754
1755 /**
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 !
1759  * @param   Entry 
1760  * @return  Transformed entry value
1761  */
1762 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1763 {
1764    if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1765    {
1766       std::string val=Entry->GetValue();
1767       std::string vr=Entry->GetVR();
1768       guint32 length = Entry->GetLength();
1769       std::ostringstream s;
1770       int nbInt;
1771
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) 
1778    
1779       if (vr == "US" || vr == "SS")
1780       {
1781          guint16 NewInt16;
1782
1783          nbInt = length / 2;
1784          for (int i=0; i < nbInt; i++) 
1785          {
1786             if(i!=0)
1787                s << '\\';
1788             NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1789             NewInt16 = SwapShort(NewInt16);
1790             s << NewInt16;
1791          }
1792       }
1793
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")
1801       {
1802          guint32 NewInt32;
1803
1804          nbInt = length / 4;
1805          for (int i=0; i < nbInt; i++) 
1806          {
1807             if(i!=0)
1808                s << '\\';
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);
1812             s << NewInt32;
1813          }
1814       }
1815 #ifdef GDCM_NO_ANSI_STRING_STREAM
1816       s << std::ends; // to avoid oddities on Solaris
1817 #endif //GDCM_NO_ANSI_STRING_STREAM
1818       return(s.str());
1819    }
1820
1821    return(Entry->GetValue());
1822 }
1823
1824 /**
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
1827  *          the value
1828  * \warning NOT end user intended method !
1829  * @param   Entry 
1830  * @return  Reverse transformed entry value
1831  */
1832 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1833 {
1834    if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1835    {
1836       std::string vr=Entry->GetVR();
1837       std::ostringstream s;
1838       std::vector<std::string> tokens;
1839
1840       if (vr == "US" || vr == "SS") 
1841       {
1842          guint16 NewInt16;
1843
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++) 
1847          {
1848             NewInt16 = atoi(tokens[i].c_str());
1849             s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1850          }
1851          tokens.clear();
1852       }
1853       if (vr == "UL" || vr == "SL") 
1854       {
1855          guint32 NewInt32;
1856
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++) 
1860          {
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);
1864          }
1865          tokens.clear();
1866       }
1867
1868 #ifdef GDCM_NO_ANSI_STRING_STREAM
1869       s << std::ends; // to avoid oddities on Solaris
1870 #endif //GDCM_NO_ANSI_STRING_STREAM
1871       return(s.str());
1872    }
1873
1874    return(Entry->GetValue());
1875 }
1876
1877 /**
1878  * \brief   Skip a given Header Entry 
1879  * \warning NOT end user intended method !
1880  * @param   entry 
1881  */
1882 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry) 
1883 {
1884    SkipBytes(entry->GetLength());
1885 }
1886
1887 /**
1888  * \brief   Skips to the begining of the next Header Entry 
1889  * \warning NOT end user intended method !
1890  * @param   entry 
1891  */
1892 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry) 
1893 {
1894    (void)fseek(fp, (long)(entry->GetOffset()),     SEEK_SET);
1895    (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1896 }
1897
1898 /**
1899  * \brief   Loads the value for a a given VLEntry 
1900  * \warning NOT end user intended method !
1901  * @param   entry 
1902  */
1903 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry) 
1904 {
1905     //SkipBytes(entry->GetLength());
1906     LoadDocEntry(entry);
1907 }
1908 /**
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.
1912  */
1913 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry, guint32 FoundLength) 
1914 {
1915    Entry->SetReadLength(FoundLength); // will be updated only if a bug is found        
1916    if ( FoundLength == 0xffffffff) {
1917       FoundLength = 0;
1918    }
1919    
1920    guint16 gr =Entry->GetGroup();
1921    guint16 el =Entry->GetElement(); 
1922      
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());
1928    }
1929       
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
1938          FoundLength =10;
1939          Entry->SetReadLength(10); // a bug is to be fixed
1940       }
1941    }
1942
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) ) ){
1947       FoundLength =4;
1948       Entry->SetReadLength(4); // a bug is to be fixed 
1949    } 
1950    // end of fix
1951  
1952    // to try to 'go inside' SeQuences (with length), and not to skip them        
1953    else if ( Entry->GetVR() == "SQ") 
1954    { 
1955       if (enableSequences)    // only if the user does want to !
1956          FoundLength =0;      // ReadLength is unchanged 
1957    } 
1958     
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)
1962    {    
1963                                          // *normally, fffe|0000 doesn't exist ! 
1964      if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1965                                          // causes extra troubles :-(                                                                   
1966         FoundLength =0;
1967    } 
1968            
1969    Entry->SetUsableLength(FoundLength);
1970 }
1971
1972 /**
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.
1977  */
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
1987    {  
1988       if (length == 4)
1989          return true;
1990       else 
1991       {
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
2004
2005          //std::cout << s.str().c_str() << std::endl;
2006          // dbg.Error("gdcmDocument::IsDocEntryAnInteger",
2007          //           s.str().c_str());     
2008       }
2009    }
2010    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2011       return true;
2012    
2013    return false;
2014 }
2015 /**
2016  * \brief  Find the Length till the next sequence delimiter
2017  * \warning NOT end user intended method !
2018  * @return 
2019  */
2020
2021  guint32 gdcmDocument::FindDocEntryLengthOB(void)  {
2022    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2023    guint16 g;
2024    guint16 n; 
2025    long PositionOnEntry = ftell(fp);
2026    bool FoundSequenceDelimiter = false;
2027    guint32 TotalLength = 0;
2028    guint32 ItemLength;
2029
2030    while ( ! FoundSequenceDelimiter) 
2031    {
2032       g = ReadInt16();
2033       n = ReadInt16();   
2034       if (errno == 1)
2035          return 0;
2036       TotalLength += 4;  // We even have to decount the group and element 
2037      
2038       if ( g != 0xfffe && g!=0xb00c ) //for bogus header  
2039       {
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); 
2043          errno = 1;
2044          return 0;
2045       }
2046       if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header 
2047          FoundSequenceDelimiter = true;
2048       else if ( n != 0xe000 )
2049       {
2050          char msg[100];  // for sprintf. Sorry
2051          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2052                       n, g,n);
2053          dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2054          errno = 1;
2055          return 0;
2056       }
2057       ItemLength = ReadInt32();
2058       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
2059                                       // the ItemLength with ReadInt32                                     
2060       SkipBytes(ItemLength);
2061    }
2062    fseek(fp, PositionOnEntry, SEEK_SET);
2063    return TotalLength;
2064 }
2065
2066 /**
2067  * \brief Reads a supposed to be 16 Bits integer
2068  *       (swaps it depending on processor endianity) 
2069  * @return read value
2070  */
2071 guint16 gdcmDocument::ReadInt16(void) {
2072    guint16 g;
2073    size_t item_read;
2074    item_read = fread (&g, (size_t)2,(size_t)1, fp);
2075    if ( item_read != 1 ) {
2076       if(ferror(fp)) 
2077          dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2078       errno = 1;
2079       return 0;
2080    }
2081    errno = 0;
2082    g = SwapShort(g);   
2083    return g;
2084 }
2085
2086 /**
2087  * \brief  Reads a supposed to be 32 Bits integer
2088  *         (swaps it depending on processor endianity)  
2089  * @return read value
2090  */
2091 guint32 gdcmDocument::ReadInt32(void) {
2092    guint32 g;
2093    size_t item_read;
2094    item_read = fread (&g, (size_t)4,(size_t)1, fp);
2095    if ( item_read != 1 ) { 
2096      if(ferror(fp)) 
2097          dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");   
2098       errno = 1;
2099       return 0;
2100    }
2101    errno = 0;   
2102    g = SwapLong(g);
2103    return g;
2104 }
2105
2106 /**
2107  * \brief skips bytes inside the source file 
2108  * \warning NOT end user intended method !
2109  * @return 
2110  */
2111 void gdcmDocument::SkipBytes(guint32 NBytes) {
2112    //FIXME don't dump the returned value
2113    (void)fseek(fp, (long)NBytes, SEEK_CUR);
2114 }
2115
2116 /**
2117  * \brief Loads all the needed Dictionaries
2118  * \warning NOT end user intended method !   
2119  */
2120 void gdcmDocument::Initialise(void) 
2121 {
2122    RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2123    RefShaDict = (gdcmDict*)0;
2124 }
2125
2126 /**
2127  * \brief   Discover what the swap code is (among little endian, big endian,
2128  *          bad little endian, bad big endian).
2129  *          sw is set
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
2133  */
2134 bool gdcmDocument::CheckSwap() {
2135
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...
2140    
2141    guint32  x=4;  // x : for ntohs
2142    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2143    guint32  s32;
2144    guint16  s16;
2145        
2146    int lgrLue;
2147    char *entCur;
2148    char deb[HEADER_LENGTH_TO_READ];
2149     
2150    // First, compare HostByteOrder and NetworkByteOrder in order to
2151    // determine if we shall need to swap bytes (i.e. the Endian type).
2152    if (x==ntohs(x))
2153       net2host = true;
2154    else
2155       net2host = false; 
2156          
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);
2160    
2161    entCur = deb + 128;
2162    if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2163       dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2164       
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.
2180       entCur = deb + 136;
2181      
2182       // FIXME : FIXME:
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 !- 
2186       
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*
2192       // FIXME
2193       // Use gdcmDocument::dicom_vr to test all the possibilities
2194       // instead of just checking for UL, OB and UI !? group 0000 
2195       {
2196          filetype = gdcmExplicitVR;
2197          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2198                      "explicit Value Representation");
2199       } 
2200       else 
2201       {
2202          filetype = gdcmImplicitVR;
2203          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2204                      "not an explicit Value Representation");
2205       }
2206       
2207       if (net2host) 
2208       {
2209          sw = 4321;
2210          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2211                         "HostByteOrder != NetworkByteOrder");
2212       } 
2213       else 
2214       {
2215          sw = 0;
2216          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2217                         "HostByteOrder = NetworkByteOrder");
2218       }
2219       
2220       // Position the file position indicator at first tag (i.e.
2221       // after the file preamble and the "DICM" string).
2222       rewind(fp);
2223       fseek (fp, 132L, SEEK_SET);
2224       return true;
2225    } // End of DicomV3
2226
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");
2231    rewind(fp);
2232
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.
2237
2238    entCur = deb + 4;
2239    // We assume the array of char we are considering contains the binary
2240    // representation of a 32 bits integer. Hence the following dirty
2241    // trick :
2242    s32 = *((guint32 *)(entCur));
2243       
2244    switch (s32) {
2245       case 0x00040000 :
2246          sw = 3412;
2247          filetype = gdcmACR;
2248          return true;
2249       case 0x04000000 :
2250          sw = 4321;
2251          filetype = gdcmACR;
2252          return true;
2253       case 0x00000400 :
2254          sw = 2143;
2255          filetype = gdcmACR;
2256          return true;
2257       case 0x00000004 :
2258          sw = 0;
2259          filetype = gdcmACR;
2260          return true;
2261       default :
2262
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 :     
2267       
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...
2277       
2278       s16 = *((guint16 *)(deb));
2279       
2280       switch (s16) {
2281       case 0x0002 :
2282       case 0x0004 :
2283       case 0x0008 :      
2284          sw = 0;
2285          filetype = gdcmACR;
2286          return true;
2287       case 0x0200 :
2288       case 0x0400 :
2289       case 0x0800 : 
2290          sw = 4321;
2291          filetype = gdcmACR;
2292          return true;
2293       default :
2294          dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2295                      "ACR/NEMA unfound swap info (Really hopeless !)"); 
2296          filetype = gdcmUnknown;     
2297          return false;
2298       }
2299       
2300       // Then the only info we have is the net2host one.
2301       //if (! net2host )
2302          //   sw = 0;
2303          //else
2304          //  sw = 4321;
2305          //return;
2306    }
2307 }
2308
2309 /**
2310  * \brief Restore the unproperly loaded values i.e. the group, the element
2311  *        and the dictionary entry depending on them. 
2312  */
2313 void gdcmDocument::SwitchSwapToBigEndian(void) 
2314 {
2315    dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2316                   "Switching to BigEndian mode.");
2317    if ( sw == 0    ) 
2318    {
2319       sw = 4321;
2320       return;
2321    }
2322    if ( sw == 4321 ) 
2323    {
2324       sw = 0;
2325       return;
2326    }
2327    if ( sw == 3412 ) 
2328    {
2329       sw = 2143;
2330       return;
2331    }
2332    if ( sw == 2143 )
2333       sw = 3412;
2334 }
2335
2336 /**
2337  * \brief  during parsing, Header Elements too long are not loaded in memory 
2338  * @param NewSize
2339  */
2340 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize) 
2341 {
2342    if (NewSize < 0)
2343       return;
2344    if ((guint32)NewSize >= (guint32)0xffffffff) 
2345    {
2346       MaxSizeLoadEntry = 0xffffffff;
2347       return;
2348    }
2349    MaxSizeLoadEntry = NewSize;
2350 }
2351
2352
2353 /**
2354  * \brief Header Elements too long will not be printed
2355  * \todo  See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE 
2356  * @param NewSize
2357  */
2358 void gdcmDocument::SetMaxSizePrintEntry(long NewSize) 
2359 {
2360    if (NewSize < 0)
2361       return;
2362    if ((guint32)NewSize >= (guint32)0xffffffff) 
2363    {
2364       MaxSizePrintEntry = 0xffffffff;
2365       return;
2366    }
2367    MaxSizePrintEntry = NewSize;
2368 }
2369
2370
2371
2372 /**
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.      
2378  */
2379 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2380    guint16 g,n;
2381    gdcmDocEntry *NewEntry;
2382    g = ReadInt16();
2383    n = ReadInt16();
2384       
2385    if (errno == 1)
2386       // We reached the EOF (or an error occured) therefore 
2387       // header parsing has to be considered as finished.
2388       return (gdcmDocEntry *)0;
2389
2390 // Pb : how to propagate the element length (used in SkipDocEntry)
2391 //       direct call to SkipBytes ?
2392    
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
2398   
2399    NewEntry = NewDocEntryByNumber(g, n);
2400    FindDocEntryVR(NewEntry);
2401    FindDocEntryLength(NewEntry);
2402
2403    if (errno == 1) {
2404       // Call it quits
2405       delete NewEntry;
2406       return NULL;
2407    }
2408    NewEntry->SetOffset(ftell(fp));  
2409    return NewEntry;
2410 }
2411
2412 /**
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
2417  */
2418 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name) 
2419 {
2420    gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2421    if (!NewTag)
2422       NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2423
2424    gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2425    if (!NewEntry) 
2426    {
2427       dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2428                   "failed to allocate gdcmDocEntry");
2429       return (gdcmDocEntry *)0;
2430    }
2431    return NewEntry;
2432 }  
2433
2434 /**
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
2441  */
2442 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2443                                                std::string vr,
2444                                                std::string fourth,
2445                                                std::string name)
2446 {
2447    return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2448 }
2449
2450 /**
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
2456  */
2457 gdcmDocEntry *gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem) 
2458 {
2459    // Find out if the tag we encountered is in the dictionaries:
2460    gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2461    if (!DictEntry)
2462       DictEntry = NewVirtualDictEntry(Group, Elem);
2463
2464    gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2465    if (!NewEntry) 
2466    {
2467       dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2468                   "failed to allocate gdcmDocEntry");
2469       return NULL;
2470    }
2471    return NewEntry;
2472 }
2473
2474 /// \todo Never used; commented out, waiting for removal.
2475 /**
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.
2483  */
2484 //gdcmDocEntry *gdcmDocument::NewManualDocEntryToPubDict(std::string NewTagName, 
2485 //                                                           std::string VR) 
2486 //{
2487 //   gdcmDocEntry *NewEntry = NULL;
2488 //   guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
2489 //   guint32 FreeElem = 0;
2490 //   gdcmDictEntry *DictEntry = NULL;
2491 //
2492 //   FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2493 //   if (FreeElem == UINT32_MAX) 
2494 //   {
2495 //      dbg.Verbose(1, "gdcmHeader::NewManualDocEntryToPubDict",
2496 //                     "Group 0xffff in Public Dict is full");
2497 //      return NULL;
2498 //   }
2499 //
2500 //   DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2501 //                                VR, "GDCM", NewTagName);
2502 //   NewEntry = new gdcmDocEntry(DictEntry);
2503 //   AddEntry(NewEntry);
2504 //   return NewEntry;
2505 //}
2506
2507 /**
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.
2512  */
2513 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group) 
2514 {
2515    for (guint32 elem = 0; elem < UINT32_MAX; elem++) 
2516    {
2517       TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2518       if (tagHT.count(key) == 0)
2519          return elem;
2520    }
2521    return UINT32_MAX;
2522 }
2523
2524
2525 /**
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.
2531  */
2532 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name) 
2533 {
2534    gdcmDictEntry *found = (gdcmDictEntry *)0;
2535    if (!RefPubDict && !RefShaDict) 
2536    {
2537       dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2538                      "we SHOULD have a default dictionary");
2539    }
2540    if (RefPubDict) 
2541    {
2542       found = RefPubDict->GetDictEntryByName(Name);
2543       if (found)
2544          return found;
2545    }
2546    if (RefShaDict) 
2547    {
2548       found = RefShaDict->GetDictEntryByName(Name);
2549       if (found)
2550          return found;
2551    }
2552    return found;
2553 }
2554
2555 /**
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
2559  *          shadow one.
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.
2563  */
2564 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element) 
2565 {
2566    gdcmDictEntry *found = (gdcmDictEntry *)0;
2567    if (!RefPubDict && !RefShaDict) 
2568    {
2569       dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2570                      "we SHOULD have a default dictionary");
2571    }
2572    if (RefPubDict) 
2573    {
2574       found = RefPubDict->GetDictEntryByNumber(group, element);
2575       if (found)
2576          return found;
2577    }
2578    if (RefShaDict) 
2579    {
2580       found = RefShaDict->GetDictEntryByNumber(group, element);
2581       if (found)
2582          return found;
2583    }
2584    return found;
2585 }
2586
2587
2588
2589 //-----------------------------------------------------------------------------