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