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