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