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