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