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