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