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