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