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