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