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