]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
* Amelioration of code, remove some code copy. For the loading of
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/11/24 11:17:47 $
7   Version:   $Revision: 1.136 $
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    BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
1069    if( !binElement )
1070       return;
1071
1072    LoadEntryBinArea(binElement);
1073 /*   size_t o =(size_t)docElement->GetOffset();
1074    Fp->seekg( o, std::ios_base::beg);
1075    size_t l = docElement->GetLength();
1076    uint8_t* a = new uint8_t[l];
1077    if(!a)
1078    {
1079       dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1080       return;
1081    }
1082
1083    // Read the value
1084    Fp->read((char*)a, l);
1085    if( Fp->fail() || Fp->eof() )//Fp->gcount() == 1
1086    {
1087       delete[] a;
1088       return;
1089    }
1090
1091    // Set the value to the DocEntry
1092    if( !SetEntryBinAreaByNumber( a, group, elem ) )
1093    {
1094       delete[] a;
1095       dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1096    }*/
1097 }
1098
1099 /**
1100  * \brief         Loads (from disk) the element content 
1101  *                when a string is not suitable
1102  * @param element  Entry whose binArea is going to be loaded
1103  */
1104 void Document::LoadEntryBinArea(BinEntry* element) 
1105 {
1106    bool openFile = !Fp;
1107    if(openFile)
1108       OpenFile();
1109
1110    size_t o =(size_t)element->GetOffset();
1111    Fp->seekg(o, std::ios_base::beg);
1112
1113    size_t l = element->GetLength();
1114    uint8_t* a = new uint8_t[l];
1115    if( !a )
1116    {
1117       dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1118       return;
1119    }
1120
1121    /// \todo check the result 
1122    Fp->read((char*)a, l);
1123    if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1124    {
1125       delete[] a;
1126       return;
1127    }
1128
1129    element->SetBinArea(a);
1130
1131    if(openFile)
1132       CloseFile();
1133 }
1134
1135 /**
1136  * \brief   Sets a 'non string' value to a given Dicom Element
1137  * @param   area area containing the 'non string' value
1138  * @param   group     Group number of the searched Dicom Element 
1139  * @param   element Element number of the searched Dicom Element 
1140  * @return  
1141  */
1142 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1143                                        uint16_t group, uint16_t element) 
1144 {
1145    DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1146    if ( !currentEntry )
1147    {
1148       return false;
1149    }
1150
1151    if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1152    {
1153       binEntry->SetBinArea( area );
1154       return true;
1155    }
1156
1157    return false;
1158 }
1159
1160 /**
1161  * \brief   Update the entries with the shadow dictionary. 
1162  *          Only non even entries are analyzed       
1163  */
1164 void Document::UpdateShaEntries()
1165 {
1166    //DictEntry *entry;
1167    std::string vr;
1168    
1169    /// \todo TODO : still any use to explore recursively the whole structure?
1170 /*
1171    for(ListTag::iterator it=listEntries.begin();
1172        it!=listEntries.end();
1173        ++it)
1174    {
1175       // Odd group => from public dictionary
1176       if((*it)->GetGroup()%2==0)
1177          continue;
1178
1179       // Peer group => search the corresponding dict entry
1180       if(RefShaDict)
1181          entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1182       else
1183          entry=NULL;
1184
1185       if((*it)->IsImplicitVR())
1186          vr="Implicit";
1187       else
1188          vr=(*it)->GetVR();
1189
1190       (*it)->SetValue(GetDocEntryUnvalue(*it));  // to go on compiling
1191       if(entry){
1192          // Set the new entry and the new value
1193          (*it)->SetDictEntry(entry);
1194          CheckDocEntryVR(*it,vr);
1195
1196          (*it)->SetValue(GetDocEntryValue(*it));    // to go on compiling
1197  
1198       }
1199       else
1200       {
1201          // Remove precedent value transformation
1202          (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1203       }
1204    }
1205 */   
1206 }
1207
1208 /**
1209  * \brief   Searches within the Header Entries for a Dicom Element of
1210  *          a given tag.
1211  * @param   tagName name of the searched Dicom Element.
1212  * @return  Corresponding Dicom Element when it exists, and NULL
1213  *          otherwise.
1214  */
1215 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1216 {
1217    DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
1218    if( !dictEntry )
1219    {
1220       return NULL;
1221    }
1222
1223   return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1224 }
1225
1226 /**
1227  * \brief  retrieves a Dicom Element (the first one) using (group, element)
1228  * \warning (group, element) IS NOT an identifier inside the Dicom Header
1229  *           if you think it's NOT UNIQUE, check the count number
1230  *           and use iterators to retrieve ALL the Dicoms Elements within
1231  *           a given couple (group, element)
1232  * @param   group Group number of the searched Dicom Element 
1233  * @param   element Element number of the searched Dicom Element 
1234  * @return  
1235  */
1236 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element) 
1237 {
1238    TagKey key = DictEntry::TranslateToKey(group, element);
1239    if ( !TagHT.count(key))
1240    {
1241       return NULL;
1242    }
1243    return TagHT.find(key)->second;
1244 }
1245
1246 /**
1247  * \brief  Same as \ref Document::GetDocEntryByNumber except it only
1248  *         returns a result when the corresponding entry is of type
1249  *         ValEntry.
1250  * @return When present, the corresponding ValEntry. 
1251  */
1252 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1253 {
1254    DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1255    if ( !currentEntry )
1256    {
1257       return 0;
1258    }
1259    if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1260    {
1261       return valEntry;
1262    }
1263    dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1264
1265    return 0;
1266 }
1267
1268 /**
1269  * \brief         Loads the element while preserving the current
1270  *                underlying file position indicator as opposed to
1271  *                to LoadDocEntry that modifies it.
1272  * @param entry   Header Entry whose value shall be loaded. 
1273  * @return  
1274  */
1275 void Document::LoadDocEntrySafe(DocEntry * entry)
1276 {
1277    long PositionOnEntry = Fp->tellg();
1278    LoadDocEntry(entry);
1279    Fp->seekg(PositionOnEntry, std::ios_base::beg);
1280 }
1281
1282 /**
1283  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1284  *          processor order.
1285  * @return  The properly swaped 32 bits integer.
1286  */
1287 uint32_t Document::SwapLong(uint32_t a)
1288 {
1289    switch (SwapCode)
1290    {
1291       case    0 :
1292          break;
1293       case 4321 :
1294          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
1295              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1296          break;
1297    
1298       case 3412 :
1299          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1300          break;
1301    
1302       case 2143 :
1303          a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1304          break;
1305       default :
1306          //std::cout << "swapCode= " << SwapCode << std::endl;
1307          dbg.Error(" Document::SwapLong : unset swap code");
1308          a = 0;
1309    }
1310    return a;
1311
1312
1313 /**
1314  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
1315  *          processor order.
1316  * @return  The properly unswaped 32 bits integer.
1317  */
1318 uint32_t Document::UnswapLong(uint32_t a)
1319 {
1320    return SwapLong(a);
1321 }
1322
1323 /**
1324  * \brief   Swaps the bytes so they agree with the processor order
1325  * @return  The properly swaped 16 bits integer.
1326  */
1327 uint16_t Document::SwapShort(uint16_t a)
1328 {
1329    if ( SwapCode == 4321 || SwapCode == 2143 )
1330    {
1331       a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1332    }
1333    return a;
1334 }
1335
1336 /**
1337  * \brief   Unswaps the bytes so they agree with the processor order
1338  * @return  The properly unswaped 16 bits integer.
1339  */
1340 uint16_t Document::UnswapShort(uint16_t a)
1341 {
1342    return SwapShort(a);
1343 }
1344
1345 //-----------------------------------------------------------------------------
1346 // Private
1347
1348 /**
1349  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1350  * @return  length of the parsed set. 
1351  */ 
1352 void Document::ParseDES(DocEntrySet *set, long offset, 
1353                         long l_max, bool delim_mode)
1354 {
1355    DocEntry *newDocEntry = 0;
1356
1357    while (true)
1358    {
1359       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1360       {
1361          break;
1362       }
1363       newDocEntry = ReadNextDocEntry( );
1364       if ( !newDocEntry )
1365       {
1366          break;
1367       }
1368
1369       VRKey vr = newDocEntry->GetVR();
1370       if ( vr != "SQ" )
1371       {
1372                
1373          if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1374          {
1375          /////////////////////// ValEntry
1376             ValEntry* newValEntry =
1377                new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1378             newValEntry->Copy( newDocEntry );
1379              
1380             // When "set" is a Document, then we are at the top of the
1381             // hierarchy and the Key is simply of the form ( group, elem )...
1382             if (Document* dummy = dynamic_cast< Document* > ( set ) )
1383             {
1384                (void)dummy;
1385                newValEntry->SetKey( newValEntry->GetKey() );
1386             }
1387             // ...but when "set" is a SQItem, we are inserting this new
1388             // valEntry in a sequence item. Hence the key has the
1389             // generalized form (refer to \ref BaseTagKey):
1390             if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1391             {
1392                newValEntry->SetKey(  parentSQItem->GetBaseTagKey()
1393                                    + newValEntry->GetKey() );
1394             }
1395              
1396             LoadDocEntry( newValEntry );
1397             bool delimitor=newValEntry->IsItemDelimitor();
1398             if( !set->AddEntry( newValEntry ) )
1399             {
1400               // If here expect big troubles
1401               delete newValEntry; //otherwise mem leak
1402             }
1403
1404             if (delimitor)
1405             {
1406                delete newDocEntry;
1407                break;
1408             }
1409             if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1410             {
1411                delete newDocEntry;
1412                break;
1413             }
1414          }
1415          else
1416          {
1417             if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1418             { 
1419                 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1420                 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1421                                "nor BinEntry. Probably unknown VR.");
1422             }
1423
1424          //////////////////// BinEntry or UNKOWN VR:
1425 /*            BinEntry* newBinEntry =
1426                new BinEntry( newDocEntry->GetDictEntry() );  //LEAK
1427             newBinEntry->Copy( newDocEntry );*/
1428             BinEntry* newBinEntry = new BinEntry( newDocEntry );  //LEAK
1429
1430             // When "this" is a Document the Key is simply of the
1431             // form ( group, elem )...
1432             if (Document* dummy = dynamic_cast< Document* > ( set ) )
1433             {
1434                (void)dummy;
1435                newBinEntry->SetKey( newBinEntry->GetKey() );
1436             }
1437             // but when "this" is a SQItem, we are inserting this new
1438             // valEntry in a sequence item, and the kay has the
1439             // generalized form (refer to \ref BaseTagKey):
1440             if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1441             {
1442                newBinEntry->SetKey(  parentSQItem->GetBaseTagKey()
1443                                    + newBinEntry->GetKey() );
1444             }
1445
1446             LoadDocEntry( newBinEntry );
1447             if( !set->AddEntry( newBinEntry ) )
1448             {
1449               //Expect big troubles if here
1450               delete newBinEntry;
1451             }
1452          }
1453
1454          if (    ( newDocEntry->GetGroup()   == 0x7fe0 )
1455               && ( newDocEntry->GetElement() == 0x0010 ) )
1456          {
1457              TransferSyntaxType ts = GetTransferSyntax();
1458              if ( ts == RLELossless ) 
1459              {
1460                 long PositionOnEntry = Fp->tellg();
1461                 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1462                 ComputeRLEInfo();
1463                 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1464              }
1465              else if ( IsJPEG() )
1466              {
1467                 long PositionOnEntry = Fp->tellg();
1468                 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1469                 ComputeJPEGFragmentInfo();
1470                 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1471              }
1472          }
1473     
1474          // Just to make sure we are at the beginning of next entry.
1475          SkipToNextDocEntry(newDocEntry);
1476          //delete newDocEntry;
1477       }
1478       else
1479       {
1480          // VR = "SQ"
1481          unsigned long l = newDocEntry->GetReadLength();            
1482          if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1483          {
1484             if ( l == 0xffffffff )
1485             {
1486               delim_mode = true;
1487             }
1488             else
1489             {
1490               delim_mode = false;
1491             }
1492          }
1493          // no other way to create it ...
1494          SeqEntry* newSeqEntry =
1495             new SeqEntry( newDocEntry->GetDictEntry() );
1496          newSeqEntry->Copy( newDocEntry );
1497          newSeqEntry->SetDelimitorMode( delim_mode );
1498
1499          // At the top of the hierarchy, stands a Document. When "set"
1500          // is a Document, then we are building the first depth level.
1501          // Hence the SeqEntry we are building simply has a depth
1502          // level of one:
1503          if (Document* dummy = dynamic_cast< Document* > ( set ) )
1504          {
1505             (void)dummy;
1506             newSeqEntry->SetDepthLevel( 1 );
1507             newSeqEntry->SetKey( newSeqEntry->GetKey() );
1508          }
1509          // But when "set" is allready a SQItem, we are building a nested
1510          // sequence, and hence the depth level of the new SeqEntry
1511          // we are building, is one level deeper:
1512          if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1513          {
1514             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1515             newSeqEntry->SetKey(  parentSQItem->GetBaseTagKey()
1516                                 + newSeqEntry->GetKey() );
1517          }
1518
1519          if ( l != 0 )
1520          {  // Don't try to parse zero-length sequences
1521             ParseSQ( newSeqEntry, 
1522                      newDocEntry->GetOffset(),
1523                      l, delim_mode);
1524          }
1525          set->AddEntry( newSeqEntry );
1526          if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1527          {
1528             delete newDocEntry;
1529             break;
1530          }
1531       }
1532       delete newDocEntry;
1533    }
1534 }
1535
1536 /**
1537  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1538  * @return  parsed length for this level
1539  */ 
1540 void Document::ParseSQ( SeqEntry* seqEntry,
1541                         long offset, long l_max, bool delim_mode)
1542 {
1543    int SQItemNumber = 0;
1544    bool dlm_mod;
1545
1546    while (true)
1547    {
1548       DocEntry* newDocEntry = ReadNextDocEntry();   
1549       if ( !newDocEntry )
1550       {
1551          // FIXME Should warn user
1552          break;
1553       }
1554       if( delim_mode )
1555       {
1556          if ( newDocEntry->IsSequenceDelimitor() )
1557          {
1558             seqEntry->SetSequenceDelimitationItem( newDocEntry ); 
1559             break;
1560          }
1561       }
1562       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1563       {
1564          delete newDocEntry;
1565          break;
1566       }
1567
1568       SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1569       std::ostringstream newBase;
1570       newBase << seqEntry->GetKey()
1571               << "/"
1572               << SQItemNumber
1573               << "#";
1574       itemSQ->SetBaseTagKey( newBase.str() );
1575       unsigned int l = newDocEntry->GetReadLength();
1576       
1577       if ( l == 0xffffffff )
1578       {
1579          dlm_mod = true;
1580       }
1581       else
1582       {
1583          dlm_mod = false;
1584       }
1585    
1586       ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1587       delete newDocEntry;
1588       
1589       seqEntry->AddEntry( itemSQ, SQItemNumber ); 
1590       SQItemNumber++;
1591       if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1592       {
1593          break;
1594       }
1595    }
1596 }
1597
1598 /**
1599  * \brief         Loads the element content if its length doesn't exceed
1600  *                the value specified with Document::SetMaxSizeLoadEntry()
1601  * @param         entry Header Entry (Dicom Element) to be dealt with
1602  */
1603 void Document::LoadDocEntry(DocEntry* entry)
1604 {
1605    uint16_t group  = entry->GetGroup();
1606    std::string  vr = entry->GetVR();
1607    uint32_t length = entry->GetLength();
1608
1609    Fp->seekg((long)entry->GetOffset(), std::ios_base::beg);
1610
1611    // A SeQuence "contains" a set of Elements.  
1612    //          (fffe e000) tells us an Element is beginning
1613    //          (fffe e00d) tells us an Element just ended
1614    //          (fffe e0dd) tells us the current SeQuence just ended
1615    if( group == 0xfffe )
1616    {
1617       // NO more value field for SQ !
1618       return;
1619    }
1620
1621    // When the length is zero things are easy:
1622    if ( length == 0 )
1623    {
1624       ((ValEntry *)entry)->SetValue("");
1625       return;
1626    }
1627
1628    // The elements whose length is bigger than the specified upper bound
1629    // are not loaded. Instead we leave a short notice of the offset of
1630    // the element content and it's length.
1631
1632    std::ostringstream s;
1633    if (length > MaxSizeLoadEntry)
1634    {
1635       if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1636       {  
1637          //s << "gdcm::NotLoaded (BinEntry)";
1638          s << GDCM_NOTLOADED;
1639          s << " Address:" << (long)entry->GetOffset();
1640          s << " Length:"  << entry->GetLength();
1641          s << " x(" << std::hex << entry->GetLength() << ")";
1642          binEntryPtr->SetValue(s.str());
1643       }
1644       // Be carefull : a BinEntry IS_A ValEntry ... 
1645       else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1646       {
1647         // s << "gdcm::NotLoaded. (ValEntry)";
1648          s << GDCM_NOTLOADED;  
1649          s << " Address:" << (long)entry->GetOffset();
1650          s << " Length:"  << entry->GetLength();
1651          s << " x(" << std::hex << entry->GetLength() << ")";
1652          valEntryPtr->SetValue(s.str());
1653       }
1654       else
1655       {
1656          // fusible
1657          std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1658                   << "nor a ValEntry ?! Should never print that !" << std::endl;
1659       }
1660
1661       // to be sure we are at the end of the value ...
1662       Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1663                 std::ios_base::beg);
1664       return;
1665    }
1666
1667    // When we find a BinEntry not very much can be done :
1668    if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1669    {
1670       s << GDCM_BINLOADED;
1671       binEntryPtr->SetValue(s.str());
1672       LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1673       return;
1674    }
1675     
1676    /// \todo Any compacter code suggested (?)
1677    if ( IsDocEntryAnInteger(entry) )
1678    {   
1679       uint32_t NewInt;
1680       int nbInt;
1681       // When short integer(s) are expected, read and convert the following 
1682       // n *two characters properly i.e. consider them as short integers as
1683       // opposed to strings.
1684       // Elements with Value Multiplicity > 1
1685       // contain a set of integers (not a single one)       
1686       if (vr == "US" || vr == "SS")
1687       {
1688          nbInt = length / 2;
1689          NewInt = ReadInt16();
1690          s << NewInt;
1691          if (nbInt > 1)
1692          {
1693             for (int i=1; i < nbInt; i++)
1694             {
1695                s << '\\';
1696                NewInt = ReadInt16();
1697                s << NewInt;
1698             }
1699          }
1700       }
1701       // See above comment on multiple integers (mutatis mutandis).
1702       else if (vr == "UL" || vr == "SL")
1703       {
1704          nbInt = length / 4;
1705          NewInt = ReadInt32();
1706          s << NewInt;
1707          if (nbInt > 1)
1708          {
1709             for (int i=1; i < nbInt; i++)
1710             {
1711                s << '\\';
1712                NewInt = ReadInt32();
1713                s << NewInt;
1714             }
1715          }
1716       }
1717 #ifdef GDCM_NO_ANSI_STRING_STREAM
1718       s << std::ends; // to avoid oddities on Solaris
1719 #endif //GDCM_NO_ANSI_STRING_STREAM
1720
1721       ((ValEntry *)entry)->SetValue(s.str());
1722       return;
1723    }
1724    
1725   // FIXME: We need an additional byte for storing \0 that is not on disk
1726    char *str = new char[length+1];
1727    Fp->read(str, (size_t)length);
1728    str[length] = '\0'; //this is only useful when length is odd
1729    // Special DicomString call to properly handle \0 and even length
1730    std::string newValue;
1731    if( length % 2 )
1732    {
1733       newValue = Util::DicomString(str, length+1);
1734       //dbg.Verbose(0, "Warning: bad length: ", length );
1735       dbg.Verbose(0, "For string :",  newValue.c_str()); 
1736       // Since we change the length of string update it length
1737       entry->SetReadLength(length+1);
1738    }
1739    else
1740    {
1741       newValue = Util::DicomString(str, length);
1742    }
1743    delete[] str;
1744
1745    if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1746    {
1747       if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1748       {
1749          dbg.Verbose(1, "Document::LoadDocEntry",
1750                         "unread element value");
1751          valEntry->SetValue(GDCM_UNREAD);
1752          return;
1753       }
1754
1755       if( vr == "UI" )
1756       {
1757          // Because of correspondance with the VR dic
1758          valEntry->SetValue(newValue);
1759       }
1760       else
1761       {
1762          valEntry->SetValue(newValue);
1763       }
1764    }
1765    else
1766    {
1767       dbg.Error(true, "Document::LoadDocEntry"
1768                       "Should have a ValEntry, here !");
1769    }
1770 }
1771
1772
1773 /**
1774  * \brief  Find the value Length of the passed Header Entry
1775  * @param  entry Header Entry whose length of the value shall be loaded. 
1776  */
1777 void Document::FindDocEntryLength( DocEntry *entry )
1778    throw ( FormatError )
1779 {
1780    uint16_t element = entry->GetElement();
1781    std::string  vr  = entry->GetVR();
1782    uint16_t length16;       
1783    
1784    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1785    {
1786       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" ) 
1787       {
1788          // The following reserved two bytes (see PS 3.5-2003, section
1789          // "7.1.2 Data element structure with explicit vr", p 27) must be
1790          // skipped before proceeding on reading the length on 4 bytes.
1791          Fp->seekg( 2L, std::ios_base::cur);
1792          uint32_t length32 = ReadInt32();
1793
1794          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1795          {
1796             uint32_t lengthOB;
1797             try 
1798             {
1799                /// \todo rename that to FindDocEntryLengthOBOrOW since
1800                ///       the above test is on both OB and OW...
1801                lengthOB = FindDocEntryLengthOB();
1802             }
1803             catch ( FormatUnexpected )
1804             {
1805                // Computing the length failed (this happens with broken
1806                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1807                // chance to get the pixels by deciding the element goes
1808                // until the end of the file. Hence we artificially fix the
1809                // the length and proceed.
1810                long currentPosition = Fp->tellg();
1811                Fp->seekg(0L,std::ios_base::end);
1812                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1813                Fp->seekg(currentPosition, std::ios_base::beg);
1814                entry->SetLength(lengthUntilEOF);
1815                return;
1816             }
1817             entry->SetLength(lengthOB);
1818             return;
1819          }
1820          FixDocEntryFoundLength(entry, length32); 
1821          return;
1822       }
1823
1824       // Length is encoded on 2 bytes.
1825       length16 = ReadInt16();
1826       
1827       // We can tell the current file is encoded in big endian (like
1828       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1829       // and it's value is the one of the encoding of a big endian file.
1830       // In order to deal with such big endian encoded files, we have
1831       // (at least) two strategies:
1832       // * when we load the "Transfer Syntax" tag with value of big endian
1833       //   encoding, we raise the proper flags. Then we wait for the end
1834       //   of the META group (0x0002) among which is "Transfer Syntax",
1835       //   before switching the swap code to big endian. We have to postpone
1836       //   the switching of the swap code since the META group is fully encoded
1837       //   in little endian, and big endian coding only starts at the next
1838       //   group. The corresponding code can be hard to analyse and adds
1839       //   many additional unnecessary tests for regular tags.
1840       // * the second strategy consists in waiting for trouble, that shall
1841       //   appear when we find the first group with big endian encoding. This
1842       //   is easy to detect since the length of a "Group Length" tag (the
1843       //   ones with zero as element number) has to be of 4 (0x0004). When we
1844       //   encounter 1024 (0x0400) chances are the encoding changed and we
1845       //   found a group with big endian encoding.
1846       // We shall use this second strategy. In order to make sure that we
1847       // can interpret the presence of an apparently big endian encoded
1848       // length of a "Group Length" without committing a big mistake, we
1849       // add an additional check: we look in the already parsed elements
1850       // for the presence of a "Transfer Syntax" whose value has to be "big
1851       // endian encoding". When this is the case, chances are we have got our
1852       // hands on a big endian encoded file: we switch the swap code to
1853       // big endian and proceed...
1854       if ( element  == 0x0000 && length16 == 0x0400 ) 
1855       {
1856          TransferSyntaxType ts = GetTransferSyntax();
1857          if ( ts != ExplicitVRBigEndian ) 
1858          {
1859             throw FormatError( "Document::FindDocEntryLength()",
1860                                " not explicit VR." );
1861             return;
1862          }
1863          length16 = 4;
1864          SwitchSwapToBigEndian();
1865          // Restore the unproperly loaded values i.e. the group, the element
1866          // and the dictionary entry depending on them.
1867          uint16_t correctGroup = SwapShort( entry->GetGroup() );
1868          uint16_t correctElem  = SwapShort( entry->GetElement() );
1869          DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1870                                                        correctElem );
1871          if ( !newTag )
1872          {
1873             // This correct tag is not in the dictionary. Create a new one.
1874             newTag = NewVirtualDictEntry(correctGroup, correctElem);
1875          }
1876          // FIXME this can create a memory leaks on the old entry that be
1877          // left unreferenced.
1878          entry->SetDictEntry( newTag );
1879       }
1880        
1881       // Heuristic: well, some files are really ill-formed.
1882       if ( length16 == 0xffff) 
1883       {
1884          // 0xffff means that we deal with 'Unknown Length' Sequence  
1885          length16 = 0;
1886       }
1887       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1888       return;
1889    }
1890    else
1891    {
1892       // Either implicit VR or a non DICOM conformal (see note below) explicit
1893       // VR that ommited the VR of (at least) this element. Farts happen.
1894       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1895       // on Data elements "Implicit and Explicit VR Data Elements shall
1896       // not coexist in a Data Set and Data Sets nested within it".]
1897       // Length is on 4 bytes.
1898       
1899       FixDocEntryFoundLength( entry, ReadInt32() );
1900       return;
1901    }
1902 }
1903
1904 /**
1905  * \brief     Find the Value Representation of the current Dicom Element.
1906  * @param     entry
1907  */
1908 void Document::FindDocEntryVR( DocEntry *entry )
1909 {
1910    if ( Filetype != ExplicitVR )
1911    {
1912       return;
1913    }
1914
1915    char vr[3];
1916
1917    long positionOnEntry = Fp->tellg();
1918    // Warning: we believe this is explicit VR (Value Representation) because
1919    // we used a heuristic that found "UL" in the first tag. Alas this
1920    // doesn't guarantee that all the tags will be in explicit VR. In some
1921    // cases (see e-film filtered files) one finds implicit VR tags mixed
1922    // within an explicit VR file. Hence we make sure the present tag
1923    // is in explicit VR and try to fix things if it happens not to be
1924    // the case.
1925    
1926    Fp->read (vr, (size_t)2);
1927    vr[2] = 0;
1928
1929    if( !CheckDocEntryVR(entry, vr) )
1930    {
1931       Fp->seekg(positionOnEntry, std::ios_base::beg);
1932       // When this element is known in the dictionary we shall use, e.g. for
1933       // the semantics (see the usage of IsAnInteger), the VR proposed by the
1934       // dictionary entry. Still we have to flag the element as implicit since
1935       // we know now our assumption on expliciteness is not furfilled.
1936       // avoid  .
1937       if ( entry->IsVRUnknown() )
1938       {
1939          entry->SetVR("Implicit");
1940       }
1941       entry->SetImplicitVR();
1942    }
1943 }
1944
1945 /**
1946  * \brief     Check the correspondance between the VR of the header entry
1947  *            and the taken VR. If they are different, the header entry is 
1948  *            updated with the new VR.
1949  * @param     entry Header Entry to check
1950  * @param     vr    Dicom Value Representation
1951  * @return    false if the VR is incorrect of if the VR isn't referenced
1952  *            otherwise, it returns true
1953 */
1954 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1955 {
1956    std::string msg;
1957    bool realExplicit = true;
1958
1959    // Assume we are reading a falsely explicit VR file i.e. we reached
1960    // a tag where we expect reading a VR but are in fact we read the
1961    // first to bytes of the length. Then we will interogate (through find)
1962    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1963    // both GCC and VC++ implementations of the STL map. Hence when the
1964    // expected VR read happens to be non-ascii characters we consider
1965    // we hit falsely explicit VR tag.
1966
1967    if ( !isalpha((unsigned char)vr[0]) && !isalpha((unsigned char)vr[1]) )
1968    {
1969       realExplicit = false;
1970    }
1971
1972    // CLEANME searching the dicom_vr at each occurence is expensive.
1973    // PostPone this test in an optional integrity check at the end
1974    // of parsing or only in debug mode.
1975    if ( realExplicit && !Global::GetVR()->Count(vr) )
1976    {
1977       realExplicit = false;
1978    }
1979
1980    if ( !realExplicit ) 
1981    {
1982       // We thought this was explicit VR, but we end up with an
1983       // implicit VR tag. Let's backtrack.   
1984       msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n", 
1985                     entry->GetGroup(), entry->GetElement());
1986       dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
1987
1988       if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1989       {
1990          // Group length is UL !
1991          DictEntry* newEntry = NewVirtualDictEntry(
1992                                    entry->GetGroup(), entry->GetElement(),
1993                                    "UL", "FIXME", "Group Length");
1994          entry->SetDictEntry( newEntry );
1995       }
1996       return false;
1997    }
1998
1999    if ( entry->IsVRUnknown() )
2000    {
2001       // When not a dictionary entry, we can safely overwrite the VR.
2002       if( entry->GetElement() == 0x0000 )
2003       {
2004          // Group length is UL !
2005          entry->SetVR("UL");
2006       }
2007       else
2008       {
2009          entry->SetVR(vr);
2010       }
2011    }
2012    else if ( entry->GetVR() != vr ) 
2013    {
2014       // The VR present in the file and the dictionary disagree. We assume
2015       // the file writer knew best and use the VR of the file. Since it would
2016       // be unwise to overwrite the VR of a dictionary (since it would
2017       // compromise it's next user), we need to clone the actual DictEntry
2018       // and change the VR for the read one.
2019       DictEntry* newEntry = NewVirtualDictEntry(
2020                                 entry->GetGroup(), entry->GetElement(),
2021                                 vr, "FIXME", entry->GetName());
2022       entry->SetDictEntry(newEntry);
2023    }
2024
2025    return true; 
2026 }
2027
2028 /**
2029  * \brief   Get the transformed value of the header entry. The VR value 
2030  *          is used to define the transformation to operate on the value
2031  * \warning NOT end user intended method !
2032  * @param   entry entry to tranform
2033  * @return  Transformed entry value
2034  */
2035 std::string Document::GetDocEntryValue(DocEntry *entry)
2036 {
2037    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2038    {
2039       std::string val = ((ValEntry *)entry)->GetValue();
2040       std::string vr  = entry->GetVR();
2041       uint32_t length = entry->GetLength();
2042       std::ostringstream s;
2043       int nbInt;
2044
2045       // When short integer(s) are expected, read and convert the following 
2046       // n * 2 bytes properly i.e. as a multivaluated strings
2047       // (each single value is separated fromthe next one by '\'
2048       // as usual for standard multivaluated filels
2049       // Elements with Value Multiplicity > 1
2050       // contain a set of short integers (not a single one) 
2051    
2052       if( vr == "US" || vr == "SS" )
2053       {
2054          uint16_t newInt16;
2055
2056          nbInt = length / 2;
2057          for (int i=0; i < nbInt; i++) 
2058          {
2059             if( i != 0 )
2060             {
2061                s << '\\';
2062             }
2063             newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2064             newInt16 = SwapShort( newInt16 );
2065             s << newInt16;
2066          }
2067       }
2068
2069       // When integer(s) are expected, read and convert the following 
2070       // n * 4 bytes properly i.e. as a multivaluated strings
2071       // (each single value is separated fromthe next one by '\'
2072       // as usual for standard multivaluated filels
2073       // Elements with Value Multiplicity > 1
2074       // contain a set of integers (not a single one) 
2075       else if( vr == "UL" || vr == "SL" )
2076       {
2077          uint32_t newInt32;
2078
2079          nbInt = length / 4;
2080          for (int i=0; i < nbInt; i++) 
2081          {
2082             if( i != 0)
2083             {
2084                s << '\\';
2085             }
2086             newInt32 = ( val[4*i+0] & 0xFF )
2087                     + (( val[4*i+1] & 0xFF ) <<  8 )
2088                     + (( val[4*i+2] & 0xFF ) << 16 )
2089                     + (( val[4*i+3] & 0xFF ) << 24 );
2090             newInt32 = SwapLong( newInt32 );
2091             s << newInt32;
2092          }
2093       }
2094 #ifdef GDCM_NO_ANSI_STRING_STREAM
2095       s << std::ends; // to avoid oddities on Solaris
2096 #endif //GDCM_NO_ANSI_STRING_STREAM
2097       return s.str();
2098    }
2099
2100    return ((ValEntry *)entry)->GetValue();
2101 }
2102
2103 /**
2104  * \brief   Get the reverse transformed value of the header entry. The VR 
2105  *          value is used to define the reverse transformation to operate on
2106  *          the value
2107  * \warning NOT end user intended method !
2108  * @param   entry Entry to reverse transform
2109  * @return  Reverse transformed entry value
2110  */
2111 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2112 {
2113    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2114    {
2115       std::string vr = entry->GetVR();
2116       std::vector<std::string> tokens;
2117       std::ostringstream s;
2118
2119       if ( vr == "US" || vr == "SS" ) 
2120       {
2121          uint16_t newInt16;
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             newInt16 = atoi(tokens[i].c_str());
2128             s << (  newInt16        & 0xFF ) 
2129               << (( newInt16 >> 8 ) & 0xFF );
2130          }
2131          tokens.clear();
2132       }
2133       if ( vr == "UL" || vr == "SL")
2134       {
2135          uint32_t newInt32;
2136
2137          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2138          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2139          for (unsigned int i=0; i<tokens.size();i++) 
2140          {
2141             newInt32 = atoi(tokens[i].c_str());
2142             s << (char)(  newInt32         & 0xFF ) 
2143               << (char)(( newInt32 >>  8 ) & 0xFF )
2144               << (char)(( newInt32 >> 16 ) & 0xFF )
2145               << (char)(( newInt32 >> 24 ) & 0xFF );
2146          }
2147          tokens.clear();
2148       }
2149
2150 #ifdef GDCM_NO_ANSI_STRING_STREAM
2151       s << std::ends; // to avoid oddities on Solaris
2152 #endif //GDCM_NO_ANSI_STRING_STREAM
2153       return s.str();
2154    }
2155
2156    return ((ValEntry *)entry)->GetValue();
2157 }
2158
2159 /**
2160  * \brief   Skip a given Header Entry 
2161  * \warning NOT end user intended method !
2162  * @param   entry entry to skip
2163  */
2164 void Document::SkipDocEntry(DocEntry *entry) 
2165 {
2166    SkipBytes(entry->GetLength());
2167 }
2168
2169 /**
2170  * \brief   Skips to the begining of the next Header Entry 
2171  * \warning NOT end user intended method !
2172  * @param   entry entry to skip
2173  */
2174 void Document::SkipToNextDocEntry(DocEntry *entry) 
2175 {
2176    Fp->seekg((long)(entry->GetOffset()),     std::ios_base::beg);
2177    Fp->seekg( (long)(entry->GetReadLength()), std::ios_base::cur);
2178 }
2179
2180 /**
2181  * \brief   When the length of an element value is obviously wrong (because
2182  *          the parser went Jabberwocky) one can hope improving things by
2183  *          applying some heuristics.
2184  * @param   entry entry to check
2185  * @param   foundLength fist assumption about length    
2186  */
2187 void Document::FixDocEntryFoundLength(DocEntry *entry,
2188                                       uint32_t foundLength)
2189 {
2190    entry->SetReadLength( foundLength ); // will be updated only if a bug is found        
2191    if ( foundLength == 0xffffffff)
2192    {
2193       foundLength = 0;
2194    }
2195    
2196    uint16_t gr = entry->GetGroup();
2197    uint16_t el = entry->GetElement(); 
2198      
2199    if ( foundLength % 2)
2200    {
2201       std::ostringstream s;
2202       s << "Warning : Tag with uneven length "
2203         << foundLength 
2204         <<  " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2205       dbg.Verbose(0, s.str().c_str());
2206    }
2207       
2208    //////// Fix for some naughty General Electric images.
2209    // Allthough not recent many such GE corrupted images are still present
2210    // on Creatis hard disks. Hence this fix shall remain when such images
2211    // are no longer in user (we are talking a few years, here)...
2212    // Note: XMedCom probably uses such a trick since it is able to read
2213    //       those pesky GE images ...
2214    if ( foundLength == 13)
2215    {
2216       // Only happens for this length !
2217       if ( entry->GetGroup()   != 0x0008
2218       || ( entry->GetElement() != 0x0070
2219         && entry->GetElement() != 0x0080 ) )
2220       {
2221          foundLength = 10;
2222          entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2223       }
2224    }
2225
2226    //////// Fix for some brain-dead 'Leonardo' Siemens images.
2227    // Occurence of such images is quite low (unless one leaves close to a
2228    // 'Leonardo' source. Hence, one might consider commenting out the
2229    // following fix on efficiency reasons.
2230    else if ( entry->GetGroup()   == 0x0009 
2231         && ( entry->GetElement() == 0x1113
2232           || entry->GetElement() == 0x1114 ) )
2233    {
2234       foundLength = 4;
2235       entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2236    } 
2237  
2238    else if ( entry->GetVR() == "SQ" )
2239    {
2240       foundLength = 0;      // ReadLength is unchanged 
2241    } 
2242     
2243    //////// We encountered a 'delimiter' element i.e. a tag of the form 
2244    // "fffe|xxxx" which is just a marker. Delimiters length should not be
2245    // taken into account.
2246    else if( entry->GetGroup() == 0xfffe )
2247    {    
2248      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2249      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2250      // causes extra troubles...
2251      if( entry->GetElement() != 0x0000 )
2252      {
2253         foundLength = 0;
2254      }
2255    } 
2256            
2257    entry->SetUsableLength(foundLength);
2258 }
2259
2260 /**
2261  * \brief   Apply some heuristics to predict whether the considered 
2262  *          element value contains/represents an integer or not.
2263  * @param   entry The element value on which to apply the predicate.
2264  * @return  The result of the heuristical predicate.
2265  */
2266 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2267 {
2268    uint16_t element = entry->GetElement();
2269    uint16_t group   = entry->GetGroup();
2270    const std::string & vr  = entry->GetVR();
2271    uint32_t length  = entry->GetLength();
2272
2273    // When we have some semantics on the element we just read, and if we
2274    // a priori know we are dealing with an integer, then we shall be
2275    // able to swap it's element value properly.
2276    if ( element == 0 )  // This is the group length of the group
2277    {  
2278       if ( length == 4 )
2279       {
2280          return true;
2281       }
2282       else 
2283       {
2284          // Allthough this should never happen, still some images have a
2285          // corrupted group length [e.g. have a glance at offset x(8336) of
2286          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2287          // Since for dicom compliant and well behaved headers, the present
2288          // test is useless (and might even look a bit paranoid), when we
2289          // encounter such an ill-formed image, we simply display a warning
2290          // message and proceed on parsing (while crossing fingers).
2291          std::ostringstream s;
2292          long filePosition = Fp->tellg();
2293          s << "Erroneous Group Length element length  on : (" \
2294            << std::hex << group << " , " << element 
2295            << ") -before- position x(" << filePosition << ")"
2296            << "lgt : " << length;
2297          dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2298       }
2299    }
2300
2301    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2302    {
2303       return true;
2304    }
2305    
2306    return false;
2307 }
2308
2309 /**
2310  * \brief  Find the Length till the next sequence delimiter
2311  * \warning NOT end user intended method !
2312  * @return 
2313  */
2314
2315 uint32_t Document::FindDocEntryLengthOB()
2316    throw( FormatUnexpected )
2317 {
2318    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2319    long positionOnEntry = Fp->tellg();
2320    bool foundSequenceDelimiter = false;
2321    uint32_t totalLength = 0;
2322
2323    while ( !foundSequenceDelimiter )
2324    {
2325       uint16_t group;
2326       uint16_t elem;
2327       try
2328       {
2329          group = ReadInt16();
2330          elem  = ReadInt16();   
2331       }
2332       catch ( FormatError )
2333       {
2334          throw FormatError("Document::FindDocEntryLengthOB()",
2335                            " group or element not present.");
2336       }
2337
2338       // We have to decount the group and element we just read
2339       totalLength += 4;
2340      
2341       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2342       {
2343          dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2344                         "tag nor a Sequence delimiter tag."); 
2345          Fp->seekg(positionOnEntry, std::ios_base::beg);
2346          throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2347                                 "Neither an Item tag nor a Sequence "
2348                                 "delimiter tag.");
2349       }
2350
2351       if ( elem == 0xe0dd )
2352       {
2353          foundSequenceDelimiter = true;
2354       }
2355
2356       uint32_t itemLength = ReadInt32();
2357       // We add 4 bytes since we just read the ItemLength with ReadInt32
2358       totalLength += itemLength + 4;
2359       SkipBytes(itemLength);
2360       
2361       if ( foundSequenceDelimiter )
2362       {
2363          break;
2364       }
2365    }
2366    Fp->seekg( positionOnEntry, std::ios_base::beg);
2367    return totalLength;
2368 }
2369
2370 /**
2371  * \brief Reads a supposed to be 16 Bits integer
2372  *       (swaps it depending on processor endianity) 
2373  * @return read value
2374  */
2375 uint16_t Document::ReadInt16()
2376    throw( FormatError )
2377 {
2378    uint16_t g;
2379    Fp->read ((char*)&g, (size_t)2);
2380    if ( Fp->fail() )
2381    {
2382       throw FormatError( "Document::ReadInt16()", " file error." );
2383    }
2384    if( Fp->eof() )
2385    {
2386       throw FormatError( "Document::ReadInt16()", "EOF." );
2387    }
2388    g = SwapShort(g); 
2389    return g;
2390 }
2391
2392 /**
2393  * \brief  Reads a supposed to be 32 Bits integer
2394  *         (swaps it depending on processor endianity)  
2395  * @return read value
2396  */
2397 uint32_t Document::ReadInt32()
2398    throw( FormatError )
2399 {
2400    uint32_t g;
2401    Fp->read ((char*)&g, (size_t)4);
2402    if ( Fp->fail() )
2403    {
2404       throw FormatError( "Document::ReadInt32()", " file error." );
2405    }
2406    if( Fp->eof() )
2407    {
2408       throw FormatError( "Document::ReadInt32()", "EOF." );
2409    }
2410    g = SwapLong(g);
2411    return g;
2412 }
2413
2414 /**
2415  * \brief skips bytes inside the source file 
2416  * \warning NOT end user intended method !
2417  * @return 
2418  */
2419 void Document::SkipBytes(uint32_t nBytes)
2420 {
2421    //FIXME don't dump the returned value
2422    Fp->seekg((long)nBytes, std::ios_base::cur);
2423 }
2424
2425 /**
2426  * \brief Loads all the needed Dictionaries
2427  * \warning NOT end user intended method !   
2428  */
2429 void Document::Initialise() 
2430 {
2431    RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2432    RefShaDict = NULL;
2433    RLEInfo  = new RLEFramesInfo;
2434    JPEGInfo = new JPEGFragmentsInfo;
2435 }
2436
2437 /**
2438  * \brief   Discover what the swap code is (among little endian, big endian,
2439  *          bad little endian, bad big endian).
2440  *          sw is set
2441  * @return false when we are absolutely sure 
2442  *               it's neither ACR-NEMA nor DICOM
2443  *         true  when we hope ours assuptions are OK
2444  */
2445 bool Document::CheckSwap()
2446 {
2447    // The only guaranted way of finding the swap code is to find a
2448    // group tag since we know it's length has to be of four bytes i.e.
2449    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2450    // occurs when we can't find such group...
2451    
2452    uint32_t  x = 4;  // x : for ntohs
2453    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2454    uint32_t  s32;
2455    uint16_t  s16;
2456        
2457    char deb[256]; //HEADER_LENGTH_TO_READ];
2458     
2459    // First, compare HostByteOrder and NetworkByteOrder in order to
2460    // determine if we shall need to swap bytes (i.e. the Endian type).
2461    if ( x == ntohs(x) )
2462    {
2463       net2host = true;
2464    }
2465    else
2466    {
2467       net2host = false;
2468    }
2469          
2470    // The easiest case is the one of a DICOM header, since it possesses a
2471    // file preamble where it suffice to look for the string "DICM".
2472    Fp->read(deb, HEADER_LENGTH_TO_READ);
2473    
2474    char *entCur = deb + 128;
2475    if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2476    {
2477       dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2478       
2479       // Next, determine the value representation (VR). Let's skip to the
2480       // first element (0002, 0000) and check there if we find "UL" 
2481       // - or "OB" if the 1st one is (0002,0001) -,
2482       // in which case we (almost) know it is explicit VR.
2483       // WARNING: if it happens to be implicit VR then what we will read
2484       // is the length of the group. If this ascii representation of this
2485       // length happens to be "UL" then we shall believe it is explicit VR.
2486       // FIXME: in order to fix the above warning, we could read the next
2487       // element value (or a couple of elements values) in order to make
2488       // sure we are not commiting a big mistake.
2489       // We need to skip :
2490       // * the 128 bytes of File Preamble (often padded with zeroes),
2491       // * the 4 bytes of "DICM" string,
2492       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2493       // i.e. a total of  136 bytes.
2494       entCur = deb + 136;
2495      
2496       // FIXME : FIXME:
2497       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2498       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2499       // *Implicit* VR.  -and it is !- 
2500       
2501       if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2502           memcmp(entCur, "OB", (size_t)2) == 0 ||
2503           memcmp(entCur, "UI", (size_t)2) == 0 ||
2504           memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
2505                                                     // when Write DCM *adds*
2506       // FIXME
2507       // Use Document::dicom_vr to test all the possibilities
2508       // instead of just checking for UL, OB and UI !? group 0000 
2509       {
2510          Filetype = ExplicitVR;
2511          dbg.Verbose(1, "Document::CheckSwap:",
2512                      "explicit Value Representation");
2513       } 
2514       else 
2515       {
2516          Filetype = ImplicitVR;
2517          dbg.Verbose(1, "Document::CheckSwap:",
2518                      "not an explicit Value Representation");
2519       }
2520       
2521       if ( net2host )
2522       {
2523          SwapCode = 4321;
2524          dbg.Verbose(1, "Document::CheckSwap:",
2525                         "HostByteOrder != NetworkByteOrder");
2526       }
2527       else 
2528       {
2529          SwapCode = 0;
2530          dbg.Verbose(1, "Document::CheckSwap:",
2531                         "HostByteOrder = NetworkByteOrder");
2532       }
2533       
2534       // Position the file position indicator at first tag (i.e.
2535       // after the file preamble and the "DICM" string).
2536       Fp->seekg(0, std::ios_base::beg);
2537       Fp->seekg ( 132L, std::ios_base::beg);
2538       return true;
2539    } // End of DicomV3
2540
2541    // Alas, this is not a DicomV3 file and whatever happens there is no file
2542    // preamble. We can reset the file position indicator to where the data
2543    // is (i.e. the beginning of the file).
2544    dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2545    Fp->seekg(0, std::ios_base::beg);
2546
2547    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2548    // By clean we mean that the length of the first tag is written down.
2549    // If this is the case and since the length of the first group HAS to be
2550    // four (bytes), then determining the proper swap code is straightforward.
2551
2552    entCur = deb + 4;
2553    // We assume the array of char we are considering contains the binary
2554    // representation of a 32 bits integer. Hence the following dirty
2555    // trick :
2556    s32 = *((uint32_t *)(entCur));
2557       
2558    switch( s32 )
2559    {
2560       case 0x00040000 :
2561          SwapCode = 3412;
2562          Filetype = ACR;
2563          return true;
2564       case 0x04000000 :
2565          SwapCode = 4321;
2566          Filetype = ACR;
2567          return true;
2568       case 0x00000400 :
2569          SwapCode = 2143;
2570          Filetype = ACR;
2571          return true;
2572       case 0x00000004 :
2573          SwapCode = 0;
2574          Filetype = ACR;
2575          return true;
2576       default :
2577          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2578          // It is time for despaired wild guesses. 
2579          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2580          //  i.e. the 'group length' element is not present :     
2581          
2582          //  check the supposed-to-be 'group number'
2583          //  in ( 0x0001 .. 0x0008 )
2584          //  to determine ' SwapCode' value .
2585          //  Only 0 or 4321 will be possible 
2586          //  (no oportunity to check for the formerly well known
2587          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2588          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-) 
2589          //  the file IS NOT ACR-NEMA nor DICOM V3
2590          //  Find a trick to tell it the caller...
2591       
2592          s16 = *((uint16_t *)(deb));
2593       
2594          switch ( s16 )
2595          {
2596             case 0x0001 :
2597             case 0x0002 :
2598             case 0x0003 :
2599             case 0x0004 :
2600             case 0x0005 :
2601             case 0x0006 :
2602             case 0x0007 :
2603             case 0x0008 :
2604                SwapCode = 0;
2605                Filetype = ACR;
2606                return true;
2607             case 0x0100 :
2608             case 0x0200 :
2609             case 0x0300 :
2610             case 0x0400 :
2611             case 0x0500 :
2612             case 0x0600 :
2613             case 0x0700 :
2614             case 0x0800 :
2615                SwapCode = 4321;
2616                Filetype = ACR;
2617                return true;
2618             default :
2619                dbg.Verbose(0, "Document::CheckSwap:",
2620                      "ACR/NEMA unfound swap info (Really hopeless !)");
2621                Filetype = Unknown;
2622                return false;
2623          }
2624          // Then the only info we have is the net2host one.
2625          //if (! net2host )
2626          //   SwapCode = 0;
2627          //else
2628          //  SwapCode = 4321;
2629          //return;
2630    }
2631 }
2632
2633
2634
2635 /**
2636  * \brief Restore the unproperly loaded values i.e. the group, the element
2637  *        and the dictionary entry depending on them. 
2638  */
2639 void Document::SwitchSwapToBigEndian() 
2640 {
2641    dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2642                   "Switching to BigEndian mode.");
2643    if ( SwapCode == 0    ) 
2644    {
2645       SwapCode = 4321;
2646    }
2647    else if ( SwapCode == 4321 ) 
2648    {
2649       SwapCode = 0;
2650    }
2651    else if ( SwapCode == 3412 ) 
2652    {
2653       SwapCode = 2143;
2654    }
2655    else if ( SwapCode == 2143 )
2656    {
2657       SwapCode = 3412;
2658    }
2659 }
2660
2661 /**
2662  * \brief  during parsing, Header Elements too long are not loaded in memory 
2663  * @param newSize
2664  */
2665 void Document::SetMaxSizeLoadEntry(long newSize) 
2666 {
2667    if ( newSize < 0 )
2668    {
2669       return;
2670    }
2671    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2672    {
2673       MaxSizeLoadEntry = 0xffffffff;
2674       return;
2675    }
2676    MaxSizeLoadEntry = newSize;
2677 }
2678
2679
2680 /**
2681  * \brief Header Elements too long will not be printed
2682  * \todo  See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE 
2683  * @param newSize
2684  */
2685 void Document::SetMaxSizePrintEntry(long newSize) 
2686 {
2687    //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2688    if ( newSize < 0 )
2689    {
2690       return;
2691    }
2692    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2693    {
2694       MaxSizePrintEntry = 0xffffffff;
2695       return;
2696    }
2697    MaxSizePrintEntry = newSize;
2698 }
2699
2700
2701
2702 /**
2703  * \brief   Handle broken private tag from Philips NTSCAN
2704  *          where the endianess is being switch to BigEndian for no
2705  *          apparent reason
2706  * @return  no return
2707  */
2708 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2709 {
2710    // Endian reversion. Some files contain groups of tags with reversed endianess.
2711    static int reversedEndian = 0;
2712    // try to fix endian switching in the middle of headers
2713    if ((group == 0xfeff) && (elem == 0x00e0))
2714    {
2715      // start endian swap mark for group found
2716      reversedEndian++;
2717      SwitchSwapToBigEndian();
2718      // fix the tag
2719      group = 0xfffe;
2720      elem = 0xe000;
2721    } 
2722    else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian) 
2723    {
2724      // end of reversed endian group
2725      reversedEndian--;
2726      SwitchSwapToBigEndian();
2727    }
2728
2729 }
2730
2731 /**
2732  * \brief   Read the next tag but WITHOUT loading it's value
2733  *          (read the 'Group Number', the 'Element Number',
2734  *           gets the Dict Entry
2735  *          gets the VR, gets the length, gets the offset value)
2736  * @return  On succes the newly created DocEntry, NULL on failure.      
2737  */
2738 DocEntry* Document::ReadNextDocEntry()
2739 {
2740    uint16_t group;
2741    uint16_t elem;
2742
2743    try
2744    {
2745       group = ReadInt16();
2746       elem  = ReadInt16();
2747    }
2748    catch ( FormatError e )
2749    {
2750       // We reached the EOF (or an error occured) therefore 
2751       // header parsing has to be considered as finished.
2752       //std::cout << e;
2753       return 0;
2754    }
2755
2756    HandleBrokenEndian(group, elem);
2757    DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2758    FindDocEntryVR(newEntry);
2759
2760    try
2761    {
2762       FindDocEntryLength(newEntry);
2763    }
2764    catch ( FormatError e )
2765    {
2766       // Call it quits
2767       //std::cout << e;
2768       delete newEntry;
2769       return 0;
2770    }
2771
2772    newEntry->SetOffset(Fp->tellg());  
2773
2774    return newEntry;
2775 }
2776
2777
2778 /**
2779  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2780  *          in the TagHt dictionary.
2781  * @param   group The generated tag must belong to this group.  
2782  * @return  The element of tag with given group which is fee.
2783  */
2784 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group) 
2785 {
2786    for (uint32_t elem = 0; elem < UINT32_MAX; elem++) 
2787    {
2788       TagKey key = DictEntry::TranslateToKey(group, elem);
2789       if (TagHT.count(key) == 0)
2790       {
2791          return elem;
2792       }
2793    }
2794    return UINT32_MAX;
2795 }
2796
2797 /**
2798  * \brief   Assuming the internal file pointer \ref Document::Fp 
2799  *          is placed at the beginning of a tag check whether this
2800  *          tag is (TestGroup, TestElement).
2801  * \warning On success the internal file pointer \ref Document::Fp
2802  *          is modified to point after the tag.
2803  *          On failure (i.e. when the tag wasn't the expected tag
2804  *          (TestGroup, TestElement) the internal file pointer
2805  *          \ref Document::Fp is restored to it's original position.
2806  * @param   testGroup   The expected group of the tag.
2807  * @param   testElement The expected Element of the tag.
2808  * @return  True on success, false otherwise.
2809  */
2810 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2811 {
2812    long positionOnEntry = Fp->tellg();
2813    long currentPosition = Fp->tellg();          // On debugging purposes
2814
2815    //// Read the Item Tag group and element, and make
2816    // sure they are what we expected:
2817    uint16_t itemTagGroup;
2818    uint16_t itemTagElement;
2819    try
2820    {
2821       itemTagGroup   = ReadInt16();
2822       itemTagElement = ReadInt16();
2823    }
2824    catch ( FormatError e )
2825    {
2826       //std::cerr << e << std::endl;
2827       return false;
2828    }
2829    if ( itemTagGroup != testGroup || itemTagElement != testElement )
2830    {
2831       std::ostringstream s;
2832       s << "   We should have found tag (";
2833       s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2834       s << "   but instead we encountered tag (";
2835       s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2836         << std::endl;
2837       s << "  at address: " << (unsigned)currentPosition << std::endl;
2838       dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2839       dbg.Verbose(0, s.str().c_str());
2840       Fp->seekg(positionOnEntry, std::ios_base::beg);
2841
2842       return false;
2843    }
2844    return true;
2845 }
2846
2847 /**
2848  * \brief   Assuming the internal file pointer \ref Document::Fp 
2849  *          is placed at the beginning of a tag (TestGroup, TestElement),
2850  *          read the length associated to the Tag.
2851  * \warning On success the internal file pointer \ref Document::Fp
2852  *          is modified to point after the tag and it's length.
2853  *          On failure (i.e. when the tag wasn't the expected tag
2854  *          (TestGroup, TestElement) the internal file pointer
2855  *          \ref Document::Fp is restored to it's original position.
2856  * @param   testGroup   The expected group of the tag.
2857  * @param   testElement The expected Element of the tag.
2858  * @return  On success returns the length associated to the tag. On failure
2859  *          returns 0.
2860  */
2861 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2862 {
2863    long positionOnEntry = Fp->tellg();
2864    (void)positionOnEntry;
2865
2866    if ( !ReadTag(testGroup, testElement) )
2867    {
2868       return 0;
2869    }
2870                                                                                 
2871    //// Then read the associated Item Length
2872    long currentPosition = Fp->tellg();
2873    uint32_t itemLength  = ReadInt32();
2874    {
2875       std::ostringstream s;
2876       s << "Basic Item Length is: "
2877         << itemLength << std::endl;
2878       s << "  at address: " << (unsigned)currentPosition << std::endl;
2879       dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2880    }
2881    return itemLength;
2882 }
2883
2884 /**
2885  * \brief When parsing the Pixel Data of an encapsulated file, read
2886  *        the basic offset table (when present, and BTW dump it).
2887  */
2888 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2889 {
2890    //// Read the Basic Offset Table Item Tag length...
2891    uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2892
2893    // When present, read the basic offset table itself.
2894    // Notes: - since the presence of this basic offset table is optional
2895    //          we can't rely on it for the implementation, and we will simply
2896    //          trash it's content (when present).
2897    //        - still, when present, we could add some further checks on the
2898    //          lengths, but we won't bother with such fuses for the time being.
2899    if ( itemLength != 0 )
2900    {
2901       char* basicOffsetTableItemValue = new char[itemLength + 1];
2902       Fp->read(basicOffsetTableItemValue, itemLength);
2903
2904 #ifdef GDCM_DEBUG
2905       for (unsigned int i=0; i < itemLength; i += 4 )
2906       {
2907          uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2908                                               uint32_t);
2909          std::ostringstream s;
2910          s << "   Read one length: ";
2911          s << std::hex << individualLength << std::endl;
2912          dbg.Verbose(0,
2913                      "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2914                      s.str().c_str());
2915       }
2916 #endif //GDCM_DEBUG
2917
2918       delete[] basicOffsetTableItemValue;
2919    }
2920 }
2921
2922 /**
2923  * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2924  *        Compute the RLE extra information and store it in \ref RLEInfo
2925  *        for later pixel retrieval usage.
2926  */
2927 void Document::ComputeRLEInfo()
2928 {
2929    TransferSyntaxType ts = GetTransferSyntax();
2930    if ( ts != RLELossless )
2931    {
2932       return;
2933    }
2934
2935    // Encoded pixel data: for the time being we are only concerned with
2936    // Jpeg or RLE Pixel data encodings.
2937    // As stated in PS 3.5-2003, section 8.2 p44:
2938    // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2939    //  value representation OB is used".
2940    // Hence we expect an OB value representation. Concerning OB VR,
2941    // the section PS 3.5-2003, section A.4.c p 58-59, states:
2942    // "For the Value Representations OB and OW, the encoding shall meet the
2943    //   following specifications depending on the Data element tag:"
2944    //   [...snip...]
2945    //    - the first item in the sequence of items before the encoded pixel
2946    //      data stream shall be basic offset table item. The basic offset table
2947    //      item value, however, is not required to be present"
2948
2949    ReadAndSkipEncapsulatedBasicOffsetTable();
2950
2951    // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2952    // Loop on the individual frame[s] and store the information
2953    // on the RLE fragments in a RLEFramesInfo.
2954    // Note: - when only a single frame is present, this is a
2955    //         classical image.
2956    //       - when more than one frame are present, then we are in 
2957    //         the case of a multi-frame image.
2958    long frameLength;
2959    while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2960    { 
2961       // Parse the RLE Header and store the corresponding RLE Segment
2962       // Offset Table information on fragments of this current Frame.
2963       // Note that the fragment pixels themselves are not loaded
2964       // (but just skipped).
2965       long frameOffset = Fp->tellg();
2966
2967       uint32_t nbRleSegments = ReadInt32();
2968       if ( nbRleSegments > 16 )
2969       {
2970          // There should be at most 15 segments (refer to RLEFrame class)
2971          dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2972       }
2973  
2974       uint32_t rleSegmentOffsetTable[16];
2975       for( int k = 1; k <= 15; k++ )
2976       {
2977          rleSegmentOffsetTable[k] = ReadInt32();
2978       }
2979
2980       // Deduce from both the RLE Header and the frameLength the
2981       // fragment length, and again store this info in a
2982       // RLEFramesInfo.
2983       long rleSegmentLength[15];
2984       // skipping (not reading) RLE Segments
2985       if ( nbRleSegments > 1)
2986       {
2987          for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2988          {
2989              rleSegmentLength[k] =  rleSegmentOffsetTable[k+1]
2990                                   - rleSegmentOffsetTable[k];
2991              SkipBytes(rleSegmentLength[k]);
2992           }
2993        }
2994
2995        rleSegmentLength[nbRleSegments] = frameLength 
2996                                       - rleSegmentOffsetTable[nbRleSegments];
2997        SkipBytes(rleSegmentLength[nbRleSegments]);
2998
2999        // Store the collected info
3000        RLEFrame* newFrameInfo = new RLEFrame;
3001        newFrameInfo->NumberFragments = nbRleSegments;
3002        for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
3003        {
3004           newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
3005           newFrameInfo->Length[uk] = rleSegmentLength[uk];
3006        }
3007        RLEInfo->Frames.push_back( newFrameInfo );
3008    }
3009
3010    // Make sure that at the end of the item we encounter a 'Sequence
3011    // Delimiter Item':
3012    if ( !ReadTag(0xfffe, 0xe0dd) )
3013    {
3014       dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3015       dbg.Verbose(0, "    item at end of RLE item sequence");
3016    }
3017 }
3018
3019 /**
3020  * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
3021  *        Compute the jpeg extra information (fragment[s] offset[s] and
3022  *        length) and store it[them] in \ref JPEGInfo for later pixel
3023  *        retrieval usage.
3024  */
3025 void Document::ComputeJPEGFragmentInfo()
3026 {
3027    // If you need to, look for comments of ComputeRLEInfo().
3028    if ( ! IsJPEG() )
3029    {
3030       return;
3031    }
3032
3033    ReadAndSkipEncapsulatedBasicOffsetTable();
3034
3035    // Loop on the fragments[s] and store the parsed information in a
3036    // JPEGInfo.
3037    long fragmentLength;
3038    while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
3039    { 
3040       long fragmentOffset = Fp->tellg();
3041
3042        // Store the collected info
3043        JPEGFragment* newFragment = new JPEGFragment;
3044        newFragment->Offset = fragmentOffset;
3045        newFragment->Length = fragmentLength;
3046        JPEGInfo->Fragments.push_back( newFragment );
3047
3048        SkipBytes( fragmentLength );
3049    }
3050
3051    // Make sure that at the end of the item we encounter a 'Sequence
3052    // Delimiter Item':
3053    if ( !ReadTag(0xfffe, 0xe0dd) )
3054    {
3055       dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3056       dbg.Verbose(0, "    item at end of JPEG item sequence");
3057    }
3058 }
3059
3060 /**
3061  * \brief Walk recursively the given \ref DocEntrySet, and feed
3062  *        the given hash table (\ref TagDocEntryHT) with all the
3063  *        \ref DocEntry (Dicom entries) encountered.
3064  *        This method does the job for \ref BuildFlatHashTable.
3065  * @param builtHT Where to collect all the \ref DocEntry encountered
3066  *        when recursively walking the given set.
3067  * @param set The structure to be traversed (recursively).
3068  */
3069 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3070                                           DocEntrySet* set )
3071
3072    if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3073    {
3074       TagDocEntryHT const & currentHT = elementSet->GetTagHT();
3075       for( TagDocEntryHT::const_iterator i  = currentHT.begin();
3076                                          i != currentHT.end();
3077                                        ++i)
3078       {
3079          DocEntry* entry = i->second;
3080          if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3081          {
3082             const ListSQItem& items = seqEntry->GetSQItems();
3083             for( ListSQItem::const_iterator item  = items.begin();
3084                                             item != items.end();
3085                                           ++item)
3086             {
3087                BuildFlatHashTableRecurse( builtHT, *item );
3088             }
3089             continue;
3090          }
3091          builtHT[entry->GetKey()] = entry;
3092       }
3093       return;
3094     }
3095
3096    if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3097    {
3098       const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3099       for (ListDocEntry::const_iterator i  = currentList.begin();
3100                                         i != currentList.end();
3101                                       ++i)
3102       {
3103          DocEntry* entry = *i;
3104          if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3105          {
3106             const ListSQItem& items = seqEntry->GetSQItems();
3107             for( ListSQItem::const_iterator item  = items.begin();
3108                                             item != items.end();
3109                                           ++item)
3110             {
3111                BuildFlatHashTableRecurse( builtHT, *item );
3112             }
3113             continue;
3114          }
3115          builtHT[entry->GetKey()] = entry;
3116       }
3117
3118    }
3119 }
3120
3121 /**
3122  * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3123  *        Document.
3124  *
3125  *        The structure used by a Document (through \ref ElementSet),
3126  *        in order to hold the parsed entries of a Dicom header, is a recursive
3127  *        one. This is due to the fact that the sequences (when present)
3128  *        can be nested. Additionaly, the sequence items (represented in
3129  *        gdcm as \ref SQItem) add an extra complexity to the data
3130  *        structure. Hence, a gdcm user whishing to visit all the entries of
3131  *        a Dicom header will need to dig in the gdcm internals (which
3132  *        implies exposing all the internal data structures to the API).
3133  *        In order to avoid this burden to the user, \ref BuildFlatHashTable
3134  *        recursively builds a temporary hash table, which holds all the
3135  *        Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3136  *        std::map<>).
3137  * \warning Of course there is NO integrity constrain between the 
3138  *        returned \ref TagDocEntryHT and the \ref ElementSet used
3139  *        to build it. Hence if the underlying \ref ElementSet is
3140  *        altered, then it is the caller responsability to invoke 
3141  *        \ref BuildFlatHashTable again...
3142  * @return The flat std::map<> we juste build.
3143  */
3144 TagDocEntryHT* Document::BuildFlatHashTable()
3145 {
3146    TagDocEntryHT* FlatHT = new TagDocEntryHT;
3147    BuildFlatHashTableRecurse( *FlatHT, this );
3148    return FlatHT;
3149 }
3150
3151
3152
3153 /**
3154  * \brief   Compares two documents, according to \ref DicomDir rules
3155  * \warning Does NOT work with ACR-NEMA files
3156  * \todo    Find a trick to solve the pb (use RET fields ?)
3157  * @param   document
3158  * @return  true if 'smaller'
3159  */
3160 bool Document::operator<(Document &document)
3161 {
3162    // Patient Name
3163    std::string s1 = GetEntryByNumber(0x0010,0x0010);
3164    std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3165    if(s1 < s2)
3166    {
3167       return true;
3168    }
3169    else if( s1 > s2 )
3170    {
3171       return false;
3172    }
3173    else
3174    {
3175       // Patient ID
3176       s1 = GetEntryByNumber(0x0010,0x0020);
3177       s2 = document.GetEntryByNumber(0x0010,0x0020);
3178       if ( s1 < s2 )
3179       {
3180          return true;
3181       }
3182       else if ( s1 > s2 )
3183       {
3184          return false;
3185       }
3186       else
3187       {
3188          // Study Instance UID
3189          s1 = GetEntryByNumber(0x0020,0x000d);
3190          s2 = document.GetEntryByNumber(0x0020,0x000d);
3191          if ( s1 < s2 )
3192          {
3193             return true;
3194          }
3195          else if( s1 > s2 )
3196          {
3197             return false;
3198          }
3199          else
3200          {
3201             // Serie Instance UID
3202             s1 = GetEntryByNumber(0x0020,0x000e);
3203             s2 = document.GetEntryByNumber(0x0020,0x000e);    
3204             if ( s1 < s2 )
3205             {
3206                return true;
3207             }
3208             else if( s1 > s2 )
3209             {
3210                return false;
3211             }
3212          }
3213       }
3214    }
3215    return false;
3216 }
3217
3218 } // end namespace gdcm
3219
3220 //-----------------------------------------------------------------------------