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