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