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