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