]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
remove old mutimap related code
[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 14:29:52 $
7   Version:   $Revision: 1.39 $
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(std::string 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   group     group number of the Dicom Element to modify
850  * @param   element element number of the Dicom Element to modify
851  */
852 bool gdcmDocument::SetEntryByNumber(void *content,
853                                   int lgth, 
854                                   guint16 group,
855                                   guint16 element) 
856 {
857    (void)lgth;  //not used
858    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
859    if ( ! tagHT.count(key))
860       return false;
861
862 /* Hope Binray field length is never wrong    
863    if(lgth%2) // Non even length are padded with a space (020H).
864    {  
865       lgth++;
866       //content = content + '\0'; // fing a trick to enlarge a binary field?
867    }
868 */      
869    gdcmBinEntry * a;
870    a = (gdcmBinEntry *)tagHT[key];           
871    a->SetVoidArea(content);  
872    //a->SetLength(lgth);  // ???  
873    return true;
874
875
876 /**
877  * \brief   Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
878  *          in the PubDocEntrySet of this instance
879  *          through it's (group, element) and modifies it's length with
880  *          the given value.
881  * \warning Use with extreme caution.
882  * @param l new length to substitute with
883  * @param group     group number of the Entry to modify
884  * @param element element number of the Entry to modify
885  * @return  true on success, false otherwise.
886  */
887 bool gdcmDocument::SetEntryLengthByNumber(guint32 l, 
888                                         guint16 group, 
889                                         guint16 element) 
890 {
891    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
892    if ( ! tagHT.count(key))
893       return false;
894    if (l%2) l++; // length must be even
895    ( ((tagHT.equal_range(key)).first)->second )->SetLength(l); 
896
897    return true ;
898 }
899
900 /**
901  * \brief   Gets (from Header) the offset  of a 'non string' element value 
902  *          (LoadElementValues has already be executed)
903  * @param Group   group number of the Entry 
904  * @param Elem  element number of the Entry
905  * @return File Offset of the Element Value 
906  */
907 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem) 
908 {
909    gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
910    if (!Entry) 
911    {
912       dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
913       return (size_t)0;
914    }
915    return Entry->GetOffset();
916 }
917
918 /**
919  * \brief   Gets (from Header) a 'non string' element value 
920  *          (LoadElementValues has already be executed)  
921  * @param Group   group number of the Entry 
922  * @param Elem  element number of the Entry
923  * @return Pointer to the 'non string' area
924  */
925 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem) 
926 {
927    gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
928    if (!Entry) 
929    {
930       dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
931       return (NULL);
932    }
933    return ((gdcmBinEntry *)Entry)->GetVoidArea();
934 }
935
936 /**
937  * \brief         Loads (from disk) the element content 
938  *                when a string is not suitable
939  * @param Group   group number of the Entry 
940  * @param Elem  element number of the Entry
941  */
942 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem) 
943 {
944    gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
945    if ( !Element )
946       return NULL;
947    size_t o =(size_t)Element->GetOffset();
948    fseek(fp, o, SEEK_SET);
949    size_t l = Element->GetLength();
950    char* a = new char[l];
951    if(!a) {
952       dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
953       return NULL;
954    }
955    SetEntryVoidAreaByNumber(a, Group, Elem);
956    /// \todo check the result 
957    size_t l2 = fread(a, 1, l ,fp);
958    if(l != l2) 
959    {
960       delete[] a;
961       return NULL;
962    }
963    return a;  
964 }
965 /**
966  * \brief         Loads (from disk) the element content 
967  *                when a string is not suitable
968  * @param Element  Entry whose voidArea is going to be loaded
969  */
970 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *Element) 
971 {
972    size_t o =(size_t)Element->GetOffset();
973    fseek(fp, o, SEEK_SET);
974    size_t l = Element->GetLength();
975    char* a = new char[l];
976    if(!a) {
977       dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
978       return NULL;
979    }
980    Element->SetVoidArea((void *)a);
981    /// \todo check the result 
982    size_t l2 = fread(a, 1, l ,fp);
983    if(l != l2) 
984    {
985       delete[] a;
986       return NULL;
987    }
988    return a;  
989 }
990
991 /**
992  * \brief   Sets a 'non string' value to a given Dicom Element
993  * @param   area area containing the 'non string' value
994  * @param   group     Group number of the searched Dicom Element 
995  * @param   element Element number of the searched Dicom Element 
996  * @return  
997  */
998 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
999                                           guint16 group, 
1000                                           guint16 element) 
1001 {
1002    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1003    if ( ! tagHT.count(key))
1004       return false;
1005       // This was for multimap ?
1006     (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1007       
1008    return true;
1009 }
1010
1011 /**
1012  * \brief   Update the entries with the shadow dictionary. 
1013  *          Only non even entries are analyzed       
1014  */
1015 void gdcmDocument::UpdateShaEntries(void) {
1016    //gdcmDictEntry *entry;
1017    std::string vr;
1018    
1019    /// \todo TODO : still any use to explore recursively the whole structure?
1020 /*
1021    for(ListTag::iterator it=listEntries.begin();
1022        it!=listEntries.end();
1023        ++it)
1024    {
1025       // Odd group => from public dictionary
1026       if((*it)->GetGroup()%2==0)
1027          continue;
1028
1029       // Peer group => search the corresponding dict entry
1030       if(RefShaDict)
1031          entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1032       else
1033          entry=NULL;
1034
1035       if((*it)->IsImplicitVR())
1036          vr="Implicit";
1037       else
1038          vr=(*it)->GetVR();
1039
1040       (*it)->SetValue(GetDocEntryUnvalue(*it));  // to go on compiling
1041       if(entry){
1042          // Set the new entry and the new value
1043          (*it)->SetDictEntry(entry);
1044          CheckDocEntryVR(*it,vr);
1045
1046          (*it)->SetValue(GetDocEntryValue(*it));    // to go on compiling
1047  
1048       }
1049       else
1050       {
1051          // Remove precedent value transformation
1052          (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1053       }
1054    }
1055 */   
1056 }
1057
1058 /**
1059  * \brief   Searches within the Header Entries for a Dicom Element of
1060  *          a given tag.
1061  * @param   tagName name of the searched Dicom Element.
1062  * @return  Corresponding Dicom Element when it exists, and NULL
1063  *          otherwise.
1064  */
1065  gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1066    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
1067    if( dictEntry == NULL)
1068       return NULL;
1069
1070   return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1071 }
1072
1073 /**
1074  * \brief  retrieves a Dicom Element (the first one) using (group, element)
1075  * \warning (group, element) IS NOT an identifier inside the Dicom Header
1076  *           if you think it's NOT UNIQUE, check the count number
1077  *           and use iterators to retrieve ALL the Dicoms Elements within
1078  *           a given couple (group, element)
1079  * @param   group Group number of the searched Dicom Element 
1080  * @param   element Element number of the searched Dicom Element 
1081  * @return  
1082  */
1083 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element) 
1084 {
1085    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1086    if ( ! tagHT.count(key))
1087       return NULL;
1088    return tagHT.find(key)->second;
1089 }
1090
1091 /**
1092  * \brief  Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1093  *         returns a result when the corresponding entry is of type
1094  *         ValEntry.
1095  * @return When present, the corresponding ValEntry. 
1096  */
1097 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1098 {
1099   gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1100   if (! CurrentEntry)
1101      return (gdcmValEntry*)0;
1102   if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1103   {
1104      return ValEntry;
1105   }
1106   dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1107   return (gdcmValEntry*)0;
1108 }
1109
1110 /**
1111  * \brief         Loads the element while preserving the current
1112  *                underlying file position indicator as opposed to
1113  *                to LoadDocEntry that modifies it.
1114  * @param entry   Header Entry whose value shall be loaded. 
1115  * @return  
1116  */
1117 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1118    long PositionOnEntry = ftell(fp);
1119    LoadDocEntry(entry);
1120    fseek(fp, PositionOnEntry, SEEK_SET);
1121 }
1122
1123 /**
1124  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1125  *          processor order.
1126  * @return  The properly swaped 32 bits integer.
1127  */
1128 guint32 gdcmDocument::SwapLong(guint32 a) {
1129    switch (sw) {
1130       case    0 :
1131          break;
1132       case 4321 :
1133          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
1134              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1135          break;
1136    
1137       case 3412 :
1138          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1139          break;
1140    
1141       case 2143 :
1142          a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1143          break;
1144       default :
1145          std::cout << "swapCode= " << sw << std::endl;
1146          dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1147          a=0;
1148    }
1149    return a;
1150
1151
1152 /**
1153  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
1154  *          processor order.
1155  * @return  The properly unswaped 32 bits integer.
1156  */
1157 guint32 gdcmDocument::UnswapLong(guint32 a) {
1158    return SwapLong(a);
1159 }
1160
1161 /**
1162  * \brief   Swaps the bytes so they agree with the processor order
1163  * @return  The properly swaped 16 bits integer.
1164  */
1165 guint16 gdcmDocument::SwapShort(guint16 a) {
1166    if ( (sw==4321)  || (sw==2143) )
1167       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1168    return a;
1169 }
1170
1171 /**
1172  * \brief   Unswaps the bytes so they agree with the processor order
1173  * @return  The properly unswaped 16 bits integer.
1174  */
1175 guint16 gdcmDocument::UnswapShort(guint16 a) {
1176    return SwapShort(a);
1177 }
1178
1179 //-----------------------------------------------------------------------------
1180 // Private
1181
1182 /**
1183  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1184  * @return  length of the parsed set. 
1185  */ 
1186
1187 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1188
1189    gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1190    gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1191    gdcmBinEntry *bn;   
1192    gdcmSeqEntry *sq;
1193    VRKey vr;
1194    unsigned long l = 0;
1195    int depth; 
1196    
1197    depth = set->GetDepthLevel();     
1198    while (true) { 
1199    
1200       if ( !delim_mode && ftell(fp)-offset >= l_max) { 
1201          break;  
1202       }
1203       NewDocEntry = ReadNextDocEntry( );
1204       if (!NewDocEntry)
1205          break;
1206      // NewDocEntry->Print(); cout << endl; //JPR
1207       vr = NewDocEntry->GetVR();
1208       if (vr!="SQ")
1209       {
1210                
1211          if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1212          {
1213             /////// ValEntry
1214             NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1215             NewValEntry->Copy(NewDocEntry);
1216             NewValEntry->SetDepthLevel(depth);
1217             set->AddEntry(NewValEntry);
1218             LoadDocEntry(NewValEntry);
1219             if (NewValEntry->isItemDelimitor())
1220                break;
1221             if ( !delim_mode && ftell(fp)-offset >= l_max)
1222             {
1223                break;
1224             }
1225          }
1226          else
1227          {
1228             if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1229             { 
1230                 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1231                 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1232                                "nor BinEntry. Probably unknown VR.");
1233             }
1234
1235             ////// BinEntry or UNKOWN VR:
1236             bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1237             bn->Copy(NewDocEntry);
1238             set->AddEntry(bn);
1239             LoadDocEntry(bn);
1240          }
1241
1242          if (NewDocEntry->GetGroup()   == 0x7fe0 && 
1243              NewDocEntry->GetElement() == 0x0010 )
1244          {
1245              if (NewDocEntry->GetReadLength()==0xffffffff)
1246              {
1247                 // Broken US.3405.1.dcm
1248                 Parse7FE0(); // to skip the pixels 
1249                              // (multipart JPEG/RLE are trouble makers)
1250              }
1251              else
1252              {
1253                 SkipToNextDocEntry(NewDocEntry);
1254                 l = NewDocEntry->GetFullLength(); 
1255              }
1256          }
1257          else
1258          {
1259              // to be sure we are at the beginning 
1260              SkipToNextDocEntry(NewDocEntry);
1261              l = NewDocEntry->GetFullLength(); 
1262          }
1263       }
1264       else
1265       {   // VR = "SQ"
1266       
1267          l=NewDocEntry->GetReadLength();            
1268          if (l != 0) // don't mess the delim_mode for zero-length sequence
1269             if (l == 0xffffffff)
1270               delim_mode = true;
1271             else
1272               delim_mode = false;
1273          // no other way to create it ...
1274          sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1275                                set->GetDepthLevel());
1276          sq->Copy(NewDocEntry);
1277          sq->SetDelimitorMode(delim_mode);
1278          sq->SetDepthLevel(depth);
1279
1280          if (l != 0)
1281          {  // Don't try to parse zero-length sequences
1282             long lgt = ParseSQ( sq, 
1283                                 NewDocEntry->GetOffset(),
1284                                 l, delim_mode);
1285             (void)lgt;  //not used...
1286          }
1287          set->AddEntry(sq);
1288          if ( !delim_mode && ftell(fp)-offset >= l_max)
1289          {
1290             break;
1291          }
1292       }
1293       delete NewDocEntry;
1294    }
1295    return l; // Probably useless 
1296 }
1297
1298 /**
1299  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1300  * @return  parsed length for this level
1301  */ 
1302 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1303                            long offset, long l_max, bool delim_mode)
1304 {
1305    int SQItemNumber = 0;
1306
1307    gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1308    gdcmSQItem *itemSQ;
1309    bool dlm_mod;
1310    int lgr, lgth;
1311    unsigned int l;
1312    int depth = set->GetDepthLevel();
1313    (void)depth; //not used
1314
1315    while (true) {
1316
1317       NewDocEntry = ReadNextDocEntry();   
1318       if (!NewDocEntry)
1319          break;
1320       if(delim_mode) {   
1321          if (NewDocEntry->isSequenceDelimitor()) {
1322             set->SetSequenceDelimitationItem(NewDocEntry);
1323             break;
1324           }
1325       }
1326       if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1327           break;
1328       }
1329
1330       itemSQ = new gdcmSQItem(set->GetDepthLevel());
1331       itemSQ->AddEntry(NewDocEntry);
1332       l= NewDocEntry->GetReadLength();
1333       
1334       if (l == 0xffffffff)
1335          dlm_mod = true;
1336       else
1337          dlm_mod=false;
1338    
1339       lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1340       
1341       set->AddEntry(itemSQ,SQItemNumber); 
1342       SQItemNumber ++;
1343       if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1344          break;
1345       }
1346    }
1347    lgth = ftell(fp) - offset;
1348    return lgth;
1349 }
1350
1351 /**
1352  * \brief         Loads the element content if its length doesn't exceed
1353  *                the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1354  * @param         Entry Header Entry (Dicom Element) to be dealt with
1355  */
1356 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1357 {
1358    size_t item_read;
1359    guint16 group  = Entry->GetGroup();
1360    std::string  vr= Entry->GetVR();
1361    guint32 length = Entry->GetLength();
1362
1363    fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1364
1365    // A SeQuence "contains" a set of Elements.  
1366    //          (fffe e000) tells us an Element is beginning
1367    //          (fffe e00d) tells us an Element just ended
1368    //          (fffe e0dd) tells us the current SeQuence just ended
1369    if( group == 0xfffe ) {
1370       // NO more value field for SQ !
1371       return;
1372    }
1373
1374    // When the length is zero things are easy:
1375    if ( length == 0 ) {
1376       ((gdcmValEntry *)Entry)->SetValue("");
1377       return;
1378    }
1379
1380    // The elements whose length is bigger than the specified upper bound
1381    // are not loaded. Instead we leave a short notice of the offset of
1382    // the element content and it's length.
1383
1384    std::ostringstream s;
1385    if (length > MaxSizeLoadEntry) {
1386       if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1387       {         
1388          s << "gdcm::NotLoaded (BinEntry)";
1389          s << " Address:" << (long)Entry->GetOffset();
1390          s << " Length:"  << Entry->GetLength();
1391          s << " x(" << std::hex << Entry->GetLength() << ")";
1392          BinEntryPtr->SetValue(s.str());
1393       }
1394       // to be sure we are at the end of the value ...
1395       fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);      
1396       return;
1397        // Be carefull : a BinEntry IS_A ValEntry ... 
1398       if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1399       {
1400          s << "gdcm::NotLoaded. (ValEntry)";
1401          s << " Address:" << (long)Entry->GetOffset();
1402          s << " Length:"  << Entry->GetLength();
1403          s << " x(" << std::hex << Entry->GetLength() << ")";
1404          ValEntryPtr->SetValue(s.str());
1405       }
1406       // to be sure we are at the end of the value ...
1407       fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);      
1408       return;
1409    }
1410
1411    // When we find a BinEntry not very much can be done :
1412    if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) ) {
1413
1414       LoadEntryVoidArea(BinEntryPtr);
1415       s << "gdcm::Loaded (BinEntry)";
1416       BinEntryPtr->SetValue(s.str());
1417       return;
1418    }
1419  
1420     
1421    // Any compacter code suggested (?)
1422    if ( IsDocEntryAnInteger(Entry) ) {   
1423       guint32 NewInt;
1424       std::ostringstream s;
1425       int nbInt;
1426    // When short integer(s) are expected, read and convert the following 
1427    // n *two characters properly i.e. as short integers as opposed to strings.
1428    // Elements with Value Multiplicity > 1
1429    // contain a set of integers (not a single one)       
1430       if (vr == "US" || vr == "SS") {
1431          nbInt = length / 2;
1432          NewInt = ReadInt16();
1433          s << NewInt;
1434          if (nbInt > 1){
1435             for (int i=1; i < nbInt; i++) {
1436                s << '\\';
1437                NewInt = ReadInt16();
1438                s << NewInt;
1439             }
1440          }
1441       }
1442    // When integer(s) are expected, read and convert the following 
1443    // n * four characters properly i.e. as integers as opposed to strings.
1444    // Elements with Value Multiplicity > 1
1445    // contain a set of integers (not a single one)           
1446       else if (vr == "UL" || vr == "SL") {
1447          nbInt = length / 4;
1448          NewInt = ReadInt32();
1449          s << NewInt;
1450          if (nbInt > 1) {
1451             for (int i=1; i < nbInt; i++) {
1452                s << '\\';
1453                NewInt = ReadInt32();
1454                s << NewInt;
1455             }
1456          }
1457       }
1458 #ifdef GDCM_NO_ANSI_STRING_STREAM
1459       s << std::ends; // to avoid oddities on Solaris
1460 #endif //GDCM_NO_ANSI_STRING_STREAM
1461
1462       ((gdcmValEntry *)Entry)->SetValue(s.str());
1463       return;
1464    }
1465    
1466    // We need an additional byte for storing \0 that is not on disk
1467    std::string NewValue(length,0);
1468    item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1469    if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) ) {  
1470       if ( item_read != 1 ) {
1471          dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1472          ValEntry->SetValue("gdcm::UnRead");
1473          return;
1474       }
1475
1476       if( (vr == "UI") ) // Because of correspondance with the VR dic
1477          ValEntry->SetValue(NewValue.c_str());
1478       else
1479          ValEntry->SetValue(NewValue);
1480    } else {
1481    // fusible
1482       std::cout << "Should have a ValEntry, here !" << std::endl;
1483    }
1484
1485 }
1486
1487
1488 /**
1489  * \brief  Find the value Length of the passed Header Entry
1490  * @param  Entry Header Entry whose length of the value shall be loaded. 
1491  */
1492  void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1493    guint16 element = Entry->GetElement();
1494    //guint16 group   = Entry->GetGroup(); //FIXME
1495    std::string  vr = Entry->GetVR();
1496    guint16 length16;
1497        
1498    
1499    if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) ) 
1500    {
1501       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) 
1502       {
1503          // The following reserved two bytes (see PS 3.5-2001, section
1504          // 7.1.2 Data element structure with explicit vr p27) must be
1505          // skipped before proceeding on reading the length on 4 bytes.
1506          fseek(fp, 2L, SEEK_CUR);
1507          guint32 length32 = ReadInt32();
1508
1509          if ( (vr == "OB") && (length32 == 0xffffffff) ) 
1510          {
1511             Entry->SetLength(FindDocEntryLengthOB());
1512             return;
1513          }
1514          FixDocEntryFoundLength(Entry, length32); 
1515          return;
1516       }
1517
1518       // Length is encoded on 2 bytes.
1519       length16 = ReadInt16();
1520       
1521       // We can tell the current file is encoded in big endian (like
1522       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1523       // and it's value is the one of the encoding of a big endian file.
1524       // In order to deal with such big endian encoded files, we have
1525       // (at least) two strategies:
1526       // * when we load the "Transfer Syntax" tag with value of big endian
1527       //   encoding, we raise the proper flags. Then we wait for the end
1528       //   of the META group (0x0002) among which is "Transfer Syntax",
1529       //   before switching the swap code to big endian. We have to postpone
1530       //   the switching of the swap code since the META group is fully encoded
1531       //   in little endian, and big endian coding only starts at the next
1532       //   group. The corresponding code can be hard to analyse and adds
1533       //   many additional unnecessary tests for regular tags.
1534       // * the second strategy consists in waiting for trouble, that shall
1535       //   appear when we find the first group with big endian encoding. This
1536       //   is easy to detect since the length of a "Group Length" tag (the
1537       //   ones with zero as element number) has to be of 4 (0x0004). When we
1538       //   encounter 1024 (0x0400) chances are the encoding changed and we
1539       //   found a group with big endian encoding.
1540       // We shall use this second strategy. In order to make sure that we
1541       // can interpret the presence of an apparently big endian encoded
1542       // length of a "Group Length" without committing a big mistake, we
1543       // add an additional check: we look in the already parsed elements
1544       // for the presence of a "Transfer Syntax" whose value has to be "big
1545       // endian encoding". When this is the case, chances are we have got our
1546       // hands on a big endian encoded file: we switch the swap code to
1547       // big endian and proceed...
1548       if ( (element  == 0x0000) && (length16 == 0x0400) ) 
1549       {
1550          if ( ! IsExplicitVRBigEndianTransferSyntax() ) 
1551          {
1552             dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1553             errno = 1;
1554             return;
1555          }
1556          length16 = 4;
1557          SwitchSwapToBigEndian();
1558          // Restore the unproperly loaded values i.e. the group, the element
1559          // and the dictionary entry depending on them.
1560          guint16 CorrectGroup   = SwapShort(Entry->GetGroup());
1561          guint16 CorrectElem    = SwapShort(Entry->GetElement());
1562          gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1563                                                        CorrectElem);
1564          if (!NewTag) 
1565          {
1566             // This correct tag is not in the dictionary. Create a new one.
1567             NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1568          }
1569          // FIXME this can create a memory leaks on the old entry that be
1570          // left unreferenced.
1571          Entry->SetDictEntry(NewTag);
1572       }
1573        
1574       // Heuristic: well, some files are really ill-formed.
1575       if ( length16 == 0xffff) 
1576       {
1577          length16 = 0;
1578          // Length16= 0xffff means that we deal with
1579          // 'Unknown Length' Sequence  
1580       }
1581       FixDocEntryFoundLength(Entry, (guint32)length16);
1582       return;
1583    }
1584    else
1585    {
1586       // Either implicit VR or a non DICOM conformal (see note below) explicit
1587       // VR that ommited the VR of (at least) this element. Farts happen.
1588       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1589       // on Data elements "Implicit and Explicit VR Data Elements shall
1590       // not coexist in a Data Set and Data Sets nested within it".]
1591       // Length is on 4 bytes.
1592       
1593       FixDocEntryFoundLength(Entry, ReadInt32());
1594       return;
1595    }
1596 }
1597
1598 /**
1599  * \brief     Find the Value Representation of the current Dicom Element.
1600  * @param     Entry
1601  */
1602 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry) 
1603 {
1604    if (Filetype != gdcmExplicitVR)
1605       return;
1606
1607    char VR[3];
1608
1609    long PositionOnEntry = ftell(fp);
1610    // Warning: we believe this is explicit VR (Value Representation) because
1611    // we used a heuristic that found "UL" in the first tag. Alas this
1612    // doesn't guarantee that all the tags will be in explicit VR. In some
1613    // cases (see e-film filtered files) one finds implicit VR tags mixed
1614    // within an explicit VR file. Hence we make sure the present tag
1615    // is in explicit VR and try to fix things if it happens not to be
1616    // the case.
1617    
1618    (void)fread (&VR, (size_t)2,(size_t)1, fp);
1619    VR[2]=0;
1620    if(!CheckDocEntryVR(Entry,VR))
1621    {
1622       fseek(fp, PositionOnEntry, SEEK_SET);
1623       // When this element is known in the dictionary we shall use, e.g. for
1624       // the semantics (see the usage of IsAnInteger), the VR proposed by the
1625       // dictionary entry. Still we have to flag the element as implicit since
1626       // we know now our assumption on expliciteness is not furfilled.
1627       // avoid  .
1628       if ( Entry->IsVRUnknown() )
1629          Entry->SetVR("Implicit");
1630       Entry->SetImplicitVR();
1631    }
1632 }
1633
1634 /**
1635  * \brief     Check the correspondance between the VR of the header entry
1636  *            and the taken VR. If they are different, the header entry is 
1637  *            updated with the new VR.
1638  * @param     Entry Header Entry to check
1639  * @param     vr    Dicom Value Representation
1640  * @return    false if the VR is incorrect of if the VR isn't referenced
1641  *            otherwise, it returns true
1642 */
1643 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1644 {
1645    char msg[100]; // for sprintf
1646    bool RealExplicit = true;
1647
1648    // Assume we are reading a falsely explicit VR file i.e. we reached
1649    // a tag where we expect reading a VR but are in fact we read the
1650    // first to bytes of the length. Then we will interogate (through find)
1651    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1652    // both GCC and VC++ implementations of the STL map. Hence when the
1653    // expected VR read happens to be non-ascii characters we consider
1654    // we hit falsely explicit VR tag.
1655
1656    if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1657       RealExplicit = false;
1658
1659    // CLEANME searching the dicom_vr at each occurence is expensive.
1660    // PostPone this test in an optional integrity check at the end
1661    // of parsing or only in debug mode.
1662    if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1663       RealExplicit= false;
1664
1665    if ( !RealExplicit ) 
1666    {
1667       // We thought this was explicit VR, but we end up with an
1668       // implicit VR tag. Let's backtrack.   
1669       sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", 
1670                    Entry->GetGroup(),Entry->GetElement());
1671       dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1672       if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1673          gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1674                                    Entry->GetGroup(),Entry->GetElement(),
1675                                    "UL","FIXME","Group Length");
1676          Entry->SetDictEntry(NewEntry);     
1677       }
1678       return false;
1679    }
1680
1681    if ( Entry->IsVRUnknown() ) 
1682    {
1683       // When not a dictionary entry, we can safely overwrite the VR.
1684       if (Entry->GetElement() == 0x0000) { // Group length is UL !
1685          Entry->SetVR("UL");
1686       } else {
1687          Entry->SetVR(vr);
1688       }
1689    }
1690    else if ( Entry->GetVR() != vr ) 
1691    {
1692       // The VR present in the file and the dictionary disagree. We assume
1693       // the file writer knew best and use the VR of the file. Since it would
1694       // be unwise to overwrite the VR of a dictionary (since it would
1695       // compromise it's next user), we need to clone the actual DictEntry
1696       // and change the VR for the read one.
1697       gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1698                                  Entry->GetGroup(),Entry->GetElement(),
1699                                  vr,"FIXME",Entry->GetName());
1700       Entry->SetDictEntry(NewEntry);
1701    }
1702    return true; 
1703 }
1704
1705 /**
1706  * \brief   Get the transformed value of the header entry. The VR value 
1707  *          is used to define the transformation to operate on the value
1708  * \warning NOT end user intended method !
1709  * @param   Entry 
1710  * @return  Transformed entry value
1711  */
1712 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1713 {
1714    if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1715    {
1716       std::string val=((gdcmValEntry *)Entry)->GetValue();
1717       std::string vr=Entry->GetVR();
1718       guint32 length = Entry->GetLength();
1719       std::ostringstream s;
1720       int nbInt;
1721
1722    // When short integer(s) are expected, read and convert the following 
1723    // n * 2 bytes properly i.e. as a multivaluated strings
1724    // (each single value is separated fromthe next one by '\'
1725    // as usual for standard multivaluated filels
1726    // Elements with Value Multiplicity > 1
1727    // contain a set of short integers (not a single one) 
1728    
1729       if (vr == "US" || vr == "SS")
1730       {
1731          guint16 NewInt16;
1732
1733          nbInt = length / 2;
1734          for (int i=0; i < nbInt; i++) 
1735          {
1736             if(i!=0)
1737                s << '\\';
1738             NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1739             NewInt16 = SwapShort(NewInt16);
1740             s << NewInt16;
1741          }
1742       }
1743
1744    // When integer(s) are expected, read and convert the following 
1745    // n * 4 bytes properly i.e. as a multivaluated strings
1746    // (each single value is separated fromthe next one by '\'
1747    // as usual for standard multivaluated filels
1748    // Elements with Value Multiplicity > 1
1749    // contain a set of integers (not a single one) 
1750       else if (vr == "UL" || vr == "SL")
1751       {
1752          guint32 NewInt32;
1753
1754          nbInt = length / 4;
1755          for (int i=0; i < nbInt; i++) 
1756          {
1757             if(i!=0)
1758                s << '\\';
1759             NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1760                      ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1761             NewInt32=SwapLong(NewInt32);
1762             s << NewInt32;
1763          }
1764       }
1765 #ifdef GDCM_NO_ANSI_STRING_STREAM
1766       s << std::ends; // to avoid oddities on Solaris
1767 #endif //GDCM_NO_ANSI_STRING_STREAM
1768       return s.str();
1769    }
1770
1771    return ((gdcmValEntry *)Entry)->GetValue();
1772 }
1773
1774 /**
1775  * \brief   Get the reverse transformed value of the header entry. The VR 
1776  *          value is used to define the reverse transformation to operate on
1777  *          the value
1778  * \warning NOT end user intended method !
1779  * @param   Entry 
1780  * @return  Reverse transformed entry value
1781  */
1782 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1783 {
1784    if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1785    {
1786       std::string vr=Entry->GetVR();
1787       std::ostringstream s;
1788       std::vector<std::string> tokens;
1789
1790       if (vr == "US" || vr == "SS") 
1791       {
1792          guint16 NewInt16;
1793
1794          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1795          Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1796          for (unsigned int i=0; i<tokens.size();i++) 
1797          {
1798             NewInt16 = atoi(tokens[i].c_str());
1799             s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1800          }
1801          tokens.clear();
1802       }
1803       if (vr == "UL" || vr == "SL") 
1804       {
1805          guint32 NewInt32;
1806
1807          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1808          Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1809          for (unsigned int i=0; i<tokens.size();i++) 
1810          {
1811             NewInt32 = atoi(tokens[i].c_str());
1812             s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1813                <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1814          }
1815          tokens.clear();
1816       }
1817
1818 #ifdef GDCM_NO_ANSI_STRING_STREAM
1819       s << std::ends; // to avoid oddities on Solaris
1820 #endif //GDCM_NO_ANSI_STRING_STREAM
1821       return s.str();
1822    }
1823
1824    return ((gdcmValEntry *)Entry)->GetValue();
1825 }
1826
1827 /**
1828  * \brief   Skip a given Header Entry 
1829  * \warning NOT end user intended method !
1830  * @param   entry 
1831  */
1832 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry) 
1833 {
1834    SkipBytes(entry->GetLength());
1835 }
1836
1837 /**
1838  * \brief   Skips to the begining of the next Header Entry 
1839  * \warning NOT end user intended method !
1840  * @param   entry 
1841  */
1842 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry) 
1843 {
1844    (void)fseek(fp, (long)(entry->GetOffset()),     SEEK_SET);
1845    (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1846 }
1847
1848 /**
1849  * \brief   When the length of an element value is obviously wrong (because
1850  *          the parser went Jabberwocky) one can hope improving things by
1851  *          applying some heuristics.
1852  */
1853 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1854                                           guint32 FoundLength)
1855 {
1856    Entry->SetReadLength(FoundLength); // will be updated only if a bug is found        
1857    if ( FoundLength == 0xffffffff) {
1858       FoundLength = 0;
1859    }
1860    
1861    guint16 gr =Entry->GetGroup();
1862    guint16 el =Entry->GetElement(); 
1863      
1864    if (FoundLength%2) {
1865       std::ostringstream s;
1866       s << "Warning : Tag with uneven length "
1867         << FoundLength 
1868         <<  " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1869       dbg.Verbose(0, s.str().c_str());
1870    }
1871       
1872    //////// Fix for some naughty General Electric images.
1873    // Allthough not recent many such GE corrupted images are still present
1874    // on Creatis hard disks. Hence this fix shall remain when such images
1875    // are no longer in user (we are talking a few years, here)...
1876    // Note: XMedCom probably uses such a trick since it is able to read
1877    //       those pesky GE images ...
1878    if (FoundLength == 13) {  // Only happens for this length !
1879       if (   (Entry->GetGroup() != 0x0008)
1880           || (   (Entry->GetElement() != 0x0070)
1881               && (Entry->GetElement() != 0x0080) ) )
1882       {
1883          FoundLength = 10;
1884          Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1885       }
1886    }
1887
1888    //////// Fix for some brain-dead 'Leonardo' Siemens images.
1889    // Occurence of such images is quite low (unless one leaves close to a
1890    // 'Leonardo' source. Hence, one might consider commenting out the
1891    // following fix on efficiency reasons.
1892    else
1893    if (   (Entry->GetGroup() == 0x0009)
1894        && (   (Entry->GetElement() == 0x1113)
1895            || (Entry->GetElement() == 0x1114) ) )
1896    {
1897       FoundLength = 4;
1898       Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1899    } 
1900  
1901    //////// Deal with sequences, but only on users request:
1902    else
1903    if ( ( Entry->GetVR() == "SQ") && enableSequences)
1904    {
1905          FoundLength = 0;      // ReadLength is unchanged 
1906    } 
1907     
1908    //////// We encountered a 'delimiter' element i.e. a tag of the form 
1909    // "fffe|xxxx" which is just a marker. Delimiters length should not be
1910    // taken into account.
1911    else
1912    if(Entry->GetGroup() == 0xfffe)
1913    {    
1914      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1915      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1916      // causes extra troubles...
1917      if( Entry->GetElement() != 0x0000 )
1918      {
1919         FoundLength = 0;
1920      }
1921    } 
1922            
1923    Entry->SetUsableLength(FoundLength);
1924 }
1925
1926 /**
1927  * \brief   Apply some heuristics to predict whether the considered 
1928  *          element value contains/represents an integer or not.
1929  * @param   Entry The element value on which to apply the predicate.
1930  * @return  The result of the heuristical predicate.
1931  */
1932 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1933    guint16 element = Entry->GetElement();
1934    guint16 group   = Entry->GetGroup();
1935    std::string  vr = Entry->GetVR();
1936    guint32 length  = Entry->GetLength();
1937
1938    // When we have some semantics on the element we just read, and if we
1939    // a priori know we are dealing with an integer, then we shall be
1940    // able to swap it's element value properly.
1941    if ( element == 0 )  // This is the group length of the group
1942    {  
1943       if (length == 4)
1944          return true;
1945       else 
1946       {
1947          // Allthough this should never happen, still some images have a
1948          // corrupted group length [e.g. have a glance at offset x(8336) of
1949          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1950          // Since for dicom compliant and well behaved headers, the present
1951          // test is useless (and might even look a bit paranoid), when we
1952          // encounter such an ill-formed image, we simply display a warning
1953          // message and proceed on parsing (while crossing fingers).
1954          std::ostringstream s;
1955          int filePosition = ftell(fp);
1956          s << "Erroneous Group Length element length  on : (" \
1957            << std::hex << group << " , " << element 
1958            << ") -before- position x(" << filePosition << ")"
1959            << "lgt : " << length;
1960          dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
1961       }
1962    }
1963
1964    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1965       return true;
1966    
1967    return false;
1968 }
1969
1970 /**
1971  * \brief  Find the Length till the next sequence delimiter
1972  * \warning NOT end user intended method !
1973  * @return 
1974  */
1975
1976  guint32 gdcmDocument::FindDocEntryLengthOB(void)  {
1977    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1978    guint16 g;
1979    guint16 n; 
1980    long PositionOnEntry = ftell(fp);
1981    bool FoundSequenceDelimiter = false;
1982    guint32 TotalLength = 0;
1983    guint32 ItemLength;
1984
1985    while ( ! FoundSequenceDelimiter) 
1986    {
1987       g = ReadInt16();
1988       n = ReadInt16();   
1989       if (errno == 1)
1990          return 0;
1991       TotalLength += 4;  // We even have to decount the group and element 
1992      
1993       if ( g != 0xfffe && g!=0xb00c ) //for bogus header  
1994       {
1995          char msg[100]; // for sprintf. Sorry
1996          sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1997          dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg); 
1998          errno = 1;
1999          return 0;
2000       }
2001       if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header 
2002          FoundSequenceDelimiter = true;
2003       else if ( n != 0xe000 )
2004       {
2005          char msg[100];  // for sprintf. Sorry
2006          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2007                       n, g,n);
2008          dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2009          errno = 1;
2010          return 0;
2011       }
2012       ItemLength = ReadInt32();
2013       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
2014                                       // the ItemLength with ReadInt32                                     
2015       SkipBytes(ItemLength);
2016    }
2017    fseek(fp, PositionOnEntry, SEEK_SET);
2018    return TotalLength;
2019 }
2020
2021 /**
2022  * \brief Reads a supposed to be 16 Bits integer
2023  *       (swaps it depending on processor endianity) 
2024  * @return read value
2025  */
2026 guint16 gdcmDocument::ReadInt16() {
2027    guint16 g;
2028    size_t item_read;
2029    item_read = fread (&g, (size_t)2,(size_t)1, fp);
2030    if ( item_read != 1 ) {
2031       if(ferror(fp)) 
2032          dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2033       errno = 1;
2034       return 0;
2035    }
2036    errno = 0;
2037    g = SwapShort(g);   
2038    return g;
2039 }
2040
2041 /**
2042  * \brief  Reads a supposed to be 32 Bits integer
2043  *         (swaps it depending on processor endianity)  
2044  * @return read value
2045  */
2046 guint32 gdcmDocument::ReadInt32() {
2047    guint32 g;
2048    size_t item_read;
2049    item_read = fread (&g, (size_t)4,(size_t)1, fp);
2050    if ( item_read != 1 ) { 
2051      if(ferror(fp)) 
2052          dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");   
2053       errno = 1;
2054       return 0;
2055    }
2056    errno = 0;   
2057    g = SwapLong(g);
2058    return g;
2059 }
2060
2061 /**
2062  * \brief skips bytes inside the source file 
2063  * \warning NOT end user intended method !
2064  * @return 
2065  */
2066 void gdcmDocument::SkipBytes(guint32 NBytes) {
2067    //FIXME don't dump the returned value
2068    (void)fseek(fp, (long)NBytes, SEEK_CUR);
2069 }
2070
2071 /**
2072  * \brief Loads all the needed Dictionaries
2073  * \warning NOT end user intended method !   
2074  */
2075 void gdcmDocument::Initialise(void) 
2076 {
2077    RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2078    RefShaDict = NULL;
2079 }
2080
2081 /**
2082  * \brief   Discover what the swap code is (among little endian, big endian,
2083  *          bad little endian, bad big endian).
2084  *          sw is set
2085  * @return false when we are absolutely sure 
2086  *               it's neither ACR-NEMA nor DICOM
2087  *         true  when we hope ours assuptions are OK
2088  */
2089 bool gdcmDocument::CheckSwap() {
2090
2091    // The only guaranted way of finding the swap code is to find a
2092    // group tag since we know it's length has to be of four bytes i.e.
2093    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2094    // occurs when we can't find such group...
2095    
2096    guint32  x=4;  // x : for ntohs
2097    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2098    guint32  s32;
2099    guint16  s16;
2100        
2101    int lgrLue;
2102    char *entCur;
2103    char deb[HEADER_LENGTH_TO_READ];
2104     
2105    // First, compare HostByteOrder and NetworkByteOrder in order to
2106    // determine if we shall need to swap bytes (i.e. the Endian type).
2107    if (x==ntohs(x))
2108       net2host = true;
2109    else
2110       net2host = false; 
2111          
2112    // The easiest case is the one of a DICOM header, since it possesses a
2113    // file preamble where it suffice to look for the string "DICM".
2114    lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2115    
2116    entCur = deb + 128;
2117    if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2118       dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2119       
2120       // Next, determine the value representation (VR). Let's skip to the
2121       // first element (0002, 0000) and check there if we find "UL" 
2122       // - or "OB" if the 1st one is (0002,0001) -,
2123       // in which case we (almost) know it is explicit VR.
2124       // WARNING: if it happens to be implicit VR then what we will read
2125       // is the length of the group. If this ascii representation of this
2126       // length happens to be "UL" then we shall believe it is explicit VR.
2127       // FIXME: in order to fix the above warning, we could read the next
2128       // element value (or a couple of elements values) in order to make
2129       // sure we are not commiting a big mistake.
2130       // We need to skip :
2131       // * the 128 bytes of File Preamble (often padded with zeroes),
2132       // * the 4 bytes of "DICM" string,
2133       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2134       // i.e. a total of  136 bytes.
2135       entCur = deb + 136;
2136      
2137       // FIXME : FIXME:
2138       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2139       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2140       // *Implicit* VR.  -and it is !- 
2141       
2142       if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2143           (memcmp(entCur, "OB", (size_t)2) == 0) ||
2144           (memcmp(entCur, "UI", (size_t)2) == 0) ||
2145           (memcmp(entCur, "CS", (size_t)2) == 0) )  // CS, to remove later
2146                                                     // when Write DCM *adds*
2147       // FIXME
2148       // Use gdcmDocument::dicom_vr to test all the possibilities
2149       // instead of just checking for UL, OB and UI !? group 0000 
2150       {
2151          Filetype = gdcmExplicitVR;
2152          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2153                      "explicit Value Representation");
2154       } 
2155       else 
2156       {
2157          Filetype = gdcmImplicitVR;
2158          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2159                      "not an explicit Value Representation");
2160       }
2161       
2162       if (net2host) 
2163       {
2164          sw = 4321;
2165          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2166                         "HostByteOrder != NetworkByteOrder");
2167       } 
2168       else 
2169       {
2170          sw = 0;
2171          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2172                         "HostByteOrder = NetworkByteOrder");
2173       }
2174       
2175       // Position the file position indicator at first tag (i.e.
2176       // after the file preamble and the "DICM" string).
2177       rewind(fp);
2178       fseek (fp, 132L, SEEK_SET);
2179       return true;
2180    } // End of DicomV3
2181
2182    // Alas, this is not a DicomV3 file and whatever happens there is no file
2183    // preamble. We can reset the file position indicator to where the data
2184    // is (i.e. the beginning of the file).
2185    dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2186    rewind(fp);
2187
2188    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2189    // By clean we mean that the length of the first tag is written down.
2190    // If this is the case and since the length of the first group HAS to be
2191    // four (bytes), then determining the proper swap code is straightforward.
2192
2193    entCur = deb + 4;
2194    // We assume the array of char we are considering contains the binary
2195    // representation of a 32 bits integer. Hence the following dirty
2196    // trick :
2197    s32 = *((guint32 *)(entCur));
2198       
2199    switch (s32) {
2200       case 0x00040000 :
2201          sw = 3412;
2202          Filetype = gdcmACR;
2203          return true;
2204       case 0x04000000 :
2205          sw = 4321;
2206          Filetype = gdcmACR;
2207          return true;
2208       case 0x00000400 :
2209          sw = 2143;
2210          Filetype = gdcmACR;
2211          return true;
2212       case 0x00000004 :
2213          sw = 0;
2214          Filetype = gdcmACR;
2215          return true;
2216       default :
2217
2218       // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2219       // It is time for despaired wild guesses. 
2220       // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2221       //  i.e. the 'group length' element is not present :     
2222       
2223       //  check the supposed to be 'group number'
2224       //  0x0002 or 0x0004 or 0x0008
2225       //  to determine ' sw' value .
2226       //  Only 0 or 4321 will be possible 
2227       //  (no oportunity to check for the formerly well known
2228       //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2229       //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-) 
2230       //  the file IS NOT ACR-NEMA nor DICOM V3
2231       //  Find a trick to tell it the caller...
2232       
2233       s16 = *((guint16 *)(deb));
2234       
2235       switch (s16) {
2236       case 0x0002 :
2237       case 0x0004 :
2238       case 0x0008 :      
2239          sw = 0;
2240          Filetype = gdcmACR;
2241          return true;
2242       case 0x0200 :
2243       case 0x0400 :
2244       case 0x0800 : 
2245          sw = 4321;
2246          Filetype = gdcmACR;
2247          return true;
2248       default :
2249          dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2250                      "ACR/NEMA unfound swap info (Really hopeless !)"); 
2251          Filetype = gdcmUnknown;     
2252          return false;
2253       }
2254       
2255       // Then the only info we have is the net2host one.
2256       //if (! net2host )
2257          //   sw = 0;
2258          //else
2259          //  sw = 4321;
2260          //return;
2261    }
2262 }
2263
2264 /**
2265  * \brief Restore the unproperly loaded values i.e. the group, the element
2266  *        and the dictionary entry depending on them. 
2267  */
2268 void gdcmDocument::SwitchSwapToBigEndian(void) 
2269 {
2270    dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2271                   "Switching to BigEndian mode.");
2272    if ( sw == 0    ) 
2273    {
2274       sw = 4321;
2275       return;
2276    }
2277    if ( sw == 4321 ) 
2278    {
2279       sw = 0;
2280       return;
2281    }
2282    if ( sw == 3412 ) 
2283    {
2284       sw = 2143;
2285       return;
2286    }
2287    if ( sw == 2143 )
2288       sw = 3412;
2289 }
2290
2291 /**
2292  * \brief  during parsing, Header Elements too long are not loaded in memory 
2293  * @param NewSize
2294  */
2295 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize) 
2296 {
2297    if (NewSize < 0)
2298       return;
2299    if ((guint32)NewSize >= (guint32)0xffffffff) 
2300    {
2301       MaxSizeLoadEntry = 0xffffffff;
2302       return;
2303    }
2304    MaxSizeLoadEntry = NewSize;
2305 }
2306
2307
2308 /**
2309  * \brief Header Elements too long will not be printed
2310  * \todo  See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE 
2311  * @param NewSize
2312  */
2313 void gdcmDocument::SetMaxSizePrintEntry(long NewSize) 
2314 {
2315    if (NewSize < 0)
2316       return;
2317    if ((guint32)NewSize >= (guint32)0xffffffff) 
2318    {
2319       MaxSizePrintEntry = 0xffffffff;
2320       return;
2321    }
2322    MaxSizePrintEntry = NewSize;
2323 }
2324
2325
2326
2327 /**
2328  * \brief   Read the next tag but WITHOUT loading it's value
2329  *          (read the 'Group Number', the 'Element Number',
2330  *           gets the Dict Entry
2331  *          gets the VR, gets the length, gets the offset value)
2332  * @return  On succes the newly created DocEntry, NULL on failure.      
2333  */
2334 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2335    guint16 g,n;
2336    gdcmDocEntry *NewEntry;
2337    g = ReadInt16();
2338    n = ReadInt16();
2339       
2340    if (errno == 1)
2341       // We reached the EOF (or an error occured) therefore 
2342       // header parsing has to be considered as finished.
2343       return (gdcmDocEntry *)0;
2344
2345    NewEntry = NewDocEntryByNumber(g, n);
2346    FindDocEntryVR(NewEntry);
2347    FindDocEntryLength(NewEntry);
2348
2349    if (errno == 1) {
2350       // Call it quits
2351       delete NewEntry;
2352       return NULL;
2353    }
2354    NewEntry->SetOffset(ftell(fp));  
2355    return NewEntry;
2356 }
2357
2358
2359 /**
2360  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2361  *          in the TagHt dictionary.
2362  * @param   group The generated tag must belong to this group.  
2363  * @return  The element of tag with given group which is fee.
2364  */
2365 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group) 
2366 {
2367    for (guint32 elem = 0; elem < UINT32_MAX; elem++) 
2368    {
2369       TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2370       if (tagHT.count(key) == 0)
2371          return elem;
2372    }
2373    return UINT32_MAX;
2374 }
2375
2376
2377 /**
2378  * \brief   Assuming the internal file pointer \ref gdcmDocument::fp 
2379  *          is placed at the beginning of a tag (TestGroup, TestElement),
2380  *          read the length associated to the Tag.
2381  * \warning On success the internal file pointer \ref gdcmDocument::fp
2382  *          is modified to point after the tag and it's length.
2383  *          On failure (i.e. when the tag wasn't the expected tag
2384  *          (TestGroup, TestElement) the internal file pointer
2385  *          \ref gdcmDocument::fp is restored to it's original position.
2386  * @param   TestGroup   The expected group of the tag.
2387  * @param   TestElement The expected Element of the tag.
2388  * @return  On success returns the length associated to the tag. On failure
2389  *          returns 0.
2390  */
2391 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2392 {
2393    guint16 ItemTagGroup;
2394    guint16 ItemTagElement; 
2395    long PositionOnEntry = ftell(fp);
2396    long CurrentPosition = ftell(fp);          // On debugging purposes
2397
2398    //// Read the Item Tag group and element, and make
2399    // sure they are respectively 0xfffe and 0xe000:
2400    ItemTagGroup   = ReadInt16();
2401    ItemTagElement = ReadInt16();
2402    if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2403    {
2404       std::ostringstream s;
2405       s << "   We should have found tag (";
2406       s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2407       s << "   but instead we encountered tag (";
2408       s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2409         << std::endl;
2410       s << "  at address: " << (unsigned)CurrentPosition << std::endl;
2411       dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2412       dbg.Verbose(0, s.str().c_str());
2413       fseek(fp, PositionOnEntry, SEEK_SET);
2414       return 0;
2415    }
2416                                                                                 
2417    //// Then read the associated Item Length
2418    CurrentPosition=ftell(fp);
2419    guint32 ItemLength;
2420    ItemLength = ReadInt32();
2421    {
2422       std::ostringstream s;
2423       s << "Basic Item Length is: "
2424         << ItemLength << std::endl;
2425       s << "  at address: " << (unsigned)CurrentPosition << std::endl;
2426       dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2427    }
2428    return ItemLength;
2429 }
2430
2431 /**
2432  * \brief   Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2433  * \sa      \ref gdcmDocument::ReadTagLength
2434  * \warning See warning of \ref gdcmDocument::ReadTagLength
2435  * @return  On success returns the length associated to the item tag.
2436  *          On failure returns 0.
2437  */ 
2438 guint32 gdcmDocument::ReadItemTagLength(void)
2439 {
2440    return ReadTagLength(0xfffe, 0xe000);
2441 }
2442
2443 /**
2444  * \brief   Read the length of an expected Sequence Delimiter tag i.e.
2445  *          (0xfffe, 0xe0dd).
2446  * \sa      \ref gdcmDocument::ReadTagLength
2447  * \warning See warning of \ref gdcmDocument::ReadTagLength
2448  * @return  On success returns the length associated to the Sequence
2449  *          Delimiter tag. On failure returns 0.
2450  */
2451 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2452 {
2453    return ReadTagLength(0xfffe, 0xe0dd);
2454 }
2455
2456
2457 /**
2458  * \brief   Parse pixel data from disk for multi-fragment Jpeg/Rle files
2459  *          No other way so 'skip' the Data
2460  *
2461  */
2462
2463 void gdcmDocument::Parse7FE0 (void)
2464 {
2465    gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2466    if ( !Element )
2467       return;
2468       
2469    if (   IsImplicitVRLittleEndianTransferSyntax()
2470        || IsExplicitVRLittleEndianTransferSyntax()
2471        || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2472        || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2473       return;
2474       
2475    // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels 
2476
2477    //// Read the Basic Offset Table Item Tag length...
2478    guint32 ItemLength = ReadItemTagLength();
2479
2480    //// ... and then read length[s] itself[themselves]. We don't use
2481    // the values read (BTW  what is the purpous of those lengths ?)
2482    if (ItemLength != 0) {
2483       // BTW, what is the purpous of those length anyhow !? 
2484       char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2485       fread(BasicOffsetTableItemValue, ItemLength, 1, fp); 
2486       for (unsigned int i=0; i < ItemLength; i += 4){
2487          guint32 IndividualLength;
2488          IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2489          std::ostringstream s;
2490          s << "   Read one length: ";
2491          s << std::hex << IndividualLength << std::endl;
2492          dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2493       }              
2494    }
2495
2496    if ( ! IsRLELossLessTransferSyntax() )
2497    {
2498       // JPEG Image
2499       
2500       //// We then skip (not reading them) all the fragments of images:
2501       while ( (ItemLength = ReadItemTagLength()) )
2502       {
2503          SkipBytes(ItemLength);
2504       } 
2505
2506    }
2507    else
2508    {
2509       // RLE Image
2510       long ftellRes;
2511       long RleSegmentLength[15], fragmentLength;
2512
2513       // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2514       while ( (fragmentLength = ReadSequenceDelimiterTagLength()) )
2515       { 
2516          // Parse fragments of the current Fragment (Frame)    
2517          //------------------ scanning (not reading) fragment pixels
2518          guint32 nbRleSegments = ReadInt32();
2519          printf("   Nb of RLE Segments : %d\n",nbRleSegments);
2520  
2521          //// Reading RLE Segments Offset Table
2522          guint32 RleSegmentOffsetTable[15];
2523          for(int k=1; k<=15; k++) {
2524             ftellRes=ftell(fp);
2525             RleSegmentOffsetTable[k] = ReadInt32();
2526             printf("        at : %x Offset Segment %d : %d (%x)\n",
2527                     (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2528                     RleSegmentOffsetTable[k]);
2529          }
2530
2531          // skipping (not reading) RLE Segments
2532          if (nbRleSegments>1) {
2533             for(unsigned int k=1; k<=nbRleSegments-1; k++) { 
2534                 RleSegmentLength[k]=   RleSegmentOffsetTable[k+1]
2535                                      - RleSegmentOffsetTable[k];
2536                 ftellRes=ftell(fp);
2537                 printf ("  Segment %d : Length = %d x(%x) Start at %x\n",
2538                         k,(unsigned)RleSegmentLength[k],
2539                        (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2540                 SkipBytes(RleSegmentLength[k]);    
2541              }
2542           }
2543
2544           RleSegmentLength[nbRleSegments]= fragmentLength 
2545                                          - RleSegmentOffsetTable[nbRleSegments];
2546           ftellRes=ftell(fp);
2547           printf ("  Segment %d : Length = %d x(%x) Start at %x\n",
2548                   nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2549                   (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2550           SkipBytes(RleSegmentLength[nbRleSegments]); 
2551       } 
2552    }
2553 }
2554
2555
2556
2557 /**
2558  * \brief   Compares two documents, according to \ref gdcmDicomDir rules
2559  * \warning Does NOT work with ACR-NEMA files
2560  * \todo    Find a trick to solve the pb (use RET fields ?)
2561  * @param   document
2562  * @return  true if 'smaller'
2563  */
2564 bool gdcmDocument::operator<(gdcmDocument &document)
2565 {
2566    std::string s1,s2;
2567                                                                                 
2568    // Patient Name
2569    s1=this->GetEntryByNumber(0x0010,0x0010);
2570    s2=document.GetEntryByNumber(0x0010,0x0010);
2571    if(s1 < s2)
2572       return true;
2573    else if(s1 > s2)
2574       return false;
2575    else
2576    {
2577       // Patient ID
2578       s1=this->GetEntryByNumber(0x0010,0x0020);
2579       s2=document.GetEntryByNumber(0x0010,0x0020);
2580       if (s1 < s2)
2581          return true;
2582       else if (s1 > s2)
2583          return true;
2584       else
2585       {
2586          // Study Instance UID
2587          s1=this->GetEntryByNumber(0x0020,0x000d);
2588          s2=document.GetEntryByNumber(0x0020,0x000d);
2589          if (s1 < s2)
2590             return true;
2591          else if(s1 > s2)
2592             return false;
2593          else
2594          {
2595             // Serie Instance UID
2596             s1=this->GetEntryByNumber(0x0020,0x000e);
2597             s2=document.GetEntryByNumber(0x0020,0x000e);
2598             if (s1 < s2)
2599                return true;
2600             else if(s1 > s2)
2601                return false;
2602          }
2603       }
2604    }
2605    return false;
2606 }
2607
2608
2609 //-----------------------------------------------------------------------------