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