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