]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
Sooooon, it will be OK
[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  /* TO DO : uncomment when everything else is OK  
93   
94    // --------------------------------------------------------------
95    // Special Patch to allow gdcm to read ACR-LibIDO formated images
96    //
97    // if recognition code tells us we deal with a LibIDO image
98    // we switch lineNumber and columnNumber
99    //
100    std::string RecCode;
101    RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
102    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
103        RecCode == "CANRME_AILIBOD1_1." )  // for brain-damaged softwares
104                                           // with "little-endian strings"
105    {
106          filetype = ACR_LIBIDO; 
107          std::string rows    = GetEntryByNumber(0x0028, 0x0010);
108          std::string columns = GetEntryByNumber(0x0028, 0x0011);
109          SetEntryByNumber(columns, 0x0028, 0x0010);
110          SetEntryByNumber(rows   , 0x0028, 0x0011);
111    }
112    // ----------------- End of Special Patch ---------------- 
113    */ 
114
115
116    printLevel = 1;  // 'Medium' print level by default
117 }
118
119 /**
120  * \brief  constructor 
121  * @param   exception_on_error
122  */
123 gdcmDocument::gdcmDocument(bool exception_on_error) {
124         (void)exception_on_error;
125    enableSequences=0;
126
127    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
128    Initialise();
129
130    printLevel = 1;  // 'Medium' print level by default
131 }
132
133 /**
134  * \brief   Canonical destructor.
135  */
136 gdcmDocument::~gdcmDocument (void) {
137    RefPubDict = NULL;
138    RefShaDict = NULL;
139 }
140
141 //-----------------------------------------------------------------------------
142 // Print
143 /**
144  
145
146 /**
147   * \brief   Prints The Dict Entries of THE public Dicom Dictionary
148   * @return
149   */  
150 void gdcmDocument::PrintPubDict(std::ostream & os) {
151    RefPubDict->Print(os);
152 }
153
154 /**
155   * \brief   Prints The Dict Entries of THE shadow Dicom Dictionary
156   * @return
157   */
158 void gdcmDocument::PrintShaDict(std::ostream & os) {
159    RefShaDict->Print(os);
160 }
161
162 //-----------------------------------------------------------------------------
163 // Public
164 /**
165  * \brief   Get the public dictionary used
166  */
167 gdcmDict *gdcmDocument::GetPubDict(void) {
168    return(RefPubDict);
169 }
170
171 /**
172  * \brief   Get the shadow dictionary used
173  */
174 gdcmDict *gdcmDocument::GetShaDict(void) {
175    return(RefShaDict);
176 }
177
178 /**
179  * \brief   Set the shadow dictionary used
180  * \param   dict dictionary to use in shadow
181  */
182 bool gdcmDocument::SetShaDict(gdcmDict *dict){
183    RefShaDict=dict;
184    return(!RefShaDict);
185 }
186
187 /**
188  * \brief   Set the shadow dictionary used
189  * \param   dictName name of the dictionary to use in shadow
190  */
191 bool gdcmDocument::SetShaDict(DictKey dictName){
192    RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
193    return(!RefShaDict);
194 }
195
196 /**
197  * \brief  This predicate, based on hopefully reasonable heuristics,
198  *         decides whether or not the current gdcmDocument was properly parsed
199  *         and contains the mandatory information for being considered as
200  *         a well formed and usable Dicom/Acr File.
201  * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
202  *         false otherwise. 
203  */
204 bool gdcmDocument::IsReadable(void) { 
205    if(filetype==gdcmUnknown) {
206       return(false);
207    }
208    if(listEntries.size()<=0) {    
209       return(false);
210    }
211
212    return(true);
213 }
214
215 /**
216  * \brief   Determines if the Transfer Syntax was already encountered
217  *          and if it corresponds to a ImplicitVRLittleEndian one.
218  * @return  True when ImplicitVRLittleEndian found. False in all other cases.
219  */
220 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void) {
221    gdcmDocEntry *Element = GetDocEntryByNumber(0x0002, 0x0010);
222    if ( !Element )
223       return false;
224    LoadDocEntrySafe(Element);
225
226    std::string Transfer = Element->GetValue();
227    if ( Transfer == UI1_2_840_10008_1_2 )
228       return true;
229    return false;
230 }
231
232 /**
233  * \brief   Determines if the Transfer Syntax was already encountered
234  *          and if it corresponds to a ExplicitVRLittleEndian one.
235  * @return  True when ExplicitVRLittleEndian found. False in all other cases.
236  */
237 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void) {
238    gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
239    if ( !Element )
240       return false;
241    LoadDocEntrySafe(Element);
242
243    std::string Transfer = Element->GetValue();
244    if ( Transfer == UI1_2_840_10008_1_2_1 )
245       return true;
246    return false;
247 }
248
249 /**
250  * \brief   Determines if the Transfer Syntax was already encountered
251  *          and if it corresponds to a DeflatedExplicitVRLittleEndian one.
252  * @return  True when DeflatedExplicitVRLittleEndian found. False in all other cases.
253  */
254 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
255    gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
256    if ( !Element )
257       return false;
258    LoadDocEntrySafe(Element);
259
260    std::string Transfer = Element->GetValue();
261    if ( Transfer == UI1_2_840_10008_1_2_1_99 )
262       return true;
263    return false;
264 }
265
266 /**
267  * \brief   Determines if the Transfer Syntax was already encountered
268  *          and if it corresponds to a Explicit VR Big Endian one.
269  * @return  True when big endian found. False in all other cases.
270  */
271 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void) {
272    gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
273    if ( !Element )
274       return false;
275    LoadDocEntrySafe(Element);
276
277    std::string Transfer = Element->GetValue();
278    if ( Transfer == UI1_2_840_10008_1_2_2 )  //1.2.2 ??? A verifier !
279       return true;
280    return false;
281 }
282
283 /**
284  * \brief  returns the File Type 
285  *         (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
286  * @return the FileType code
287  */
288 FileType gdcmDocument::GetFileType(void) {
289    return(filetype);
290 }
291
292 /**
293  * \brief   opens the file
294  * @param   exception_on_error
295  * @return  
296  */
297 FILE *gdcmDocument::OpenFile(bool exception_on_error)
298   throw(gdcmFileError) 
299 {
300   fp=fopen(filename.c_str(),"rb");
301   if(exception_on_error) 
302   {
303     if(!fp)
304       throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
305   }
306
307   if ( fp ) 
308   {
309      guint16 zero;
310      fread(&zero,  (size_t)2, (size_t)1, fp);
311
312     //ACR -- or DICOM with no Preamble --
313     if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
314        return(fp);
315
316     //DICOM
317     fseek(fp, 126L, SEEK_CUR);
318     char dicm[4];
319     fread(dicm,  (size_t)4, (size_t)1, fp);
320     if( memcmp(dicm, "DICM", 4) == 0 )
321        return(fp);
322
323     fclose(fp);
324     dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
325   }
326   else {
327     dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
328   }
329   return(NULL);
330 }
331
332 /**
333  * \brief closes the file  
334  * @return  TRUE if the close was successfull 
335  */
336 bool gdcmDocument::CloseFile(void) {
337   int closed = fclose(fp);
338   fp = (FILE *)0;
339   if (! closed)
340      return false;
341   return true;
342 }
343
344 /**
345  * \brief Writes in a file all the Header Entries (Dicom Elements) 
346  *        of the Chained List
347  * @param fp file pointer on an already open file
348  * @param type Type of the File to be written 
349  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
350  * \return Always true.
351  */
352 bool gdcmDocument::Write(FILE *fp, FileType type) {
353 /// \todo
354 ///  ==============
355 ///      The stuff will have to be rewritten using the SeQuence based 
356 ///       tree-like stucture instead  of the chained list .
357 ///      (so we shall remove the GroupHT from the gdcmDocument)
358 ///      To be checked
359 /// =============
360
361    /// \todo move the following lines (and a lot of others, to be written)
362    /// to a future function CheckAndCorrectHeader
363    
364    /// \todo
365    /// Question :
366    /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
367    /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
368    /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
369    /// no way 
370    /// a moins de se livrer a un tres complique ajout des champs manquants.
371    /// faire un CheckAndCorrectHeader (?)  
372
373    if (type == gdcmImplicitVR) 
374    {
375       std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
376       ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
377       
378       /// \todo Refer to standards on page 21, chapter 6.2
379       ///       "Value representation": values with a VR of UI shall be
380       ///       padded with a single trailing null
381       ///       Dans le cas suivant on doit pader manuellement avec un 0
382       
383       SetEntryLengthByNumber(18, 0x0002, 0x0010);
384    } 
385
386    if (type == gdcmExplicitVR) 
387    {
388       std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
389       ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
390       
391       /// \todo Refer to standards on page 21, chapter 6.2
392       ///       "Value representation": values with a VR of UI shall be
393       ///       padded with a single trailing null
394       ///       Dans le cas suivant on doit pader manuellement avec un 0
395       
396       SetEntryLengthByNumber(20, 0x0002, 0x0010);
397    }
398
399 /**
400  * \todo rewrite later, if really usefull
401  *
402  *       --> Warning : un-updated odd groups lengths can causes pb 
403  *       -->           (xmedcon breaks)
404  *       --> to be re- written with future org.
405  *
406  * if ( (type == ImplicitVR) || (type == ExplicitVR) )
407  *    UpdateGroupLength(false,type);
408  * if ( type == ACR)
409  *    UpdateGroupLength(true,ACR);
410  */
411
412    WriteEntries(fp,type);
413    return(true);
414 }
415
416 /**
417  * \brief   Modifies the value of a given Header Entry (Dicom Element)
418  *          when it exists. Create it with the given value when unexistant.
419  * \warning Adds the Header Entry to the HTable, NOT to the chained List
420  * @param   Value Value to be set
421  * @param   Group Group of the Entry 
422  * @param   Elem  Element of the Entry
423  * \return  pointer to the modified/created Header Entry (NULL when creation
424  *          failed).
425  */
426  
427  
428 gdcmDocEntry * gdcmDocument::ReplaceOrCreateByNumber(
429                                          std::string Value, 
430                                          guint16 Group, 
431                                          guint16 Elem ){
432    gdcmDocEntry* a;
433    a = GetDocEntryByNumber( Group, Elem);
434    if (a == NULL) {
435       a =NewDocEntryByNumber(Group, Elem);
436       if (a == NULL) 
437          return NULL;
438       AddEntry(a);
439    }   
440    SetEntryByNumber(Value, Group, Elem);
441    //a->SetValue(Value);
442    return(a);
443 }   
444
445 /**
446  * \brief Set a new value if the invoked element exists
447  *        Seems to be useless !!!
448  * @param Value new element value
449  * @param Group   group of the Entry 
450  * @param Elem element of the Entry
451  * \return  boolean 
452  */
453 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) 
454 {
455    std::string v = Value;
456    SetEntryByNumber(v, Group, Elem);
457    return true;
458
459
460 //-----------------------------------------------------------------------------
461 // Protected
462
463 /**
464  * \brief   Checks if a given Dicom Element exists
465  *          within the H table
466  * @param   group Group   number of the searched Dicom Element 
467  * @param   element  Element number of the searched Dicom Element 
468  * @return  number of occurences
469  */
470 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
471    std::string key = gdcmDictEntry::TranslateToKey(group, element );
472    return (tagHT.count(key));
473 }
474
475 /**
476  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
477  *          the public and private dictionaries 
478  *          for the element value of a given tag.
479  * \warning Don't use any longer : use GetPubEntryByName
480  * @param   tagName name of the searched element.
481  * @return  Corresponding element value when it exists,
482  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
483  */
484 std::string gdcmDocument::GetEntryByName(std::string tagName) {
485    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
486    if( dictEntry == NULL)
487       return GDCM_UNFOUND;
488
489    return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));  
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  *
497  *          Obtaining the VR (Value Representation) might be needed by caller
498  *          to convert the string typed content to caller's native type 
499  *          (think of C++ vs Python). The VR is actually of a higher level
500  *          of semantics than just the native C++ type.
501  * @param   tagName name of the searched element.
502  * @return  Corresponding element value representation when it exists,
503  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
504  */
505 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
506    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
507    if( dictEntry == NULL)
508       return GDCM_UNFOUND;
509
510    gdcmDocEntry* elem =  GetDocEntryByNumber(dictEntry->GetGroup(),
511                                                    dictEntry->GetElement());
512    return elem->GetVR();
513 }
514
515
516 /**
517  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
518  *          the public and private dictionaries 
519  *          for the element value representation of a given tag.
520  * @param   group Group of the searched tag.
521  * @param   element Element of the searched tag.
522  * @return  Corresponding element value representation when it exists,
523  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
524  */
525 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
526    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
527    if ( ! tagHT.count(key))
528       return GDCM_UNFOUND;
529    return tagHT.find(key)->second->GetValue();
530 }
531
532 /**
533  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
534  *          the public and private dictionaries 
535  *          for the element value representation of a given tag..
536  *
537  *          Obtaining the VR (Value Representation) might be needed by caller
538  *          to convert the string typed content to caller's native type 
539  *          (think of C++ vs Python). The VR is actually of a higher level
540  *          of semantics than just the native C++ type.
541  * @param   group Group of the searched tag.
542  * @param   element Element of the searched tag.
543  * @return  Corresponding element value representation when it exists,
544  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
545  */
546 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
547    gdcmDocEntry* elem =  GetDocEntryByNumber(group, element);
548    if ( !elem )
549       return GDCM_UNFOUND;
550    return elem->GetVR();
551 }
552
553 /**
554  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
555  *          the public and private dictionaries 
556  *          for the value length of a given tag..
557  * @param   group Group of the searched tag.
558  * @param   element Element of the searched tag.
559  * @return  Corresponding element length; -2 if not found
560  */
561 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
562    gdcmDocEntry* elem =  GetDocEntryByNumber(group, element);
563    if ( !elem )
564       return -2;
565    return elem->GetLength();
566 }
567 /**
568  * \brief   Sets the value (string) of the Header Entry (Dicom Element)
569  * @param   content string value of the Dicom Element
570  * @param   tagName name of the searched Dicom Element.
571  * @return  true when found
572  */
573 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
574    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
575    if( dictEntry == NULL)
576       return false;    
577
578    return(SetEntryByNumber(content,dictEntry->GetGroup(),
579                                    dictEntry->GetElement()));
580 }
581
582 /**
583  * \brief   Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
584  *          through it's (group, element) and modifies it's content with
585  *          the given value.
586  * @param   content new value to substitute with
587  * @param   group   group of the Dicom Element to modify
588  * @param   element element of the Dicom Element to modify
589  */
590 bool gdcmDocument::SetEntryByNumber(std::string content, 
591                                   guint16 group,
592                                   guint16 element) 
593 {
594    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
595    if ( ! tagHT.count(key))
596       return false;
597    int l = content.length();
598    if(l%2) // Non even length are padded with a space (020H).
599    {  
600       l++;
601       content = content + '\0';
602    }
603       
604    gdcmDocEntry * a;
605    IterHT p;
606    TagDocEntryHT::iterator p2;
607    // DO NOT remove the following lines : they explain the stuff   
608    //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
609    //p2=p.first;                // iterator on the first synonym 
610    //a=p2->second;              // H Table target column (2-nd col)
611     
612    // or, easier :
613    
614    // Oops ! this was for multimap, right ?
615    a = ((tagHT.equal_range(key)).first)->second; 
616        
617    ((gdcmValEntry*)a)->SetValue(content);
618    
619    std::string vr = a->GetVR();
620    
621    guint32 lgr;
622    if( (vr == "US") || (vr == "SS") ) 
623       lgr = 2;
624    else if( (vr == "UL") || (vr == "SL") )
625       lgr = 4;
626    else
627       lgr = l;   
628
629    a->SetLength(lgr);   
630    return true;
631 }  
632
633 /**
634  * \brief   Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
635  *          in the PubDocEntrySet of this instance
636  *          through it's (group, element) and modifies it's length with
637  *          the given value.
638  * \warning Use with extreme caution.
639  * @param l new length to substitute with
640  * @param group   group of the Entry to modify
641  * @param element element of the Entry to modify
642  * @return  true on success, false otherwise.
643  */
644 bool gdcmDocument::SetEntryLengthByNumber(guint32 l, 
645                                         guint16 group, 
646                                         guint16 element) 
647 {
648    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
649    if ( ! tagHT.count(key))
650       return false;
651    if (l%2) l++; // length must be even
652    ( ((tagHT.equal_range(key)).first)->second )->SetLength(l); 
653
654    return true ;
655 }
656
657 /**
658  * \brief   Gets (from Header) the offset  of a 'non string' element value 
659  *          (LoadElementValues has already be executed)
660  * @param Group   group of the Entry 
661  * @param Elem  element of the Entry
662  * @return File Offset of the Element Value 
663  */
664 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem) 
665 {
666    gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
667    if (!Entry) 
668    {
669       dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
670                       "failed to Locate gdcmDocEntry");
671       return (size_t)0;
672    }
673    return Entry->GetOffset();
674 }
675
676 /**
677  * \brief   Gets (from Header) a 'non string' element value 
678  *          (LoadElementValues has already be executed)  
679  * @param Group   group of the Entry 
680  * @param Elem element of the Entry
681  * @return Pointer to the 'non string' area
682  */
683 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem) 
684 {
685    gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
686    if (!Entry) 
687    {
688       dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
689                   "failed to Locate gdcmDocEntry");
690       return (NULL);
691    }
692    return ((gdcmBinEntry *)Entry)->GetVoidArea();
693 }
694
695 /**
696  * \brief         Loads (from disk) the element content 
697  *                when a string is not suitable
698  * @param Group   group of the Entry 
699  * @param Elem element of the Entry
700  */
701 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem) 
702 {
703    gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
704    if ( !Element )
705       return NULL;
706    size_t o =(size_t)Element->GetOffset();
707    fseek(fp, o, SEEK_SET);
708    size_t l=Element->GetLength();
709    char* a = new char[l];
710    if(!a) 
711       return NULL;
712
713    SetEntryVoidAreaByNumber(a, Group, Elem);
714    /// \todo check the result 
715    size_t l2 = fread(a, 1, l ,fp);
716    if(l != l2) 
717    {
718       delete[] a;
719       return NULL;
720    }
721
722    return a;  
723 }
724
725 /**
726  * \brief   Sets a 'non string' value to a given Dicom Element
727  * @param   area
728  * @param   group Group number of the searched Dicom Element 
729  * @param   element Element number of the searched Dicom Element 
730  * @return  
731  */
732 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
733                                           guint16 group, 
734                                           guint16 element) 
735 {
736    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
737    if ( ! tagHT.count(key))
738       return false;
739       // This was for multimap ?
740     (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
741       
742    return true;
743 }
744
745 /**
746  * \brief   Update the entries with the shadow dictionary. 
747  *          Only non even entries are analyzed       
748  */
749 void gdcmDocument::UpdateShaEntries(void) {
750    gdcmDictEntry *entry;
751    std::string vr;
752
753    for(ListTag::iterator it=listEntries.begin();
754        it!=listEntries.end();
755        ++it)
756    {
757       // Odd group => from public dictionary
758       if((*it)->GetGroup()%2==0)
759          continue;
760
761       // Peer group => search the corresponding dict entry
762       if(RefShaDict)
763          entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
764       else
765          entry=NULL;
766
767       if((*it)->IsImplicitVR())
768          vr="Implicit";
769       else
770          vr=(*it)->GetVR();
771
772       //(*it)->SetValue(GetDocEntryUnvalue(*it));
773       // to go on compiling
774       if(entry){
775          // Set the new entry and the new value
776          (*it)->SetDictEntry(entry);
777          CheckDocEntryVR(*it,vr);
778
779          //(*it)->SetValue(GetDocEntryValue(*it));
780         // to go on compiling
781          
782       }
783       else
784       {
785          // Remove precedent value transformation
786          (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
787       }
788    }
789 }
790
791 /**
792  * \brief   Searches within the Header Entries for a Dicom Element of
793  *          a given tag.
794  * @param   tagName name of the searched Dicom Element.
795  * @return  Corresponding Dicom Element when it exists, and NULL
796  *          otherwise.
797  */
798  gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
799    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
800    if( dictEntry == NULL)
801       return NULL;
802
803   return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
804 }
805
806 /**
807  * \brief  retrieves a Dicom Element (the first one) using (group, element)
808  * \warning (group, element) IS NOT an identifier inside the Dicom Header
809  *           if you think it's NOT UNIQUE, check the count number
810  *           and use iterators to retrieve ALL the Dicoms Elements within
811  *           a given couple (group, element)
812  * @param   group Group number of the searched Dicom Element 
813  * @param   element Element number of the searched Dicom Element 
814  * @return  
815  */
816 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element) 
817 {
818    TagKey key = gdcmDictEntry::TranslateToKey(group, element);   
819    if ( ! tagHT.count(key))
820       return NULL;
821    return tagHT.find(key)->second;
822 }
823
824 /**
825  * \brief   retrieves the Dicom Elements (all of them) using (group, element) 
826  * @param   group Group number of the searched Dicom Element.
827  * @param   element Element number of the searched Dicom Element.
828  * @return  a range (i.e.pair<,>) containing all elements whose key is group|element) 
829  */
830  
831 IterHT gdcmDocument::GetDocEntrySameNumber(guint16 group, guint16 element){
832    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
833    return (tagHT.equal_range(key));
834 }
835
836 /**
837  * \brief         Loads the element while preserving the current
838  *                underlying file position indicator as opposed to
839  *                to LoadDocEntry that modifies it.
840  * @param entry   Header Entry whose value shall be loaded. 
841  * @return  
842  */
843 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
844    long PositionOnEntry = ftell(fp);
845    LoadDocEntry(entry);
846    fseek(fp, PositionOnEntry, SEEK_SET);
847 }
848
849 /**
850  * \brief   Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
851  * \warning : to be re-written using the chained list instead of the H table.
852  * \warning : DO NOT use (doesn't work any longer because of the multimap)
853  * \todo : to be re-written using the chained list instead of the H table
854  * @param   SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
855  * @param   type Type of the File (ExplicitVR,ImplicitVR, ACR, ...) 
856  */
857  
858  /* Probabely useless, now !
859  
860 void gdcmDocument::UpdateGroupLength(bool SkipSequence, FileType type) {
861    guint16 gr, el;
862    std::string vr;
863    
864    gdcmDocEntry *elem;
865    char trash[10];
866    std::string str_trash;
867    
868    GroupKey key;
869    GroupHT groupHt;  // to hold the length of each group
870    TagKey tk;
871    // remember :
872    // typedef std::map<GroupKey, int> GroupHT;
873    
874    gdcmDocEntry *elemZ;
875   
876    // for each Tag in the DCM Header
877    
878    for (TagDocEntryHT::iterator tag2 = tagHT.begin(); 
879         tag2 != tagHT.end();
880         ++tag2)
881    {
882       elem  = tag2->second;
883       gr = elem->GetGroup();
884       el = elem->GetElement();
885       vr = elem->GetVR(); 
886                  
887       sprintf(trash, "%04x", gr);
888       key = trash;   // generate 'group tag'
889       
890       // if the caller decided not to take SEQUENCEs into account 
891       // e.g : he wants to write an ACR-NEMA File 
892                 
893       if (SkipSequence && vr == "SQ") 
894          continue;
895       
896       // Still unsolved problem :
897       // we cannot find the 'Sequence Delimitation Item'
898       // since it's at the end of the Hash Table
899       // (fffe,e0dd) 
900        
901       // there is SEQUENCE in ACR-NEMA
902       // WARNING : 
903       // --> la descente a l'interieur' des SQ 
904       // devrait etre faite avec une liste chainee, pas avec une HTable...
905             
906       if ( groupHt.count(key) == 0) // we just read the first elem of a given group
907       { 
908          if (el == 0x0000) // the first elem is 0x0000
909          {
910             groupHt[key] = 0;      // initialize group length 
911          } 
912          else 
913          {
914             groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
915          } 
916       } 
917       else // any elem but the first
918       {   
919          if (type == ExplicitVR) 
920          {
921             if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) 
922             {
923                groupHt[key] +=  4; // explicit VR AND OB, OW, SQ : 4 more bytes
924             }
925          }
926          groupHt[key] += 2 + 2 + 4 + elem->GetLength(); 
927       } 
928    }
929
930    unsigned short int gr_bid;
931   
932    for (GroupHT::iterator g = groupHt.begin(); // for each group we found
933         g != groupHt.end();
934         ++g)
935    { 
936       // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
937       //        warning: unsigned int format, different type arg
938       sscanf(g->first.c_str(),"%x",&gr_bid); //FIXME
939       tk = g->first + "|0000";   // generate the element full tag
940                      
941       if ( tagHT.count(tk) == 0) // if element 0x0000 not found
942       {
943          gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");       
944          elemZ = new gdcmDocEntry(tagZ);
945          elemZ->SetLength(4);
946          AddEntry(elemZ);   // create it
947       } 
948       else 
949       {
950          elemZ=GetDocEntryByNumber(gr_bid, 0x0000);
951       }     
952       sprintf(trash ,"%d",g->second);
953       str_trash=trash;
954       //elemZ->SetValue(str_trash); // to go on compiling
955    }   
956 }
957
958 */
959
960 /**
961  * \brief Writes in a file (according to the requested format)
962  *        the group, the element, the value representation and the length
963  *        of a single gdcmDocEntry passed as argument.
964  * @param tag  pointer on the gdcmDocEntry to be written
965  * @param _fp  already open file pointer
966  * @param type type of the File to be written 
967  */
968 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
969                                        FILE *_fp,
970                                        FileType type)
971 {
972    guint16 group  = tag->GetGroup();
973    std::string vr = tag->GetVR();
974    guint16 el     = tag->GetElement();
975    guint32 lgr    = tag->GetReadLength();
976
977    if ( (group == 0xfffe) && (el == 0x0000) ) 
978      // Fix in order to make some MR PHILIPS images e-film readable
979      // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
980      // we just *always* ignore spurious fffe|0000 tag !   
981       return; 
982
983    fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp);  //group
984    fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp);     //element
985       
986    if ( type == gdcmExplicitVR ) {
987
988       // Special case of delimiters:
989       if (group == 0xfffe) {
990          // Delimiters have NO Value Representation and have NO length.
991          // Hence we skip writing the VR and length and we pad by writing
992          // 0xffffffff
993
994          int ff=0xffffffff;
995          fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
996          return;
997       }
998
999       guint16 z=0;
1000       guint16 shortLgr = lgr;
1001       if (vr == "unkn") {     // Unknown was 'written'
1002          // deal with Little Endian            
1003          fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1004          fwrite ( &z,  (size_t)2 ,(size_t)1 ,_fp);
1005       } else {
1006          fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);                     
1007          if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1008          {
1009             fwrite ( &z,  (size_t)2 ,(size_t)1 ,_fp);
1010             fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1011          } else {
1012             fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1013          }
1014       }
1015    } 
1016    else // IMPLICIT VR 
1017    { 
1018       fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1019    }
1020 }
1021       
1022 /**
1023  * \brief Writes in a file (according to the requested format)
1024  *        the value of a single gdcmDocEntry passed as argument.
1025  * @param tag  Pointer on the gdcmDocEntry to be written
1026  * @param _fp  Already open file pointer
1027  * @param type type of the File to be written
1028  */
1029  
1030  // TODO : to be re -written recursively !
1031  
1032 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1033 {
1034    (void)type;
1035    guint16 group  = tag->GetGroup();
1036    std::string vr = tag->GetVR();
1037    guint32 lgr    = tag->GetReadLength();
1038
1039    if (vr == "SQ")
1040       // SeQuences have no value:
1041       return;
1042    if (group == 0xfffe)
1043       // Delimiters have no associated value:
1044       return;
1045       
1046    void *voidArea;
1047   // voidArea = tag->GetVoidArea();
1048   // to go on compiling
1049    if (voidArea != NULL) 
1050    { // there is a 'non string' LUT, overlay, etc
1051       fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1052       return;            
1053    }
1054       
1055    if (vr == "US" || vr == "SS") 
1056    {
1057       // some 'Short integer' fields may be mulivaluated
1058       // each single value is separated from the next one by '\'
1059       // we split the string and write each value as a short int
1060       std::vector<std::string> tokens;
1061       tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1062       Tokenize (tag->GetValue(), tokens, "\\");
1063       for (unsigned int i=0; i<tokens.size();i++) 
1064       {
1065          guint16 val_uint16 = atoi(tokens[i].c_str());
1066          void *ptr = &val_uint16;
1067          fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1068       }
1069       tokens.clear();
1070       return;
1071    }
1072       // some 'Integer' fields may be mulivaluated
1073       // each single value is separated from the next one by '\'
1074       // we split the string and write each value as an int
1075    if (vr == "UL" || vr == "SL") 
1076    {
1077       std::vector<std::string> tokens;
1078       tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1079       Tokenize (tag->GetValue(), tokens, "\\");
1080       for (unsigned int i=0; i<tokens.size();i++) 
1081       {
1082          guint32 val_uint32 = atoi(tokens[i].c_str());
1083          void *ptr = &val_uint32;
1084          fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1085       }
1086       tokens.clear();
1087       return;
1088    }           
1089    fwrite (tag->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1090 }
1091
1092 /**
1093  * \brief Writes in a file (according to the requested format)
1094  *        a single gdcmDocEntry passed as argument.
1095  * \sa    WriteEntryValue, WriteEntryTagVRLength.
1096  * @param tag  Pointer on the gdcmDocEntry to be written
1097  * @param _fp  Already open file pointer
1098  * @param type type of the File to be written
1099  */
1100
1101 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1102 {
1103    guint32 length = tag->GetLength();
1104
1105    // The value of a tag MUST (see the DICOM norm) be an odd number of
1106    // bytes. When this is not the case, pad with an additional byte:
1107    if(length%2==1)
1108    { 
1109 //      tag->SetValue(tag->GetValue()+"\0");
1110 // to go on compiling
1111       tag->SetLength(tag->GetReadLength()+1);
1112    }
1113
1114    WriteEntryTagVRLength(tag, _fp, type);
1115    WriteEntryValue(tag, _fp, type);
1116    return true;
1117 }
1118
1119 /**
1120  * \brief   writes on disc according to the requested format
1121  *          (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1122  *          using the Chained List
1123  * \warning does NOT add the missing elements in the header :
1124  *           it's up to the user doing it !
1125  *           (function CheckHeaderCoherence to be written)
1126  * \warning DON'T try, right now, to write a DICOM image
1127  *           from an ACR Header (meta elements will be missing!)
1128  * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1129  * @param   type type of the File to be written 
1130  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
1131  * @param   _fp already open file pointer
1132  */
1133
1134 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1135 {   
1136    /// \todo (?) check write failures (after *each* fwrite)
1137      
1138    for (ListTag::iterator tag2=listEntries.begin();
1139                           tag2 != listEntries.end();
1140                           ++tag2)
1141    {
1142       if ( type == gdcmACR ){ 
1143          if ((*tag2)->GetGroup() < 0x0008)
1144             // Ignore pure DICOM V3 groups
1145             continue;
1146          if ((*tag2)->GetElement() %2)
1147             // Ignore the "shadow" groups
1148             continue;
1149          if ((*tag2)->GetVR() == "SQ" ) // ignore Sequences
1150             continue;
1151          if ((*tag2)->GetSQDepthLevel() != 0) // Not only ignore the SQ element
1152             continue;       
1153       } 
1154       if (! WriteEntry(*tag2,_fp,type) )
1155          return false;
1156    }
1157    return true;
1158 }   
1159
1160 /**
1161  * \brief   writes on disc according to the requested format
1162  *          (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1163  *          using only the last synonym of each mutimap H Table post.
1164  * \warning Uses the H Table, instead of the Chained List
1165  *          in order to be compliant with the old way to proceed
1166  *         (added elements taken in to account)
1167  *         Only THERALYS, during a transitory phase is supposed
1168  *         to use this method !!!
1169  * \warning DON'T try, right now, to write a DICOM image
1170  *           from an ACR Header (meta elements will be missing!)
1171  * \sa WriteEntries
1172  * @param   _fp already open file pointer
1173  * @param   type type of the File to be written 
1174  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
1175  */
1176 void gdcmDocument::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1177
1178    // restent a tester les echecs en ecriture (apres chaque fwrite)
1179
1180    for (TagDocEntryHT::iterator tag2=tagHT.begin();
1181         tag2 != tagHT.end();
1182         ++tag2){
1183       if ( type == gdcmACR ){ 
1184          if ((*tag2->second).GetGroup() < 0x0008)    continue; // ignore pure DICOM V3 groups
1185          if ((*tag2->second).GetElement() %2)        continue; // ignore shadow groups
1186          if ((*tag2->second).GetVR() == "SQ" )       continue; // ignore Sequences
1187          if ((*tag2->second).GetSQDepthLevel() != 0) continue; // Not only ignore the SQ element          
1188       }
1189       if ( ! WriteEntry(tag2->second,_fp,type))
1190          break;
1191    }
1192 }
1193
1194 /**
1195  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1196  *          processor order.
1197  * @return  The properly swaped 32 bits integer.
1198  */
1199 guint32 gdcmDocument::SwapLong(guint32 a) {
1200    switch (sw) {
1201       case    0 :
1202          break;
1203       case 4321 :
1204          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
1205              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1206          break;
1207    
1208       case 3412 :
1209          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1210          break;
1211    
1212       case 2143 :
1213          a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1214          break;
1215       default :
1216          std::cout << "swapCode= " << sw << std::endl;
1217          dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1218          a=0;
1219    }
1220    return(a);
1221 }
1222
1223 /**
1224  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
1225  *          processor order.
1226  * @return  The properly unswaped 32 bits integer.
1227  */
1228 guint32 gdcmDocument::UnswapLong(guint32 a) {
1229    return (SwapLong(a));
1230 }
1231
1232 /**
1233  * \brief   Swaps the bytes so they agree with the processor order
1234  * @return  The properly swaped 16 bits integer.
1235  */
1236 guint16 gdcmDocument::SwapShort(guint16 a) {
1237    if ( (sw==4321)  || (sw==2143) )
1238       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1239    return (a);
1240 }
1241
1242 /**
1243  * \brief   Unswaps the bytes so they agree with the processor order
1244  * @return  The properly unswaped 16 bits integer.
1245  */
1246 guint16 gdcmDocument::UnswapShort(guint16 a) {
1247    return (SwapShort(a));
1248 }
1249
1250 //-----------------------------------------------------------------------------
1251 // Private
1252
1253
1254
1255 /**
1256  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1257  * @return  false if file is not ACR-NEMA / PAPYRUS / DICOM 
1258  */ 
1259
1260 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1261
1262    gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1263    gdcmValEntry *vl;
1264    gdcmBinEntry *bn;   
1265    gdcmSeqEntry *sq;
1266    string vr;
1267    long l;
1268    cout << hex << "offset " << offset 
1269         << " l_max "<< l_max 
1270         << " ftell a l'entree " << ftell(fp)
1271         << endl;         
1272    while (true) { 
1273       NewDocEntry = ReadNextDocEntry( );
1274       if (!NewDocEntry)
1275          break;
1276          
1277       std::cout << hex 
1278                << " gr " 
1279                << NewDocEntry->GetGroup() 
1280                << " el "
1281                << NewDocEntry->GetElement() 
1282                << " vr "
1283                << NewDocEntry->GetVR()
1284                << " lgt "
1285                << NewDocEntry->GetReadLength()
1286                << " off "
1287                << NewDocEntry->GetOffset()             
1288                << std::endl;
1289                
1290       vr = NewDocEntry->GetVR();         
1291       if (vr!="SQ") {
1292                
1293          if (vr == "AE" || vr == "AS" || vr == "DA" || vr == "PN" || 
1294              vr == "UI" || vr == "TM" || vr == "SH" || vr == "LO" ||
1295              vr == "CS" || vr == "IS" || vr == "LO" || vr == "LT" ||
1296              vr == "SH" || vr == "ST" ||                  
1297              vr == "SL" || vr == "SS" || vr == "UL" || vr == "US"
1298                                                                   ) {
1299       // --- ValEntry                            
1300             vl= new gdcmValEntry(NewDocEntry->GetDictEntry());
1301             vl->Copy(NewDocEntry);
1302             set->AddEntry(vl);
1303             LoadDocEntry(vl);
1304             std::cout << "value [" << vl->GetValue() << "]" << std::endl;
1305             if (/*!delim_mode && */vl->isItemDelimitor())
1306                break;
1307             cout << hex
1308                  << " l_max = "<< l_max
1309                  << " offset = " << offset
1310                  << " ftell(fp) = " << ftell(fp)
1311                  << endl;
1312             if ( !delim_mode && ftell(fp)-offset >= l_max)
1313                break;        
1314          } else { // BinEntry
1315          
1316         // Hope the following VR *do* correspond to a BinEntry 
1317                 
1318         //AT Attribute Tag;         // 2 16-bit unsigned short integers
1319         //FL Floating Point Single; // 32-bit IEEE 754:1985 float
1320         //FD Floating Point Double; // 64-bit IEEE 754:1985 double
1321         //UN Unknown;               // Any length of bytes
1322         //UT Unlimited Text;        // At most 2^32 -1 chars
1323         //OB Other Byte String;     // String of bytes (VR independant)
1324         //OW Other Word String;     // String of 16-bit words (VR dependant)
1325                  
1326             bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1327             bn->Copy(NewDocEntry);
1328             LoadDocEntry(bn);
1329             std::cout << "value [" << "Bin Entry, in voidArea" << "]" << std::endl;                      
1330          }      
1331
1332           SkipToNextDocEntry(NewDocEntry); // to be sure we are at the beginning 
1333           l = NewDocEntry->GetFullLength(); 
1334             
1335       } else {   // VR = "SQ"
1336             
1337          std::cout << "gdcmDocument::ParseDES : SQ found " << std::endl;
1338          l=NewDocEntry->GetReadLength();
1339          
1340          if (l == 0xffffffff)
1341            delim_mode = true;
1342          else
1343            delim_mode = false;
1344            
1345          sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry());
1346          sq->Copy(NewDocEntry);
1347          sq->SetDelimitorMode(delim_mode);
1348
1349          if (l != 0) {  // Don't try to parse zero-length sequences              
1350             long lgt = ParseSQ((gdcmDocEntrySet *)sq, 
1351                                 //NewDocEntry->GetOffset(),
1352                                 offset, // marche pour DICOMDIR, plante sur 3...dcm
1353                                 l, delim_mode);
1354          }
1355          // FIXME : on en fait quoi, de lgt ?
1356          set->AddEntry(sq);
1357          cout << " l_max = " << l_max
1358               << " offset = " << offset
1359               << "ftell(fp) = " << ftell(fp)
1360               << endl;
1361          if ( !delim_mode && ftell(fp)-offset >= l_max)
1362             break;
1363       } 
1364    }
1365    cout << endl; 
1366    delete NewDocEntry;   
1367    return l; // ?? 
1368 }
1369
1370 /**
1371  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1372  * @return  parsed length for this level
1373  */ 
1374 long gdcmDocument::ParseSQ(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1375
1376    cout << "=================== gdcmDocument::ParseSQ on entre ds une Sequence"
1377         << hex
1378         << " offset " << offset
1379         << " l_max " << l_max
1380         << " delim_mode " << delim_mode
1381         <<endl;
1382    int SQItemNumber = 0;
1383    gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1384    gdcmSQItem *itemSQ;
1385    bool dlm_mod;
1386    int lgr, l, lgth;
1387    
1388    while (true) {
1389       std::cout << " ===== gdcmDocument::ParseSQ on itere "
1390                 << "sur les SQ Items : num " 
1391                  << SQItemNumber << std::endl;
1392       
1393       NewDocEntry = ReadNextDocEntry();
1394 cout << "=============================== isSequenceDelimitor " 
1395      << NewDocEntry->isSequenceDelimitor() 
1396      << endl;     
1397       if(delim_mode) {   
1398           if (NewDocEntry->isSequenceDelimitor()) {
1399              cout << " SequenceDelimitationItem found" << endl;
1400           //                    add the Sequence Delimitor  // TODO : find the trick to put it proprerly !
1401           //   ((gdcmSeqEntry *)set)->SetSequenceDelimitationItem(NewDocEntry);
1402              break;
1403           }          
1404       }      
1405       if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1406              cout << hex
1407                   << " offset " << offset
1408                   << " l_max " << l_max
1409                   << " ftell " << ftell(fp)
1410                   << endl;               
1411              cout << "depasse ou atteint : on sort " << endl;    
1412              break;
1413       }         
1414       itemSQ = new gdcmSQItem();
1415       itemSQ->AddEntry(NewDocEntry); // no value, no voidArea. Think of it while printing !
1416       l= NewDocEntry->GetReadLength();
1417       cout << "NewDocEntry->GetReadLength() " << l << endl;
1418       if (l ==0xffffffff)
1419          dlm_mod = true;
1420       else
1421          dlm_mod=false;
1422 cout << "================================ appel ParseDES :dlm_mod = " << dlm_mod <<endl;      
1423       lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1424       ((gdcmSeqEntry *)set)->AddEntry(itemSQ);   
1425 cout << "================================ sortie ParseDES " << endl;
1426       SQItemNumber ++;
1427    }
1428    //Update(lgth); 
1429    lgth = ftell(fp) - offset;
1430    cout << "=============== lgr Sequence :" << lgth <<endl;
1431    return(lgth);
1432 }
1433
1434
1435 /**
1436  * \brief   Parses the header of the file and load element values.
1437  * @return  false if file is not ACR-NEMA / PAPYRUS / DICOM 
1438  */
1439
1440 /* =======================================================================
1441 // Replaced by ParseSQ
1442   
1443 bool gdcmDocument::LoadHeaderEntries(bool exception_on_error) throw(gdcmFormatError) {
1444    (void)exception_on_error;
1445    rewind(fp);
1446    if (!CheckSwap())
1447       return false;
1448       
1449    gdcmDocEntry *newDocEntry = (gdcmDocEntry *)0;   
1450    while ( (newDocEntry = ReadNextDocEntry()) ) {
1451      SkipDocEntry(newDocEntry);
1452      if ( (ignoreShadow==0) || (newDocEntry->GetGroup()%2) == 0) { 
1453         AddEntry(newDocEntry); 
1454      }     
1455    }   
1456    rewind(fp);
1457    // Be carefull : merging this two loops may cause troubles ...
1458    for (ListTag::iterator i = GetListEntry().begin();                           
1459         i != GetListEntry().end();                                                
1460         ++i)                                                                      
1461    {                                                                            
1462       LoadDocEntry(*i);                                                      
1463    }                                                                            
1464    rewind(fp);                                                                     
1465    
1466    // Load 'non string' values
1467  
1468    
1469    // --------------------------------------------------------------
1470    // Special Patch to allow gdcm to read ACR-LibIDO formated images
1471    //
1472    // if recognition code tells us we deal with a LibIDO image
1473    // we switch lineNumber and columnNumber
1474    //
1475    std::string RecCode;
1476    RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1477    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1478        RecCode == "CANRME_AILIBOD1_1." )  // for brain-damaged softwares
1479                                           // with "little-endian strings"
1480    {
1481          filetype = ACR_LIBIDO; 
1482          std::string rows    = GetEntryByNumber(0x0028, 0x0010);
1483          std::string columns = GetEntryByNumber(0x0028, 0x0011);
1484          SetEntryByNumber(columns, 0x0028, 0x0010);
1485          SetEntryByNumber(rows   , 0x0028, 0x0011);
1486    }
1487    // ----------------- End of Special Patch ----------------   
1488    return true;
1489 }
1490 ======================================================================= */
1491
1492
1493 /**
1494  * \brief         Loads the element content if its length doesn't exceed
1495  *                the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1496  * @param         Entry Header Entry (Dicom Element) to be dealt with
1497  */
1498 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)  {
1499    size_t item_read;
1500    guint16 group  = Entry->GetGroup();
1501    std::string  vr= Entry->GetVR();
1502    guint32 length = Entry->GetLength();
1503
1504    fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1505
1506    // A SeQuence "contains" a set of Elements.  
1507    //          (fffe e000) tells us an Element is beginning
1508    //          (fffe e00d) tells us an Element just ended
1509    //          (fffe e0dd) tells us the current SeQuence just ended
1510    if( group == 0xfffe ) {
1511       // NO more value field for SQ !
1512       //Entry->SetValue("gdcm::Skipped");
1513       // appel recursif de Load Value
1514       // (meme pb que pour le parsing)
1515       return;
1516    }
1517
1518    // When the length is zero things are easy:
1519    if ( length == 0 ) {
1520       ((gdcmValEntry *)Entry)->SetValue("");
1521       return;
1522    }
1523
1524    // The elements whose length is bigger than the specified upper bound
1525    // are not loaded. Instead we leave a short notice of the offset of
1526    // the element content and it's length.
1527    if (length > MaxSizeLoadEntry) {
1528       std::ostringstream s;
1529       s << "gdcm::NotLoaded.";
1530       s << " Address:" << (long)Entry->GetOffset();
1531       s << " Length:"  << Entry->GetLength();
1532       s << " x(" << std::hex << Entry->GetLength() << ")";
1533       ((gdcmValEntry *)Entry)->SetValue(s.str());
1534       return;
1535    }
1536     
1537    // Any compacter code suggested (?)
1538    if ( IsDocEntryAnInteger(Entry) ) {   
1539       guint32 NewInt;
1540       std::ostringstream s;
1541       int nbInt;
1542    // When short integer(s) are expected, read and convert the following 
1543    // n *two characters properly i.e. as short integers as opposed to strings.
1544    // Elements with Value Multiplicity > 1
1545    // contain a set of integers (not a single one)       
1546       if (vr == "US" || vr == "SS") {
1547          nbInt = length / 2;
1548          NewInt = ReadInt16();
1549          s << NewInt;
1550          if (nbInt > 1){
1551             for (int i=1; i < nbInt; i++) {
1552                s << '\\';
1553                NewInt = ReadInt16();
1554                s << NewInt;
1555             }
1556          }
1557       }
1558    // When integer(s) are expected, read and convert the following 
1559    // n * four characters properly i.e. as integers as opposed to strings.
1560    // Elements with Value Multiplicity > 1
1561    // contain a set of integers (not a single one)           
1562       else if (vr == "UL" || vr == "SL") {
1563          nbInt = length / 4;
1564          NewInt = ReadInt32();
1565          s << NewInt;
1566          if (nbInt > 1) {
1567             for (int i=1; i < nbInt; i++) {
1568                s << '\\';
1569                NewInt = ReadInt32();
1570                s << NewInt;
1571             }
1572          }
1573       }
1574 #ifdef GDCM_NO_ANSI_STRING_STREAM
1575       s << std::ends; // to avoid oddities on Solaris
1576 #endif //GDCM_NO_ANSI_STRING_STREAM
1577
1578       ((gdcmValEntry *)Entry)->SetValue(s.str());
1579       return;
1580    }
1581    
1582    // We need an additional byte for storing \0 that is not on disk
1583    std::string NewValue(length,0);
1584    item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1585    if ( item_read != 1 ) {
1586       dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1587       ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1588       return;
1589    }
1590
1591    if( (vr == "UI") ) // Because of correspondance with the VR dic
1592       ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1593    else
1594       ((gdcmValEntry *)Entry)->SetValue(NewValue);
1595 }
1596
1597
1598 /**
1599  * \brief  Find the value Length of the passed Header Entry
1600  * @param  Entry Header Entry whose length of the value shall be loaded. 
1601  */
1602  void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1603    guint16 element = Entry->GetElement();
1604    //guint16 group   = Entry->GetGroup(); //FIXME
1605    std::string  vr = Entry->GetVR();
1606    guint16 length16;
1607        
1608    
1609    if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) ) 
1610    {
1611       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) 
1612       {
1613          // The following reserved two bytes (see PS 3.5-2001, section
1614          // 7.1.2 Data element structure with explicit vr p27) must be
1615          // skipped before proceeding on reading the length on 4 bytes.
1616          fseek(fp, 2L, SEEK_CUR);
1617          guint32 length32 = ReadInt32();
1618
1619          if ( (vr == "OB") && (length32 == 0xffffffff) ) 
1620          {
1621             Entry->SetLength(FindDocEntryLengthOB());
1622             return;
1623          }
1624          FixDocEntryFoundLength(Entry, length32); 
1625          return;
1626       }
1627
1628       // Length is encoded on 2 bytes.
1629       length16 = ReadInt16();
1630       
1631       // We can tell the current file is encoded in big endian (like
1632       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1633       // and it's value is the one of the encoding of a big endian file.
1634       // In order to deal with such big endian encoded files, we have
1635       // (at least) two strategies:
1636       // * when we load the "Transfer Syntax" tag with value of big endian
1637       //   encoding, we raise the proper flags. Then we wait for the end
1638       //   of the META group (0x0002) among which is "Transfer Syntax",
1639       //   before switching the swap code to big endian. We have to postpone
1640       //   the switching of the swap code since the META group is fully encoded
1641       //   in little endian, and big endian coding only starts at the next
1642       //   group. The corresponding code can be hard to analyse and adds
1643       //   many additional unnecessary tests for regular tags.
1644       // * the second strategy consists in waiting for trouble, that shall
1645       //   appear when we find the first group with big endian encoding. This
1646       //   is easy to detect since the length of a "Group Length" tag (the
1647       //   ones with zero as element number) has to be of 4 (0x0004). When we
1648       //   encounter 1024 (0x0400) chances are the encoding changed and we
1649       //   found a group with big endian encoding.
1650       // We shall use this second strategy. In order to make sure that we
1651       // can interpret the presence of an apparently big endian encoded
1652       // length of a "Group Length" without committing a big mistake, we
1653       // add an additional check: we look in the already parsed elements
1654       // for the presence of a "Transfer Syntax" whose value has to be "big
1655       // endian encoding". When this is the case, chances are we have got our
1656       // hands on a big endian encoded file: we switch the swap code to
1657       // big endian and proceed...
1658       if ( (element  == 0x0000) && (length16 == 0x0400) ) 
1659       {
1660          if ( ! IsExplicitVRBigEndianTransferSyntax() ) 
1661          {
1662             dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1663             errno = 1;
1664             return;
1665          }
1666          length16 = 4;
1667          SwitchSwapToBigEndian();
1668          // Restore the unproperly loaded values i.e. the group, the element
1669          // and the dictionary entry depending on them.
1670          guint16 CorrectGroup   = SwapShort(Entry->GetGroup());
1671          guint16 CorrectElem    = SwapShort(Entry->GetElement());
1672          gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1673                                                        CorrectElem);
1674          if (!NewTag) 
1675          {
1676             // This correct tag is not in the dictionary. Create a new one.
1677             NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1678          }
1679          // FIXME this can create a memory leaks on the old entry that be
1680          // left unreferenced.
1681          Entry->SetDictEntry(NewTag);
1682       }
1683        
1684       // Heuristic: well some files are really ill-formed.
1685       if ( length16 == 0xffff) 
1686       {
1687          length16 = 0;
1688          //dbg.Verbose(0, "gdcmDocument::FindLength",
1689          //            "Erroneous element length fixed.");
1690          // Actually, length= 0xffff means that we deal with
1691          // Unknown Sequence Length 
1692       }
1693       FixDocEntryFoundLength(Entry, (guint32)length16);
1694       return;
1695    }
1696    else
1697    {
1698       // Either implicit VR or a non DICOM conformal (see note below) explicit
1699       // VR that ommited the VR of (at least) this element. Farts happen.
1700       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1701       // on Data elements "Implicit and Explicit VR Data Elements shall
1702       // not coexist in a Data Set and Data Sets nested within it".]
1703       // Length is on 4 bytes.
1704       
1705       FixDocEntryFoundLength(Entry, ReadInt32());
1706       return;
1707    }
1708 }
1709
1710 /**
1711  * \brief     Find the Value Representation of the current Dicom Element.
1712  * @param     Entry
1713  */
1714 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry) 
1715 {
1716    if (filetype != gdcmExplicitVR)
1717       return;
1718
1719    char VR[3];
1720
1721    long PositionOnEntry = ftell(fp);
1722    // Warning: we believe this is explicit VR (Value Representation) because
1723    // we used a heuristic that found "UL" in the first tag. Alas this
1724    // doesn't guarantee that all the tags will be in explicit VR. In some
1725    // cases (see e-film filtered files) one finds implicit VR tags mixed
1726    // within an explicit VR file. Hence we make sure the present tag
1727    // is in explicit VR and try to fix things if it happens not to be
1728    // the case.
1729    
1730    (void)fread (&VR, (size_t)2,(size_t)1, fp);
1731    VR[2]=0;
1732    if(!CheckDocEntryVR(Entry,VR))
1733    {
1734       fseek(fp, PositionOnEntry, SEEK_SET);
1735       // When this element is known in the dictionary we shall use, e.g. for
1736       // the semantics (see the usage of IsAnInteger), the VR proposed by the
1737       // dictionary entry. Still we have to flag the element as implicit since
1738       // we know now our assumption on expliciteness is not furfilled.
1739       // avoid  .
1740       if ( Entry->IsVRUnknown() )
1741          Entry->SetVR("Implicit");
1742       Entry->SetImplicitVR();
1743    }
1744 }
1745
1746 /**
1747  * \brief     Check the correspondance between the VR of the header entry
1748  *            and the taken VR. If they are different, the header entry is 
1749  *            updated with the new VR.
1750  * @param     Entry Header Entry to check
1751  * @param     vr    Dicom Value Representation
1752  * @return    false if the VR is incorrect of if the VR isn't referenced
1753  *            otherwise, it returns true
1754 */
1755 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1756 {
1757    char msg[100]; // for sprintf
1758    bool RealExplicit = true;
1759
1760    // Assume we are reading a falsely explicit VR file i.e. we reached
1761    // a tag where we expect reading a VR but are in fact we read the
1762    // first to bytes of the length. Then we will interogate (through find)
1763    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1764    // both GCC and VC++ implementations of the STL map. Hence when the
1765    // expected VR read happens to be non-ascii characters we consider
1766    // we hit falsely explicit VR tag.
1767
1768    if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1769       RealExplicit = false;
1770
1771    // CLEANME searching the dicom_vr at each occurence is expensive.
1772    // PostPone this test in an optional integrity check at the end
1773    // of parsing or only in debug mode.
1774    if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1775       RealExplicit= false;
1776
1777    if ( !RealExplicit ) 
1778    {
1779       // We thought this was explicit VR, but we end up with an
1780       // implicit VR tag. Let's backtrack.   
1781       sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", 
1782                    Entry->GetGroup(),Entry->GetElement());
1783       dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1784       if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1785          gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1786                                    Entry->GetGroup(),Entry->GetElement(),
1787                                    "UL","FIXME","Group Length");
1788          Entry->SetDictEntry(NewEntry);     
1789       }
1790       return(false);
1791    }
1792
1793    if ( Entry->IsVRUnknown() ) 
1794    {
1795       // When not a dictionary entry, we can safely overwrite the VR.
1796       if (Entry->GetElement() == 0x0000) { // Group length is UL !
1797          Entry->SetVR("UL");
1798       } else {
1799          Entry->SetVR(vr);
1800       }
1801    }
1802    else if ( Entry->GetVR() != vr ) 
1803    {
1804       // The VR present in the file and the dictionary disagree. We assume
1805       // the file writer knew best and use the VR of the file. Since it would
1806       // be unwise to overwrite the VR of a dictionary (since it would
1807       // compromise it's next user), we need to clone the actual DictEntry
1808       // and change the VR for the read one.
1809       gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1810                                  Entry->GetGroup(),Entry->GetElement(),
1811                                  vr,"FIXME",Entry->GetName());
1812       Entry->SetDictEntry(NewEntry);
1813    }
1814    return(true); 
1815 }
1816
1817 /**
1818  * \brief   Get the transformed value of the header entry. The VR value 
1819  *          is used to define the transformation to operate on the value
1820  * \warning NOT end user intended method !
1821  * @param   Entry 
1822  * @return  Transformed entry value
1823  */
1824 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1825 {
1826    if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1827    {
1828       std::string val=Entry->GetValue();
1829       std::string vr=Entry->GetVR();
1830       guint32 length = Entry->GetLength();
1831       std::ostringstream s;
1832       int nbInt;
1833
1834    // When short integer(s) are expected, read and convert the following 
1835    // n * 2 bytes properly i.e. as a multivaluated strings
1836    // (each single value is separated fromthe next one by '\'
1837    // as usual for standard multivaluated filels
1838    // Elements with Value Multiplicity > 1
1839    // contain a set of short integers (not a single one) 
1840    
1841       if (vr == "US" || vr == "SS")
1842       {
1843          guint16 NewInt16;
1844
1845          nbInt = length / 2;
1846          for (int i=0; i < nbInt; i++) 
1847          {
1848             if(i!=0)
1849                s << '\\';
1850             NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1851             NewInt16 = SwapShort(NewInt16);
1852             s << NewInt16;
1853          }
1854       }
1855
1856    // When integer(s) are expected, read and convert the following 
1857    // n * 4 bytes properly i.e. as a multivaluated strings
1858    // (each single value is separated fromthe next one by '\'
1859    // as usual for standard multivaluated filels
1860    // Elements with Value Multiplicity > 1
1861    // contain a set of integers (not a single one) 
1862       else if (vr == "UL" || vr == "SL")
1863       {
1864          guint32 NewInt32;
1865
1866          nbInt = length / 4;
1867          for (int i=0; i < nbInt; i++) 
1868          {
1869             if(i!=0)
1870                s << '\\';
1871             NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1872                      ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1873             NewInt32=SwapLong(NewInt32);
1874             s << NewInt32;
1875          }
1876       }
1877 #ifdef GDCM_NO_ANSI_STRING_STREAM
1878       s << std::ends; // to avoid oddities on Solaris
1879 #endif //GDCM_NO_ANSI_STRING_STREAM
1880       return(s.str());
1881    }
1882
1883    return(Entry->GetValue());
1884 }
1885
1886 /**
1887  * \brief   Get the reverse transformed value of the header entry. The VR 
1888  *          value is used to define the reverse transformation to operate on
1889  *          the value
1890  * \warning NOT end user intended method !
1891  * @param   Entry 
1892  * @return  Reverse transformed entry value
1893  */
1894 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1895 {
1896    if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1897    {
1898       std::string vr=Entry->GetVR();
1899       std::ostringstream s;
1900       std::vector<std::string> tokens;
1901
1902       if (vr == "US" || vr == "SS") 
1903       {
1904          guint16 NewInt16;
1905
1906          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1907          Tokenize (Entry->GetValue(), tokens, "\\");
1908          for (unsigned int i=0; i<tokens.size();i++) 
1909          {
1910             NewInt16 = atoi(tokens[i].c_str());
1911             s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1912          }
1913          tokens.clear();
1914       }
1915       if (vr == "UL" || vr == "SL") 
1916       {
1917          guint32 NewInt32;
1918
1919          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1920          Tokenize (Entry->GetValue(), tokens, "\\");
1921          for (unsigned int i=0; i<tokens.size();i++) 
1922          {
1923             NewInt32 = atoi(tokens[i].c_str());
1924             s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1925                <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1926          }
1927          tokens.clear();
1928       }
1929
1930 #ifdef GDCM_NO_ANSI_STRING_STREAM
1931       s << std::ends; // to avoid oddities on Solaris
1932 #endif //GDCM_NO_ANSI_STRING_STREAM
1933       return(s.str());
1934    }
1935
1936    return(Entry->GetValue());
1937 }
1938
1939 /**
1940  * \brief   Skip a given Header Entry 
1941  * \warning NOT end user intended method !
1942  * @param   entry 
1943  */
1944 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry) 
1945 {
1946    SkipBytes(entry->GetLength());
1947 }
1948
1949 /**
1950  * \brief   Skips to the begining of the next Header Entry 
1951  * \warning NOT end user intended method !
1952  * @param   entry 
1953  */
1954 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry) 
1955 {
1956    (void)fseek(fp, (long)(entry->GetOffset()),     SEEK_SET);
1957    (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1958 }
1959
1960 /**
1961  * \brief   Loads the value for a a given VLEntry 
1962  * \warning NOT end user intended method !
1963  * @param   entry 
1964  */
1965 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry) 
1966 {
1967     //SkipBytes(entry->GetLength());
1968     LoadDocEntry(entry);
1969 }
1970 /**
1971  * \brief   When the length of an element value is obviously wrong (because
1972  *          the parser went Jabberwocky) one can hope improving things by
1973  *          applying this heuristic.
1974  */
1975 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry, guint32 FoundLength) 
1976 {
1977    Entry->SetReadLength(FoundLength); // will be updated only if a bug is found        
1978    if ( FoundLength == 0xffffffff) {
1979       FoundLength = 0;
1980    }
1981    
1982    guint16 gr =Entry->GetGroup();
1983    guint16 el =Entry->GetElement(); 
1984      
1985    if (FoundLength%2) {
1986       std::ostringstream s;
1987       s << "Warning : Tag with uneven length " << FoundLength 
1988          <<  " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1989       dbg.Verbose(0,s.str().c_str());
1990    }
1991       
1992    // Sorry for the patch!  
1993    // XMedCom did the trick to read some naughty GE images ...
1994    if (FoundLength == 13) {
1995       // The following 'if' will be removed when there is no more
1996       // images on Creatis HDs with a 13 length for Manufacturer...
1997       if ( (Entry->GetGroup() != 0x0008) ||  
1998            ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1999       // end of remove area
2000          FoundLength =10;
2001          Entry->SetReadLength(10); // a bug is to be fixed
2002       }
2003    }
2004
2005    // to fix some garbage 'Leonardo' Siemens images
2006    // May be commented out to avoid overhead
2007    else if ( (Entry->GetGroup() == 0x0009) &&
2008        ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
2009       FoundLength =4;
2010       Entry->SetReadLength(4); // a bug is to be fixed 
2011    } 
2012    // end of fix
2013  
2014    // to try to 'go inside' SeQuences (with length), and not to skip them        
2015    else if ( Entry->GetVR() == "SQ") 
2016    { 
2017       if (enableSequences)    // only if the user does want to !
2018          FoundLength =0;      // ReadLength is unchanged 
2019    } 
2020     
2021    // we found a 'delimiter' element                                         
2022    // fffe|xxxx is just a marker, we don't take its length into account                                                   
2023    else if(Entry->GetGroup() == 0xfffe)
2024    {    
2025                                          // *normally, fffe|0000 doesn't exist ! 
2026      if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
2027                                          // causes extra troubles :-(                                                                   
2028         FoundLength =0;
2029    } 
2030            
2031    Entry->SetUsableLength(FoundLength);
2032 }
2033
2034 /**
2035  * \brief   Apply some heuristics to predict whether the considered 
2036  *          element value contains/represents an integer or not.
2037  * @param   Entry The element value on which to apply the predicate.
2038  * @return  The result of the heuristical predicate.
2039  */
2040 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2041    guint16 element = Entry->GetElement();
2042    guint16 group   = Entry->GetGroup();
2043    std::string  vr = Entry->GetVR();
2044    guint32 length  = Entry->GetLength();
2045    // When we have some semantics on the element we just read, and if we
2046    // a priori know we are dealing with an integer, then we shall be
2047    // able to swap it's element value properly.
2048    if ( element == 0 )  // This is the group length of the group
2049    {  
2050       if (length == 4)
2051          return true;
2052       else 
2053       {
2054          std::ostringstream s;
2055          int filePosition = ftell(fp);
2056          s << "Erroneous Group Length element length  on : (" \
2057            << std::hex << group << " , " << element 
2058            << ") -before- position x(" << filePosition << ")"
2059            << "lgt : " << length;
2060          // These 2 lines commented out : a *very dirty* patch
2061          // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
2062          // have a glance at offset  x(8336) ...
2063          // For *regular* headers, the test is useless..
2064          // lets's print a warning message and go on, 
2065          // instead of giving up with an error message
2066
2067          //std::cout << s.str().c_str() << std::endl;
2068          // dbg.Error("gdcmDocument::IsDocEntryAnInteger",
2069          //           s.str().c_str());     
2070       }
2071    }
2072    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2073       return true;
2074    
2075    return false;
2076 }
2077 /**
2078  * \brief  Find the Length till the next sequence delimiter
2079  * \warning NOT end user intended method !
2080  * @return 
2081  */
2082
2083  guint32 gdcmDocument::FindDocEntryLengthOB(void)  {
2084    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2085    guint16 g;
2086    guint16 n; 
2087    long PositionOnEntry = ftell(fp);
2088    bool FoundSequenceDelimiter = false;
2089    guint32 TotalLength = 0;
2090    guint32 ItemLength;
2091
2092    while ( ! FoundSequenceDelimiter) 
2093    {
2094       g = ReadInt16();
2095       n = ReadInt16();   
2096       if (errno == 1)
2097          return 0;
2098       TotalLength += 4;  // We even have to decount the group and element 
2099      
2100       if ( g != 0xfffe && g!=0xb00c ) //for bogus header  
2101       {
2102          char msg[100]; // for sprintf. Sorry
2103          sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2104          dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg); 
2105          errno = 1;
2106          return 0;
2107       }
2108       if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header 
2109          FoundSequenceDelimiter = true;
2110       else if ( n != 0xe000 )
2111       {
2112          char msg[100];  // for sprintf. Sorry
2113          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2114                       n, g,n);
2115          dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2116          errno = 1;
2117          return 0;
2118       }
2119       ItemLength = ReadInt32();
2120       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
2121                                       // the ItemLength with ReadInt32                                     
2122       SkipBytes(ItemLength);
2123    }
2124    fseek(fp, PositionOnEntry, SEEK_SET);
2125    return TotalLength;
2126 }
2127
2128 /**
2129  * \brief Reads a supposed to be 16 Bits integer
2130  *       (swaps it depending on processor endianity) 
2131  * @return read value
2132  */
2133 guint16 gdcmDocument::ReadInt16(void) {
2134    guint16 g;
2135    size_t item_read;
2136    item_read = fread (&g, (size_t)2,(size_t)1, fp);
2137    if ( item_read != 1 ) {
2138       if(ferror(fp)) 
2139          dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2140       errno = 1;
2141       return 0;
2142    }
2143    errno = 0;
2144    g = SwapShort(g);   
2145    return g;
2146 }
2147
2148 /**
2149  * \brief  Reads a supposed to be 32 Bits integer
2150  *         (swaps it depending on processor endianity)  
2151  * @return read value
2152  */
2153 guint32 gdcmDocument::ReadInt32(void) {
2154    guint32 g;
2155    size_t item_read;
2156    item_read = fread (&g, (size_t)4,(size_t)1, fp);
2157    if ( item_read != 1 ) { 
2158      if(ferror(fp)) 
2159          dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");   
2160       errno = 1;
2161       return 0;
2162    }
2163    errno = 0;   
2164    g = SwapLong(g);
2165    return g;
2166 }
2167
2168 /**
2169  * \brief skips bytes inside the source file 
2170  * \warning NOT end user intended method !
2171  * @return 
2172  */
2173 void gdcmDocument::SkipBytes(guint32 NBytes) {
2174    //FIXME don't dump the returned value
2175    (void)fseek(fp, (long)NBytes, SEEK_CUR);
2176 }
2177
2178 /**
2179  * \brief Loads all the needed Dictionaries
2180  * \warning NOT end user intended method !   
2181  */
2182 void gdcmDocument::Initialise(void) 
2183 {
2184    RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2185    RefShaDict = (gdcmDict*)0;
2186 }
2187
2188 /**
2189  * \brief   Discover what the swap code is (among little endian, big endian,
2190  *          bad little endian, bad big endian).
2191  *          sw is set
2192  * @return false when we are absolutely sure 
2193  *               it's neither ACR-NEMA nor DICOM
2194  *         true  when we hope ours assuptions are OK
2195  */
2196 bool gdcmDocument::CheckSwap() {
2197
2198    // The only guaranted way of finding the swap code is to find a
2199    // group tag since we know it's length has to be of four bytes i.e.
2200    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2201    // occurs when we can't find such group...
2202    
2203    guint32  x=4;  // x : for ntohs
2204    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2205    guint32  s32;
2206    guint16  s16;
2207        
2208    int lgrLue;
2209    char *entCur;
2210    char deb[HEADER_LENGTH_TO_READ];
2211     
2212    // First, compare HostByteOrder and NetworkByteOrder in order to
2213    // determine if we shall need to swap bytes (i.e. the Endian type).
2214    if (x==ntohs(x))
2215       net2host = true;
2216    else
2217       net2host = false; 
2218          
2219    // The easiest case is the one of a DICOM header, since it possesses a
2220    // file preamble where it suffice to look for the string "DICM".
2221    lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2222    
2223    entCur = deb + 128;
2224    if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2225       dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2226       
2227       // Next, determine the value representation (VR). Let's skip to the
2228       // first element (0002, 0000) and check there if we find "UL" 
2229       // - or "OB" if the 1st one is (0002,0001) -,
2230       // in which case we (almost) know it is explicit VR.
2231       // WARNING: if it happens to be implicit VR then what we will read
2232       // is the length of the group. If this ascii representation of this
2233       // length happens to be "UL" then we shall believe it is explicit VR.
2234       // FIXME: in order to fix the above warning, we could read the next
2235       // element value (or a couple of elements values) in order to make
2236       // sure we are not commiting a big mistake.
2237       // We need to skip :
2238       // * the 128 bytes of File Preamble (often padded with zeroes),
2239       // * the 4 bytes of "DICM" string,
2240       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2241       // i.e. a total of  136 bytes.
2242       entCur = deb + 136;
2243      
2244       // FIXME : FIXME:
2245       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2246       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2247       // *Implicit* VR.  -and it is !- 
2248       
2249       if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2250           (memcmp(entCur, "OB", (size_t)2) == 0) ||
2251           (memcmp(entCur, "UI", (size_t)2) == 0) ||
2252           (memcmp(entCur, "CS", (size_t)2) == 0) )  // CS, to remove later
2253                                                     // when Write DCM *adds*
2254       // FIXME
2255       // Use gdcmDocument::dicom_vr to test all the possibilities
2256       // instead of just checking for UL, OB and UI !? group 0000 
2257       {
2258          filetype = gdcmExplicitVR;
2259          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2260                      "explicit Value Representation");
2261       } 
2262       else 
2263       {
2264          filetype = gdcmImplicitVR;
2265          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2266                      "not an explicit Value Representation");
2267       }
2268       
2269       if (net2host) 
2270       {
2271          sw = 4321;
2272          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2273                         "HostByteOrder != NetworkByteOrder");
2274       } 
2275       else 
2276       {
2277          sw = 0;
2278          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2279                         "HostByteOrder = NetworkByteOrder");
2280       }
2281       
2282       // Position the file position indicator at first tag (i.e.
2283       // after the file preamble and the "DICM" string).
2284       rewind(fp);
2285       fseek (fp, 132L, SEEK_SET);
2286       return true;
2287    } // End of DicomV3
2288
2289    // Alas, this is not a DicomV3 file and whatever happens there is no file
2290    // preamble. We can reset the file position indicator to where the data
2291    // is (i.e. the beginning of the file).
2292    dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2293    rewind(fp);
2294
2295    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2296    // By clean we mean that the length of the first tag is written down.
2297    // If this is the case and since the length of the first group HAS to be
2298    // four (bytes), then determining the proper swap code is straightforward.
2299
2300    entCur = deb + 4;
2301    // We assume the array of char we are considering contains the binary
2302    // representation of a 32 bits integer. Hence the following dirty
2303    // trick :
2304    s32 = *((guint32 *)(entCur));
2305       
2306    switch (s32) {
2307       case 0x00040000 :
2308          sw = 3412;
2309          filetype = gdcmACR;
2310          return true;
2311       case 0x04000000 :
2312          sw = 4321;
2313          filetype = gdcmACR;
2314          return true;
2315       case 0x00000400 :
2316          sw = 2143;
2317          filetype = gdcmACR;
2318          return true;
2319       case 0x00000004 :
2320          sw = 0;
2321          filetype = gdcmACR;
2322          return true;
2323       default :
2324
2325       // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2326       // It is time for despaired wild guesses. 
2327       // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2328       //  i.e. the 'group length' element is not present :     
2329       
2330       //  check the supposed to be 'group number'
2331       //  0x0002 or 0x0004 or 0x0008
2332       //  to determine ' sw' value .
2333       //  Only 0 or 4321 will be possible 
2334       //  (no oportunity to check for the formerly well known
2335       //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2336       //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-) 
2337       //  the file IS NOT ACR-NEMA nor DICOM V3
2338       //  Find a trick to tell it the caller...
2339       
2340       s16 = *((guint16 *)(deb));
2341       
2342       switch (s16) {
2343       case 0x0002 :
2344       case 0x0004 :
2345       case 0x0008 :      
2346          sw = 0;
2347          filetype = gdcmACR;
2348          return true;
2349       case 0x0200 :
2350       case 0x0400 :
2351       case 0x0800 : 
2352          sw = 4321;
2353          filetype = gdcmACR;
2354          return true;
2355       default :
2356          dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2357                      "ACR/NEMA unfound swap info (Really hopeless !)"); 
2358          filetype = gdcmUnknown;     
2359          return false;
2360       }
2361       
2362       // Then the only info we have is the net2host one.
2363       //if (! net2host )
2364          //   sw = 0;
2365          //else
2366          //  sw = 4321;
2367          //return;
2368    }
2369 }
2370
2371 /**
2372  * \brief Restore the unproperly loaded values i.e. the group, the element
2373  *        and the dictionary entry depending on them. 
2374  */
2375 void gdcmDocument::SwitchSwapToBigEndian(void) 
2376 {
2377    dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2378                   "Switching to BigEndian mode.");
2379    if ( sw == 0    ) 
2380    {
2381       sw = 4321;
2382       return;
2383    }
2384    if ( sw == 4321 ) 
2385    {
2386       sw = 0;
2387       return;
2388    }
2389    if ( sw == 3412 ) 
2390    {
2391       sw = 2143;
2392       return;
2393    }
2394    if ( sw == 2143 )
2395       sw = 3412;
2396 }
2397
2398 /**
2399  * \brief  during parsing, Header Elements too long are not loaded in memory 
2400  * @param NewSize
2401  */
2402 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize) 
2403 {
2404    if (NewSize < 0)
2405       return;
2406    if ((guint32)NewSize >= (guint32)0xffffffff) 
2407    {
2408       MaxSizeLoadEntry = 0xffffffff;
2409       return;
2410    }
2411    MaxSizeLoadEntry = NewSize;
2412 }
2413
2414
2415 /**
2416  * \brief Header Elements too long will not be printed
2417  * \todo  See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE 
2418  * @param NewSize
2419  */
2420 void gdcmDocument::SetMaxSizePrintEntry(long NewSize) 
2421 {
2422    if (NewSize < 0)
2423       return;
2424    if ((guint32)NewSize >= (guint32)0xffffffff) 
2425    {
2426       MaxSizePrintEntry = 0xffffffff;
2427       return;
2428    }
2429    MaxSizePrintEntry = NewSize;
2430 }
2431
2432
2433
2434 /**
2435  * \brief   Read the next tag but WITHOUT loading it's value
2436  *          (read the 'Group Number', the 'Element Number',
2437  *           gets the Dict Entry
2438  *          gets the VR, gets the length, gets the offset value)
2439  * @return  On succes the newly created DocEntry, NULL on failure.      
2440  */
2441 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2442    guint16 g,n;
2443    gdcmDocEntry *NewEntry;
2444    g = ReadInt16();
2445    n = ReadInt16();
2446       
2447    if (errno == 1)
2448       // We reached the EOF (or an error occured) therefore 
2449       // header parsing has to be considered as finished.
2450       return (gdcmDocEntry *)0;
2451
2452 // Pb : how to propagate the element length (used in SkipDocEntry)
2453 //       direct call to SkipBytes ?
2454    
2455 //   if (ignoreShadow == 1 && g%2 ==1)
2456       // if user wants to skip shadow groups
2457       // and current element *is* a shadow element
2458       // we don't create anything
2459 //      return (gdcmDocEntry *)1; // to tell caller it's NOT finished
2460   
2461    NewEntry = NewDocEntryByNumber(g, n);
2462    FindDocEntryVR(NewEntry);
2463    FindDocEntryLength(NewEntry);
2464
2465    if (errno == 1) {
2466       // Call it quits
2467       delete NewEntry;
2468       return NULL;
2469    }
2470    NewEntry->SetOffset(ftell(fp));  
2471    return NewEntry;
2472 }
2473
2474 /**
2475  * \brief   Build a new Element Value from all the low level arguments. 
2476  *          Check for existence of dictionary entry, and build
2477  *          a default one when absent.
2478  * @param   Name    Name of the underlying DictEntry
2479  */
2480 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name) 
2481 {
2482    gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2483    if (!NewTag)
2484       NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2485
2486    gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2487    if (!NewEntry) 
2488    {
2489       dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2490                   "failed to allocate gdcmDocEntry");
2491       return (gdcmDocEntry *)0;
2492    }
2493    return NewEntry;
2494 }  
2495
2496 /**
2497  * \brief   Request a new virtual dict entry to the dict set
2498  * @param   group  group   of the underlying DictEntry
2499  * @param   element  element of the underlying DictEntry
2500  * @param   vr     VR of the underlying DictEntry
2501  * @param   fourth owner group
2502  * @param   name   english name
2503  */
2504 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2505                                                std::string vr,
2506                                                std::string fourth,
2507                                                std::string name)
2508 {
2509    return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2510 }
2511
2512 /**
2513  * \brief   Build a new Element Value from all the low level arguments. 
2514  *          Check for existence of dictionary entry, and build
2515  *          a default one when absent.
2516  * @param   Group group   of the underlying DictEntry
2517  * @param   Elem  element of the underlying DictEntry
2518  */
2519 gdcmDocEntry *gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem) 
2520 {
2521    // Find out if the tag we encountered is in the dictionaries:
2522    gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2523    if (!DictEntry)
2524       DictEntry = NewVirtualDictEntry(Group, Elem);
2525
2526    gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2527    if (!NewEntry) 
2528    {
2529       dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2530                   "failed to allocate gdcmDocEntry");
2531       return NULL;
2532    }
2533    return NewEntry;
2534 }
2535
2536 /// \todo Never used; commented out, waiting for removal.
2537 /**
2538  * \brief   Small utility function that creates a new manually crafted
2539  *          (as opposed as read from the file) gdcmDocEntry with user
2540  *          specified name and adds it to the public tag hash table.
2541  * \note    A fake TagKey is generated so the PubDict can keep it's coherence.
2542  * @param   NewTagName The name to be given to this new tag.
2543  * @param   VR The Value Representation to be given to this new tag.
2544  * @return  The newly hand crafted Element Value.
2545  */
2546 //gdcmDocEntry *gdcmDocument::NewManualDocEntryToPubDict(std::string NewTagName, 
2547 //                                                           std::string VR) 
2548 //{
2549 //   gdcmDocEntry *NewEntry = NULL;
2550 //   guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
2551 //   guint32 FreeElem = 0;
2552 //   gdcmDictEntry *DictEntry = NULL;
2553 //
2554 //   FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2555 //   if (FreeElem == UINT32_MAX) 
2556 //   {
2557 //      dbg.Verbose(1, "gdcmHeader::NewManualDocEntryToPubDict",
2558 //                     "Group 0xffff in Public Dict is full");
2559 //      return NULL;
2560 //   }
2561 //
2562 //   DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2563 //                                VR, "GDCM", NewTagName);
2564 //   NewEntry = new gdcmDocEntry(DictEntry);
2565 //   AddEntry(NewEntry);
2566 //   return NewEntry;
2567 //}
2568
2569 /**
2570  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2571  *          in the TagHt dictionary.
2572  * @param   group The generated tag must belong to this group.  
2573  * @return  The element of tag with given group which is fee.
2574  */
2575 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group) 
2576 {
2577    for (guint32 elem = 0; elem < UINT32_MAX; elem++) 
2578    {
2579       TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2580       if (tagHT.count(key) == 0)
2581          return elem;
2582    }
2583    return UINT32_MAX;
2584 }
2585
2586
2587 /**
2588  * \brief   Searches both the public and the shadow dictionary (when they
2589  *          exist) for the presence of the DictEntry with given name.
2590  *          The public dictionary has precedence on the shadow one.
2591  * @param   Name name of the searched DictEntry
2592  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2593  */
2594 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name) 
2595 {
2596    gdcmDictEntry *found = (gdcmDictEntry *)0;
2597    if (!RefPubDict && !RefShaDict) 
2598    {
2599       dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2600                      "we SHOULD have a default dictionary");
2601    }
2602    if (RefPubDict) 
2603    {
2604       found = RefPubDict->GetDictEntryByName(Name);
2605       if (found)
2606          return found;
2607    }
2608    if (RefShaDict) 
2609    {
2610       found = RefShaDict->GetDictEntryByName(Name);
2611       if (found)
2612          return found;
2613    }
2614    return found;
2615 }
2616
2617 /**
2618  * \brief   Searches both the public and the shadow dictionary (when they
2619  *          exist) for the presence of the DictEntry with given
2620  *          group and element. The public dictionary has precedence on the
2621  *          shadow one.
2622  * @param   group   group of the searched DictEntry
2623  * @param   element element of the searched DictEntry
2624  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2625  */
2626 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element) 
2627 {
2628    gdcmDictEntry *found = (gdcmDictEntry *)0;
2629    if (!RefPubDict && !RefShaDict) 
2630    {
2631       dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2632                      "we SHOULD have a default dictionary");
2633    }
2634    if (RefPubDict) 
2635    {
2636       found = RefPubDict->GetDictEntryByNumber(group, element);
2637       if (found)
2638          return found;
2639    }
2640    if (RefShaDict) 
2641    {
2642       found = RefShaDict->GetDictEntryByNumber(group, element);
2643       if (found)
2644          return found;
2645    }
2646    return found;
2647 }
2648
2649
2650
2651 //-----------------------------------------------------------------------------