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