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