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