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