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