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