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