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