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