]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
The following methods
[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:37:37 $
7   Version:   $Revision: 1.203 $
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 /**
933  * \brief  Loads the element while preserving the current
934  *         underlying file position indicator as opposed to
935  *        LoadDocEntry that modifies it.
936  * @param entry   Header Entry whose value will be loaded. 
937  * @return  
938  */
939 void Document::LoadDocEntrySafe(DocEntry *entry)
940 {
941    if(Fp)
942    {
943       long PositionOnEntry = Fp->tellg();
944       LoadDocEntry(entry);
945       Fp->seekg(PositionOnEntry, std::ios::beg);
946    }
947 }
948
949 /**
950  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
951  *          processor order.
952  * @return  The properly swaped 32 bits integer.
953  */
954 uint32_t Document::SwapLong(uint32_t a)
955 {
956    switch (SwapCode)
957    {
958       case 1234 :
959          break;
960       case 4321 :
961          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
962              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
963          break;   
964       case 3412 :
965          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
966          break;  
967       case 2143 :
968          a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
969       break;
970       default :
971          gdcmErrorMacro( "Unset swap code:" << SwapCode );
972          a = 0;
973    }
974    return a;
975
976
977 /**
978  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
979  *          processor order.
980  * @return  The properly unswaped 32 bits integer.
981  */
982 uint32_t Document::UnswapLong(uint32_t a)
983 {
984    return SwapLong(a);
985 }
986
987 /**
988  * \brief   Swaps the bytes so they agree with the processor order
989  * @return  The properly swaped 16 bits integer.
990  */
991 uint16_t Document::SwapShort(uint16_t a)
992 {
993    if ( SwapCode == 4321 || SwapCode == 2143 )
994    {
995       a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
996    }
997    return a;
998 }
999
1000 /**
1001  * \brief   Unswaps the bytes so they agree with the processor order
1002  * @return  The properly unswaped 16 bits integer.
1003  */
1004 uint16_t Document::UnswapShort(uint16_t a)
1005 {
1006    return SwapShort(a);
1007 }
1008
1009 //-----------------------------------------------------------------------------
1010 // Private
1011
1012 /**
1013  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1014  * @return  length of the parsed set. 
1015  */ 
1016 void Document::ParseDES(DocEntrySet *set, long offset, 
1017                         long l_max, bool delim_mode)
1018 {
1019    DocEntry *newDocEntry = 0;
1020    ValEntry *newValEntry;
1021    BinEntry *newBinEntry;
1022    SeqEntry *newSeqEntry;
1023    VRKey vr;
1024    bool used = false;
1025
1026    while (true)
1027    {
1028       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1029       {
1030          break;
1031       }
1032
1033       used = true;
1034       newDocEntry = ReadNextDocEntry( );
1035
1036       if ( !newDocEntry )
1037       {
1038          break;
1039       }
1040
1041       vr = newDocEntry->GetVR();
1042       newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
1043       newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
1044       newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1045
1046       if ( newValEntry || newBinEntry )
1047       {
1048          if ( newBinEntry )
1049          {
1050             if ( Filetype == ExplicitVR && ! Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1051             { 
1052                 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1053                 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup() 
1054                                   << "|" << newDocEntry->GetElement()
1055                                   << " : Neither Valentry, nor BinEntry." 
1056                                   "Probably unknown VR.");
1057             }
1058
1059          //////////////////// BinEntry or UNKOWN VR:
1060             // When "this" is a Document the Key is simply of the
1061             // form ( group, elem )...
1062             if ( dynamic_cast< Document* > ( set ) )
1063             {
1064                newBinEntry->SetKey( newBinEntry->GetKey() );
1065             }
1066             // but when "this" is a SQItem, we are inserting this new
1067             // valEntry in a sequence item, and the key has the
1068             // generalized form (refer to \ref BaseTagKey):
1069             if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1070             {
1071                newBinEntry->SetKey(  parentSQItem->GetBaseTagKey()
1072                                    + newBinEntry->GetKey() );
1073             }
1074
1075             LoadDocEntry( newBinEntry );
1076             if( !set->AddEntry( newBinEntry ) )
1077             {
1078               //Expect big troubles if here
1079               //delete newBinEntry;
1080               used=false;
1081             }
1082          }
1083          else
1084          {
1085          /////////////////////// ValEntry
1086             // When "set" is a Document, then we are at the top of the
1087             // hierarchy and the Key is simply of the form ( group, elem )...
1088             if ( dynamic_cast< Document* > ( set ) )
1089             {
1090                newValEntry->SetKey( newValEntry->GetKey() );
1091             }
1092             // ...but when "set" is a SQItem, we are inserting this new
1093             // valEntry in a sequence item. Hence the key has the
1094             // generalized form (refer to \ref BaseTagKey):
1095             if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1096             {
1097                newValEntry->SetKey(  parentSQItem->GetBaseTagKey()
1098                                    + newValEntry->GetKey() );
1099             }
1100              
1101             LoadDocEntry( newValEntry );
1102             bool delimitor=newValEntry->IsItemDelimitor();
1103             if( !set->AddEntry( newValEntry ) )
1104             {
1105               // If here expect big troubles
1106               //delete newValEntry; //otherwise mem leak
1107               used=false;
1108             }
1109
1110             if (delimitor)
1111             {
1112                if(!used)
1113                   delete newDocEntry;
1114                break;
1115             }
1116             if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1117             {
1118                if(!used)
1119                   delete newDocEntry;
1120                break;
1121             }
1122          }
1123
1124          if (    ( newDocEntry->GetGroup()   == 0x7fe0 )
1125               && ( newDocEntry->GetElement() == 0x0010 ) )
1126          {
1127              std::string ts = GetTransferSyntax();
1128              if ( Global::GetTS()->IsRLELossless(ts) ) 
1129              {
1130                 long positionOnEntry = Fp->tellg();
1131                 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1132                 ComputeRLEInfo();
1133                 Fp->seekg( positionOnEntry, std::ios::beg );
1134              }
1135              else if ( Global::GetTS()->IsJPEG(ts) )
1136              {
1137                 long positionOnEntry = Fp->tellg();
1138                 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1139                 ComputeJPEGFragmentInfo();
1140                 Fp->seekg( positionOnEntry, std::ios::beg );
1141              }
1142          }
1143
1144          // Just to make sure we are at the beginning of next entry.
1145          SkipToNextDocEntry(newDocEntry);
1146       }
1147       else
1148       {
1149          // VR = "SQ"
1150          unsigned long l = newDocEntry->GetReadLength();            
1151          if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1152          {
1153             if ( l == 0xffffffff )
1154             {
1155               delim_mode = true;
1156             }
1157             else
1158             {
1159               delim_mode = false;
1160             }
1161          }
1162          // no other way to create it ...
1163          newSeqEntry->SetDelimitorMode( delim_mode );
1164
1165          // At the top of the hierarchy, stands a Document. When "set"
1166          // is a Document, then we are building the first depth level.
1167          // Hence the SeqEntry we are building simply has a depth
1168          // level of one:
1169          if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
1170          {
1171             //(void)dummy;
1172             newSeqEntry->SetDepthLevel( 1 );
1173             newSeqEntry->SetKey( newSeqEntry->GetKey() );
1174          }
1175          // But when "set" is already a SQItem, we are building a nested
1176          // sequence, and hence the depth level of the new SeqEntry
1177          // we are building, is one level deeper:
1178          if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1179          {
1180             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1181             newSeqEntry->SetKey(  parentSQItem->GetBaseTagKey()
1182                                 + newSeqEntry->GetKey() );
1183          }
1184
1185          if ( l != 0 )
1186          {  // Don't try to parse zero-length sequences
1187             ParseSQ( newSeqEntry, 
1188                      newDocEntry->GetOffset(),
1189                      l, delim_mode);
1190          }
1191          set->AddEntry( newSeqEntry );
1192          if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1193          {
1194             break;
1195          }
1196       }
1197
1198       if(!used)
1199          delete newDocEntry;
1200    }
1201 }
1202
1203 /**
1204  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1205  * @return  parsed length for this level
1206  */ 
1207 void Document::ParseSQ( SeqEntry *seqEntry,
1208                         long offset, long l_max, bool delim_mode)
1209 {
1210    int SQItemNumber = 0;
1211    bool dlm_mod;
1212    long offsetStartCurrentSQItem = offset;
1213
1214    while (true)
1215    {
1216       // the first time, we read the fff0,e000 of the first SQItem
1217       DocEntry *newDocEntry = ReadNextDocEntry();
1218
1219       if ( !newDocEntry )
1220       {
1221          // FIXME Should warn user
1222          break;
1223       }
1224       if( delim_mode )
1225       {
1226          if ( newDocEntry->IsSequenceDelimitor() )
1227          {
1228             seqEntry->SetDelimitationItem( newDocEntry ); 
1229             break;
1230          }
1231       }
1232       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1233       {
1234          delete newDocEntry;
1235          break;
1236       }
1237       // create the current SQItem
1238       SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1239       std::ostringstream newBase;
1240       newBase << seqEntry->GetKey()
1241               << "/"
1242               << SQItemNumber
1243               << "#";
1244       itemSQ->SetBaseTagKey( newBase.str() );
1245       unsigned int l = newDocEntry->GetReadLength();
1246       
1247       if ( l == 0xffffffff )
1248       {
1249          dlm_mod = true;
1250       }
1251       else
1252       {
1253          dlm_mod = false;
1254       }
1255       // FIXME, TODO
1256       // when we're here, element fffe,e000 is already passed.
1257       // it's lost for the SQItem we're going to process !!
1258
1259       //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1260       //delete newDocEntry; // FIXME well ... it's too late to use it !
1261
1262       // Let's try :------------
1263       // remove fff0,e000, created out of the SQItem
1264       delete newDocEntry;
1265       Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1266       // fill up the current SQItem, starting at the beginning of fff0,e000
1267       ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1268       offsetStartCurrentSQItem = Fp->tellg();
1269       // end try -----------------
1270  
1271       seqEntry->AddSQItem( itemSQ, SQItemNumber ); 
1272       SQItemNumber++;
1273       if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1274       {
1275          break;
1276       }
1277    }
1278 }
1279
1280 /**
1281  * \brief         Loads the element content if its length doesn't exceed
1282  *                the value specified with Document::SetMaxSizeLoadEntry()
1283  * @param         entry Header Entry (Dicom Element) to be dealt with
1284  */
1285 void Document::LoadDocEntry(DocEntry *entry)
1286 {
1287    uint16_t group  = entry->GetGroup();
1288    std::string  vr = entry->GetVR();
1289    uint32_t length = entry->GetLength();
1290
1291    Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1292
1293    // A SeQuence "contains" a set of Elements.  
1294    //          (fffe e000) tells us an Element is beginning
1295    //          (fffe e00d) tells us an Element just ended
1296    //          (fffe e0dd) tells us the current SeQuence just ended
1297    if( group == 0xfffe )
1298    {
1299       // NO more value field for SQ !
1300       return;
1301    }
1302
1303    // When the length is zero things are easy:
1304    if ( length == 0 )
1305    {
1306       ((ValEntry *)entry)->SetValue("");
1307       return;
1308    }
1309
1310    // The elements whose length is bigger than the specified upper bound
1311    // are not loaded. Instead we leave a short notice of the offset of
1312    // the element content and it's length.
1313
1314    std::ostringstream s;
1315    if (length > MaxSizeLoadEntry)
1316    {
1317       if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1318       {  
1319          //s << "gdcm::NotLoaded (BinEntry)";
1320          s << GDCM_NOTLOADED;
1321          s << " Address:" << (long)entry->GetOffset();
1322          s << " Length:"  << entry->GetLength();
1323          s << " x(" << std::hex << entry->GetLength() << ")";
1324          binEntryPtr->SetValue(s.str());
1325       }
1326       // Be carefull : a BinEntry IS_A ValEntry ... 
1327       else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1328       {
1329         // s << "gdcm::NotLoaded. (ValEntry)";
1330          s << GDCM_NOTLOADED;  
1331          s << " Address:" << (long)entry->GetOffset();
1332          s << " Length:"  << entry->GetLength();
1333          s << " x(" << std::hex << entry->GetLength() << ")";
1334          valEntryPtr->SetValue(s.str());
1335       }
1336       else
1337       {
1338          // fusible
1339          gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1340                       << "nor a ValEntry ?! Should never print that !" );
1341       }
1342
1343       // to be sure we are at the end of the value ...
1344       Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1345                 std::ios::beg);
1346       return;
1347    }
1348
1349    // When we find a BinEntry not very much can be done :
1350    if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1351    {
1352       s << GDCM_BINLOADED;
1353       binEntryPtr->SetValue(s.str());
1354       LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1355       return;
1356    }
1357
1358    /// \todo Any compacter code suggested (?)
1359    if ( IsDocEntryAnInteger(entry) )
1360    {   
1361       uint32_t NewInt;
1362       int nbInt;
1363       // When short integer(s) are expected, read and convert the following 
1364       // n *two characters properly i.e. consider them as short integers as
1365       // opposed to strings.
1366       // Elements with Value Multiplicity > 1
1367       // contain a set of integers (not a single one)       
1368       if (vr == "US" || vr == "SS")
1369       {
1370          nbInt = length / 2;
1371          NewInt = ReadInt16();
1372          s << NewInt;
1373          if (nbInt > 1)
1374          {
1375             for (int i=1; i < nbInt; i++)
1376             {
1377                s << '\\';
1378                NewInt = ReadInt16();
1379                s << NewInt;
1380             }
1381          }
1382       }
1383       // See above comment on multiple integers (mutatis mutandis).
1384       else if (vr == "UL" || vr == "SL")
1385       {
1386          nbInt = length / 4;
1387          NewInt = ReadInt32();
1388          s << NewInt;
1389          if (nbInt > 1)
1390          {
1391             for (int i=1; i < nbInt; i++)
1392             {
1393                s << '\\';
1394                NewInt = ReadInt32();
1395                s << NewInt;
1396             }
1397          }
1398       }
1399 #ifdef GDCM_NO_ANSI_STRING_STREAM
1400       s << std::ends; // to avoid oddities on Solaris
1401 #endif //GDCM_NO_ANSI_STRING_STREAM
1402
1403       ((ValEntry *)entry)->SetValue(s.str());
1404       return;
1405    }
1406    
1407   // FIXME: We need an additional byte for storing \0 that is not on disk
1408    char *str = new char[length+1];
1409    Fp->read(str, (size_t)length);
1410    str[length] = '\0'; //this is only useful when length is odd
1411    // Special DicomString call to properly handle \0 and even length
1412    std::string newValue;
1413    if( length % 2 )
1414    {
1415       newValue = Util::DicomString(str, length+1);
1416       gdcmVerboseMacro("Warning: bad length: " << length <<
1417                        ",For string :" <<  newValue.c_str()); 
1418       // Since we change the length of string update it length
1419       //entry->SetReadLength(length+1);
1420    }
1421    else
1422    {
1423       newValue = Util::DicomString(str, length);
1424    }
1425    delete[] str;
1426
1427    if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1428    {
1429       if ( Fp->fail() || Fp->eof())
1430       {
1431          gdcmVerboseMacro("Unread element value");
1432          valEntry->SetValue(GDCM_UNREAD);
1433          return;
1434       }
1435
1436       if( vr == "UI" )
1437       {
1438          // Because of correspondance with the VR dic
1439          valEntry->SetValue(newValue);
1440       }
1441       else
1442       {
1443          valEntry->SetValue(newValue);
1444       }
1445    }
1446    else
1447    {
1448       gdcmErrorMacro( "Should have a ValEntry, here !");
1449    }
1450 }
1451
1452
1453 /**
1454  * \brief  Find the value Length of the passed Header Entry
1455  * @param  entry Header Entry whose length of the value shall be loaded. 
1456  */
1457 void Document::FindDocEntryLength( DocEntry *entry )
1458    throw ( FormatError )
1459 {
1460    std::string  vr  = entry->GetVR();
1461    uint16_t length16;       
1462    
1463    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1464    {
1465       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" ) 
1466       {
1467          // The following reserved two bytes (see PS 3.5-2003, section
1468          // "7.1.2 Data element structure with explicit vr", p 27) must be
1469          // skipped before proceeding on reading the length on 4 bytes.
1470          Fp->seekg( 2L, std::ios::cur);
1471          uint32_t length32 = ReadInt32();
1472
1473          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1474          {
1475             uint32_t lengthOB;
1476             try 
1477             {
1478                lengthOB = FindDocEntryLengthOBOrOW();
1479             }
1480             catch ( FormatUnexpected )
1481             {
1482                // Computing the length failed (this happens with broken
1483                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1484                // chance to get the pixels by deciding the element goes
1485                // until the end of the file. Hence we artificially fix the
1486                // the length and proceed.
1487                long currentPosition = Fp->tellg();
1488                Fp->seekg(0L,std::ios::end);
1489
1490                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1491                Fp->seekg(currentPosition, std::ios::beg);
1492
1493                entry->SetReadLength(lengthUntilEOF);
1494                entry->SetLength(lengthUntilEOF);
1495                return;
1496             }
1497             entry->SetReadLength(lengthOB);
1498             entry->SetLength(lengthOB);
1499             return;
1500          }
1501          FixDocEntryFoundLength(entry, length32); 
1502          return;
1503       }
1504
1505       // Length is encoded on 2 bytes.
1506       length16 = ReadInt16();
1507
1508       // FIXME : This heuristic supposes that the first group following
1509       //         group 0002 *has* and element 0000.
1510       // BUT ... Element 0000 is optionnal :-(
1511
1512
1513    // Fixed using : HandleOutOfGroup0002()
1514    //              (first hereafter strategy ...)
1515       
1516       // We can tell the current file is encoded in big endian (like
1517       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1518       // and it's value is the one of the encoding of a big endian file.
1519       // In order to deal with such big endian encoded files, we have
1520       // (at least) two strategies:
1521       // * when we load the "Transfer Syntax" tag with value of big endian
1522       //   encoding, we raise the proper flags. Then we wait for the end
1523       //   of the META group (0x0002) among which is "Transfer Syntax",
1524       //   before switching the swap code to big endian. We have to postpone
1525       //   the switching of the swap code since the META group is fully encoded
1526       //   in little endian, and big endian coding only starts at the next
1527       //   group. The corresponding code can be hard to analyse and adds
1528       //   many additional unnecessary tests for regular tags.
1529       // * the second strategy consists in waiting for trouble, that shall
1530       //   appear when we find the first group with big endian encoding. This
1531       //   is easy to detect since the length of a "Group Length" tag (the
1532       //   ones with zero as element number) has to be of 4 (0x0004). When we
1533       //   encounter 1024 (0x0400) chances are the encoding changed and we
1534       //   found a group with big endian encoding.
1535       //---> Unfortunately, element 0000 is optional.
1536       //---> This will not work when missing!
1537       // We shall use this second strategy. In order to make sure that we
1538       // can interpret the presence of an apparently big endian encoded
1539       // length of a "Group Length" without committing a big mistake, we
1540       // add an additional check: we look in the already parsed elements
1541       // for the presence of a "Transfer Syntax" whose value has to be "big
1542       // endian encoding". When this is the case, chances are we have got our
1543       // hands on a big endian encoded file: we switch the swap code to
1544       // big endian and proceed...
1545
1546 //      if ( element  == 0x0000 && length16 == 0x0400 ) 
1547 //      {
1548 //         std::string ts = GetTransferSyntax();
1549 //         if ( Global::GetTS()->GetSpecialTransferSyntax(ts) 
1550 //                != TS::ExplicitVRBigEndian ) 
1551 //         {
1552 //            throw FormatError( "Document::FindDocEntryLength()",
1553 //                               " not explicit VR." );
1554 //           return;
1555 //        }
1556 //        length16 = 4;
1557 //        SwitchByteSwapCode();
1558 //
1559 //         // Restore the unproperly loaded values i.e. the group, the element
1560 //         // and the dictionary entry depending on them.
1561 //         uint16_t correctGroup = SwapShort( entry->GetGroup() );
1562 //         uint16_t correctElem  = SwapShort( entry->GetElement() );
1563 //         DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1564 //         if ( !newTag )
1565 //         {
1566 //            // This correct tag is not in the dictionary. Create a new one.
1567 //            newTag = NewVirtualDictEntry(correctGroup, correctElem);
1568 //         }
1569 //         // FIXME this can create a memory leaks on the old entry that be
1570 //         // left unreferenced.
1571 //         entry->SetDictEntry( newTag );
1572 //      }
1573   
1574       // 0xffff means that we deal with 'No Length' Sequence 
1575       //        or 'No Length' SQItem
1576       if ( length16 == 0xffff) 
1577       {           
1578          length16 = 0;
1579       }
1580       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1581       return;
1582    }
1583    else
1584    {
1585       // Either implicit VR or a non DICOM conformal (see note below) explicit
1586       // VR that ommited the VR of (at least) this element. Farts happen.
1587       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1588       // on Data elements "Implicit and Explicit VR Data Elements shall
1589       // not coexist in a Data Set and Data Sets nested within it".]
1590       // Length is on 4 bytes.
1591
1592      // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1593      // even if Transfer Syntax is 'Implicit VR ...' 
1594       
1595       FixDocEntryFoundLength( entry, ReadInt32() );
1596       return;
1597    }
1598 }
1599
1600 /**
1601  * \brief     Find the Value Representation of the current Dicom Element.
1602  * @return    Value Representation of the current Entry
1603  */
1604 std::string Document::FindDocEntryVR()
1605 {
1606    if ( Filetype != ExplicitVR )
1607       return GDCM_UNKNOWN;
1608
1609    long positionOnEntry = Fp->tellg();
1610    // Warning: we believe this is explicit VR (Value Representation) because
1611    // we used a heuristic that found "UL" in the first tag. Alas this
1612    // doesn't guarantee that all the tags will be in explicit VR. In some
1613    // cases (see e-film filtered files) one finds implicit VR tags mixed
1614    // within an explicit VR file. Hence we make sure the present tag
1615    // is in explicit VR and try to fix things if it happens not to be
1616    // the case.
1617
1618    char vr[3];
1619    Fp->read (vr, (size_t)2);
1620    vr[2] = 0;
1621
1622    if( !CheckDocEntryVR(vr) )
1623    {
1624       Fp->seekg(positionOnEntry, std::ios::beg);
1625       return GDCM_UNKNOWN;
1626    }
1627    return vr;
1628 }
1629
1630 /**
1631  * \brief     Check the correspondance between the VR of the header entry
1632  *            and the taken VR. If they are different, the header entry is 
1633  *            updated with the new VR.
1634  * @param     vr    Dicom Value Representation
1635  * @return    false if the VR is incorrect of if the VR isn't referenced
1636  *            otherwise, it returns true
1637 */
1638 bool Document::CheckDocEntryVR(VRKey vr)
1639 {
1640    // CLEANME searching the dicom_vr at each occurence is expensive.
1641    // PostPone this test in an optional integrity check at the end
1642    // of parsing or only in debug mode.
1643    if ( !Global::GetVR()->IsValidVR(vr) )
1644       return false;
1645
1646    return true; 
1647 }
1648
1649 /**
1650  * \brief   Get the transformed value of the header entry. The VR value 
1651  *          is used to define the transformation to operate on the value
1652  * \warning NOT end user intended method !
1653  * @param   entry entry to tranform
1654  * @return  Transformed entry value
1655  */
1656 std::string Document::GetDocEntryValue(DocEntry *entry)
1657 {
1658    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1659    {
1660       std::string val = ((ValEntry *)entry)->GetValue();
1661       std::string vr  = entry->GetVR();
1662       uint32_t length = entry->GetLength();
1663       std::ostringstream s;
1664       int nbInt;
1665
1666       // When short integer(s) are expected, read and convert the following 
1667       // n * 2 bytes properly i.e. as a multivaluated strings
1668       // (each single value is separated fromthe next one by '\'
1669       // as usual for standard multivaluated filels
1670       // Elements with Value Multiplicity > 1
1671       // contain a set of short integers (not a single one) 
1672    
1673       if( vr == "US" || vr == "SS" )
1674       {
1675          uint16_t newInt16;
1676
1677          nbInt = length / 2;
1678          for (int i=0; i < nbInt; i++) 
1679          {
1680             if( i != 0 )
1681             {
1682                s << '\\';
1683             }
1684             newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1685             newInt16 = SwapShort( newInt16 );
1686             s << newInt16;
1687          }
1688       }
1689
1690       // When integer(s) are expected, read and convert the following 
1691       // n * 4 bytes properly i.e. as a multivaluated strings
1692       // (each single value is separated fromthe next one by '\'
1693       // as usual for standard multivaluated filels
1694       // Elements with Value Multiplicity > 1
1695       // contain a set of integers (not a single one) 
1696       else if( vr == "UL" || vr == "SL" )
1697       {
1698          uint32_t newInt32;
1699
1700          nbInt = length / 4;
1701          for (int i=0; i < nbInt; i++) 
1702          {
1703             if( i != 0)
1704             {
1705                s << '\\';
1706             }
1707             newInt32 = ( val[4*i+0] & 0xFF )
1708                     + (( val[4*i+1] & 0xFF ) <<  8 )
1709                     + (( val[4*i+2] & 0xFF ) << 16 )
1710                     + (( val[4*i+3] & 0xFF ) << 24 );
1711             newInt32 = SwapLong( newInt32 );
1712             s << newInt32;
1713          }
1714       }
1715 #ifdef GDCM_NO_ANSI_STRING_STREAM
1716       s << std::ends; // to avoid oddities on Solaris
1717 #endif //GDCM_NO_ANSI_STRING_STREAM
1718       return s.str();
1719    }
1720
1721    return ((ValEntry *)entry)->GetValue();
1722 }
1723
1724 /**
1725  * \brief   Get the reverse transformed value of the header entry. The VR 
1726  *          value is used to define the reverse transformation to operate on
1727  *          the value
1728  * \warning NOT end user intended method !
1729  * @param   entry Entry to reverse transform
1730  * @return  Reverse transformed entry value
1731  */
1732 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1733 {
1734    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1735    {
1736       std::string vr = entry->GetVR();
1737       std::vector<std::string> tokens;
1738       std::ostringstream s;
1739
1740       if ( vr == "US" || vr == "SS" ) 
1741       {
1742          uint16_t newInt16;
1743
1744          tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1745          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1746          for (unsigned int i=0; i<tokens.size(); i++) 
1747          {
1748             newInt16 = atoi(tokens[i].c_str());
1749             s << (  newInt16        & 0xFF ) 
1750               << (( newInt16 >> 8 ) & 0xFF );
1751          }
1752          tokens.clear();
1753       }
1754       if ( vr == "UL" || vr == "SL")
1755       {
1756          uint32_t newInt32;
1757
1758          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1759          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1760          for (unsigned int i=0; i<tokens.size();i++) 
1761          {
1762             newInt32 = atoi(tokens[i].c_str());
1763             s << (char)(  newInt32         & 0xFF ) 
1764               << (char)(( newInt32 >>  8 ) & 0xFF )
1765               << (char)(( newInt32 >> 16 ) & 0xFF )
1766               << (char)(( newInt32 >> 24 ) & 0xFF );
1767          }
1768          tokens.clear();
1769       }
1770
1771 #ifdef GDCM_NO_ANSI_STRING_STREAM
1772       s << std::ends; // to avoid oddities on Solaris
1773 #endif //GDCM_NO_ANSI_STRING_STREAM
1774       return s.str();
1775    }
1776
1777    return ((ValEntry *)entry)->GetValue();
1778 }
1779
1780 /**
1781  * \brief   Skip a given Header Entry 
1782  * \warning NOT end user intended method !
1783  * @param   entry entry to skip
1784  */
1785 void Document::SkipDocEntry(DocEntry *entry) 
1786 {
1787    SkipBytes(entry->GetLength());
1788 }
1789
1790 /**
1791  * \brief   Skips to the begining of the next Header Entry 
1792  * \warning NOT end user intended method !
1793  * @param   currentDocEntry entry to skip
1794  */
1795 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry) 
1796 {
1797    Fp->seekg((long)(currentDocEntry->GetOffset()),     std::ios::beg);
1798    if (currentDocEntry->GetGroup() != 0xfffe)  // for fffe pb
1799       Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1800 }
1801
1802 /**
1803  * \brief   When the length of an element value is obviously wrong (because
1804  *          the parser went Jabberwocky) one can hope improving things by
1805  *          applying some heuristics.
1806  * @param   entry entry to check
1807  * @param   foundLength first assumption about length    
1808  */
1809 void Document::FixDocEntryFoundLength(DocEntry *entry,
1810                                       uint32_t foundLength)
1811 {
1812    entry->SetReadLength( foundLength ); // will be updated only if a bug is found        
1813    if ( foundLength == 0xffffffff)
1814    {
1815       foundLength = 0;
1816    }
1817    
1818    uint16_t gr   = entry->GetGroup();
1819    uint16_t elem = entry->GetElement(); 
1820      
1821    if ( foundLength % 2)
1822    {
1823       gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength 
1824         <<  " in x(" << std::hex << gr << "," << elem <<")");
1825    }
1826       
1827    //////// Fix for some naughty General Electric images.
1828    // Allthough not recent many such GE corrupted images are still present
1829    // on Creatis hard disks. Hence this fix shall remain when such images
1830    // are no longer in use (we are talking a few years, here)...
1831    // Note: XMedCom probably uses such a trick since it is able to read
1832    //       those pesky GE images ...
1833    if ( foundLength == 13)
1834    {
1835       // Only happens for this length !
1836       if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1837       {
1838          foundLength = 10;
1839          entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1840       }
1841    }
1842
1843    //////// Fix for some brain-dead 'Leonardo' Siemens images.
1844    // Occurence of such images is quite low (unless one leaves close to a
1845    // 'Leonardo' source. Hence, one might consider commenting out the
1846    // following fix on efficiency reasons.
1847    else if ( gr   == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1848    {
1849       foundLength = 4;
1850       entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1851    } 
1852  
1853    else if ( entry->GetVR() == "SQ" )
1854    {
1855       foundLength = 0;      // ReadLength is unchanged 
1856    } 
1857     
1858    //////// We encountered a 'delimiter' element i.e. a tag of the form 
1859    // "fffe|xxxx" which is just a marker. Delimiters length should not be
1860    // taken into account.
1861    else if( gr == 0xfffe )
1862    {    
1863      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1864      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1865      // causes extra troubles...
1866      if( entry->GetElement() != 0x0000 )
1867      {
1868         foundLength = 0;
1869      }
1870    } 
1871            
1872    entry->SetLength(foundLength);
1873 }
1874
1875 /**
1876  * \brief   Apply some heuristics to predict whether the considered 
1877  *          element value contains/represents an integer or not.
1878  * @param   entry The element value on which to apply the predicate.
1879  * @return  The result of the heuristical predicate.
1880  */
1881 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1882 {
1883    uint16_t elem    = entry->GetElement();
1884    uint16_t group   = entry->GetGroup();
1885    const std::string &vr  = entry->GetVR();
1886    uint32_t length  = entry->GetLength();
1887
1888    // When we have some semantics on the element we just read, and if we
1889    // a priori know we are dealing with an integer, then we shall be
1890    // able to swap it's element value properly.
1891    if ( elem == 0 )  // This is the group length of the group
1892    {  
1893       if ( length == 4 )
1894       {
1895          return true;
1896       }
1897       else 
1898       {
1899          // Allthough this should never happen, still some images have a
1900          // corrupted group length [e.g. have a glance at offset x(8336) of
1901          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1902          // Since for dicom compliant and well behaved headers, the present
1903          // test is useless (and might even look a bit paranoid), when we
1904          // encounter such an ill-formed image, we simply display a warning
1905          // message and proceed on parsing (while crossing fingers).
1906          long filePosition = Fp->tellg();
1907          gdcmVerboseMacro( "Erroneous Group Length element length  on : (" 
1908            << std::hex << group << " , " << elem
1909            << ") -before- position x(" << filePosition << ")"
1910            << "lgt : " << length );
1911       }
1912    }
1913
1914    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1915    {
1916       return true;
1917    }   
1918    return false;
1919 }
1920
1921 /**
1922  * \brief  Find the Length till the next sequence delimiter
1923  * \warning NOT end user intended method !
1924  * @return 
1925  */
1926
1927 uint32_t Document::FindDocEntryLengthOBOrOW()
1928    throw( FormatUnexpected )
1929 {
1930    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1931    long positionOnEntry = Fp->tellg();
1932    bool foundSequenceDelimiter = false;
1933    uint32_t totalLength = 0;
1934
1935    while ( !foundSequenceDelimiter )
1936    {
1937       uint16_t group;
1938       uint16_t elem;
1939       try
1940       {
1941          group = ReadInt16();
1942          elem  = ReadInt16();   
1943       }
1944       catch ( FormatError )
1945       {
1946          throw FormatError("Unexpected end of file encountered during ",
1947                            "Document::FindDocEntryLengthOBOrOW()");
1948       }
1949
1950       // We have to decount the group and element we just read
1951       totalLength += 4;
1952      
1953       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1954       {
1955          long filePosition = Fp->tellg();
1956          gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :" 
1957            << std::hex << group << " , " << elem 
1958            << ") -before- position x(" << filePosition << ")" );
1959   
1960          Fp->seekg(positionOnEntry, std::ios::beg);
1961          throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1962       }
1963
1964       if ( elem == 0xe0dd )
1965       {
1966          foundSequenceDelimiter = true;
1967       }
1968
1969       uint32_t itemLength = ReadInt32();
1970       // We add 4 bytes since we just read the ItemLength with ReadInt32
1971       totalLength += itemLength + 4;
1972       SkipBytes(itemLength);
1973       
1974       if ( foundSequenceDelimiter )
1975       {
1976          break;
1977       }
1978    }
1979    Fp->seekg( positionOnEntry, std::ios::beg);
1980    return totalLength;
1981 }
1982
1983 /**
1984  * \brief Reads a supposed to be 16 Bits integer
1985  *       (swaps it depending on processor endianity) 
1986  * @return read value
1987  */
1988 uint16_t Document::ReadInt16()
1989    throw( FormatError )
1990 {
1991    uint16_t g;
1992    Fp->read ((char*)&g, (size_t)2);
1993    if ( Fp->fail() )
1994    {
1995       throw FormatError( "Document::ReadInt16()", " file error." );
1996    }
1997    if( Fp->eof() )
1998    {
1999       throw FormatError( "Document::ReadInt16()", "EOF." );
2000    }
2001    g = SwapShort(g); 
2002    return g;
2003 }
2004
2005 /**
2006  * \brief  Reads a supposed to be 32 Bits integer
2007  *         (swaps it depending on processor endianity)  
2008  * @return read value
2009  */
2010 uint32_t Document::ReadInt32()
2011    throw( FormatError )
2012 {
2013    uint32_t g;
2014    Fp->read ((char*)&g, (size_t)4);
2015    if ( Fp->fail() )
2016    {
2017       throw FormatError( "Document::ReadInt32()", " file error." );
2018    }
2019    if( Fp->eof() )
2020    {
2021       throw FormatError( "Document::ReadInt32()", "EOF." );
2022    }
2023    g = SwapLong(g);
2024    return g;
2025 }
2026
2027 /**
2028  * \brief skips bytes inside the source file 
2029  * \warning NOT end user intended method !
2030  * @return 
2031  */
2032 void Document::SkipBytes(uint32_t nBytes)
2033 {
2034    //FIXME don't dump the returned value
2035    Fp->seekg((long)nBytes, std::ios::cur);
2036 }
2037
2038 /**
2039  * \brief Loads all the needed Dictionaries
2040  * \warning NOT end user intended method !   
2041  */
2042 void Document::Initialize() 
2043 {
2044    RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2045    RefShaDict = NULL;
2046    RLEInfo  = new RLEFramesInfo;
2047    JPEGInfo = new JPEGFragmentsInfo;
2048    Filetype = Unknown;
2049 }
2050
2051 /**
2052  * \brief   Discover what the swap code is (among little endian, big endian,
2053  *          bad little endian, bad big endian).
2054  *          sw is set
2055  * @return false when we are absolutely sure 
2056  *               it's neither ACR-NEMA nor DICOM
2057  *         true  when we hope ours assuptions are OK
2058  */
2059 bool Document::CheckSwap()
2060 {
2061    // The only guaranted way of finding the swap code is to find a
2062    // group tag since we know it's length has to be of four bytes i.e.
2063    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2064    // occurs when we can't find such group...
2065    
2066    uint32_t  x = 4;  // x : for ntohs
2067    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2068    uint32_t  s32;
2069    uint16_t  s16;
2070        
2071    char deb[256];
2072     
2073    // First, compare HostByteOrder and NetworkByteOrder in order to
2074    // determine if we shall need to swap bytes (i.e. the Endian type).
2075    if ( x == ntohs(x) )
2076    {
2077       net2host = true;
2078    }
2079    else
2080    {
2081       net2host = false;
2082    }
2083          
2084    // The easiest case is the one of a 'true' DICOM header, we just have
2085    // to look for the string "DICM" inside the file preamble.
2086    Fp->read(deb, 256);
2087    
2088    char *entCur = deb + 128;
2089    if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2090    {
2091       gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
2092       
2093       // Group 0002 should always be VR, and the first element 0000
2094       // Let's be carefull (so many wrong headers ...)
2095       // and determine the value representation (VR) : 
2096       // Let's skip to the first element (0002,0000) and check there if we find
2097       // "UL"  - or "OB" if the 1st one is (0002,0001) -,
2098       // in which case we (almost) know it is explicit VR.
2099       // WARNING: if it happens to be implicit VR then what we will read
2100       // is the length of the group. If this ascii representation of this
2101       // length happens to be "UL" then we shall believe it is explicit VR.
2102       // We need to skip :
2103       // * the 128 bytes of File Preamble (often padded with zeroes),
2104       // * the 4 bytes of "DICM" string,
2105       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2106       // i.e. a total of  136 bytes.
2107       entCur = deb + 136;
2108      
2109       // group 0x0002 *is always* Explicit VR Sometimes ,
2110       // even if elem 0002,0010 (Transfer Syntax) tells us the file is
2111       // *Implicit* VR  (see former 'gdcmData/icone.dcm')
2112       
2113       if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2114           memcmp(entCur, "OB", (size_t)2) == 0 ||
2115           memcmp(entCur, "UI", (size_t)2) == 0 ||
2116           memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
2117                                                   // when Write DCM *adds*
2118       // FIXME
2119       // Use Document::dicom_vr to test all the possibilities
2120       // instead of just checking for UL, OB and UI !? group 0000 
2121       {
2122          Filetype = ExplicitVR;
2123          gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
2124       } 
2125       else 
2126       {
2127          Filetype = ImplicitVR;
2128          gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
2129                         << "Looks like a bugged Header!");
2130       }
2131       
2132       if ( net2host )
2133       {
2134          SwapCode = 4321;
2135          gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
2136       }
2137       else 
2138       {
2139          SwapCode = 1234;
2140          gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
2141       }
2142       
2143       // Position the file position indicator at first tag 
2144       // (i.e. after the file preamble and the "DICM" string).
2145       Fp->seekg(0, std::ios::beg);
2146       Fp->seekg ( 132L, std::ios::beg);
2147       return true;
2148    } // End of DicomV3
2149
2150    // Alas, this is not a DicomV3 file and whatever happens there is no file
2151    // preamble. We can reset the file position indicator to where the data
2152    // is (i.e. the beginning of the file).
2153    gdcmVerboseMacro( "Not a DICOM Version3 file");
2154    Fp->seekg(0, std::ios::beg);
2155
2156    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2157    // By clean we mean that the length of the first tag is written down.
2158    // If this is the case and since the length of the first group HAS to be
2159    // four (bytes), then determining the proper swap code is straightforward.
2160
2161    entCur = deb + 4;
2162    // We assume the array of char we are considering contains the binary
2163    // representation of a 32 bits integer. Hence the following dirty
2164    // trick :
2165    s32 = *((uint32_t *)(entCur));
2166
2167    switch( s32 )
2168    {
2169       case 0x00040000 :
2170          SwapCode = 3412;
2171          Filetype = ACR;
2172          return true;
2173       case 0x04000000 :
2174          SwapCode = 4321;
2175          Filetype = ACR;
2176          return true;
2177       case 0x00000400 :
2178          SwapCode = 2143;
2179          Filetype = ACR;
2180          return true;
2181       case 0x00000004 :
2182          SwapCode = 1234;
2183          Filetype = ACR;
2184          return true;
2185       default :
2186          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2187          // It is time for despaired wild guesses. 
2188          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2189          //  i.e. the 'group length' element is not present :     
2190          
2191          //  check the supposed-to-be 'group number'
2192          //  in ( 0x0001 .. 0x0008 )
2193          //  to determine ' SwapCode' value .
2194          //  Only 0 or 4321 will be possible 
2195          //  (no oportunity to check for the formerly well known
2196          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2197          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-) 
2198          //  the file IS NOT ACR-NEMA nor DICOM V3
2199          //  Find a trick to tell it the caller...
2200       
2201          s16 = *((uint16_t *)(deb));
2202       
2203          switch ( s16 )
2204          {
2205             case 0x0001 :
2206             case 0x0002 :
2207             case 0x0003 :
2208             case 0x0004 :
2209             case 0x0005 :
2210             case 0x0006 :
2211             case 0x0007 :
2212             case 0x0008 :
2213                SwapCode = 1234;
2214                Filetype = ACR;
2215                return true;
2216             case 0x0100 :
2217             case 0x0200 :
2218             case 0x0300 :
2219             case 0x0400 :
2220             case 0x0500 :
2221             case 0x0600 :
2222             case 0x0700 :
2223             case 0x0800 :
2224                SwapCode = 4321;
2225                Filetype = ACR;
2226                return true;
2227             default :
2228                gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2229                Filetype = Unknown;
2230                return false;
2231          }
2232    }
2233 }
2234
2235 /**
2236  * \brief Change the Byte Swap code. 
2237  */
2238 void Document::SwitchByteSwapCode() 
2239 {
2240    gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
2241    if ( SwapCode == 1234 ) 
2242    {
2243       SwapCode = 4321;
2244    }
2245    else if ( SwapCode == 4321 ) 
2246    {
2247       SwapCode = 1234;
2248    }
2249    else if ( SwapCode == 3412 ) 
2250    {
2251       SwapCode = 2143;
2252    }
2253    else if ( SwapCode == 2143 )
2254    {
2255       SwapCode = 3412;
2256    }
2257 }
2258
2259 /**
2260  * \brief  during parsing, Header Elements too long are not loaded in memory 
2261  * @param newSize
2262  */
2263 void Document::SetMaxSizeLoadEntry(long newSize) 
2264 {
2265    if ( newSize < 0 )
2266    {
2267       return;
2268    }
2269    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2270    {
2271       MaxSizeLoadEntry = 0xffffffff;
2272       return;
2273    }
2274    MaxSizeLoadEntry = newSize;
2275 }
2276
2277
2278 /**
2279  * \brief Header Elements too long will not be printed
2280  * \todo  See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE 
2281  * @param newSize
2282  */
2283 void Document::SetMaxSizePrintEntry(long newSize) 
2284 {
2285    if ( newSize < 0 )
2286    {
2287       return;
2288    }
2289    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2290    {
2291       MaxSizePrintEntry = 0xffffffff;
2292       return;
2293    }
2294    MaxSizePrintEntry = newSize;
2295 }
2296
2297
2298
2299 /**
2300  * \brief   Handle broken private tag from Philips NTSCAN
2301  *          where the endianess is being switch to BigEndian for no
2302  *          apparent reason
2303  * @return  no return
2304  */
2305 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2306 {
2307    // Endian reversion. Some files contain groups of tags with reversed endianess.
2308    static int reversedEndian = 0;
2309    // try to fix endian switching in the middle of headers
2310    if ((group == 0xfeff) && (elem == 0x00e0))
2311    {
2312      // start endian swap mark for group found
2313      reversedEndian++;
2314      SwitchByteSwapCode();
2315      // fix the tag
2316      group = 0xfffe;
2317      elem = 0xe000;
2318    } 
2319    else if (group == 0xfffe && elem == 0xe00d && reversedEndian) 
2320    {
2321      // end of reversed endian group
2322      reversedEndian--;
2323      SwitchByteSwapCode();
2324    }
2325 }
2326
2327 /**
2328  * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
2329  * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
2330  */
2331 std::string Document::GetTransferSyntaxName()
2332 {
2333    // use the TS (TS : Transfer Syntax)
2334    std::string transferSyntax = GetEntry(0x0002,0x0010);
2335
2336    if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
2337    {
2338       gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
2339                << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
2340       return "Uncompressed ACR-NEMA";
2341    }
2342    if ( transferSyntax == GDCM_UNFOUND )
2343    {
2344       gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
2345       return "Uncompressed ACR-NEMA";
2346    }
2347
2348    // we do it only when we need it
2349    const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
2350
2351    // Global::GetTS() is a global static you shall never try to delete it!
2352    return tsName;
2353 }
2354
2355 /**
2356  * \brief   Group 0002 is always coded Little Endian
2357  *          whatever Transfer Syntax is
2358  * @return  no return
2359  */
2360 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2361 {
2362    // Endian reversion. Some files contain groups of tags with reversed endianess.
2363    if ( !Group0002Parsed && group != 0x0002)
2364    {
2365       Group0002Parsed = true;
2366       // we just came out of group 0002
2367       // if Transfer syntax is Big Endian we have to change CheckSwap
2368
2369       std::string ts = GetTransferSyntax();
2370       if ( !Global::GetTS()->IsTransferSyntax(ts) )
2371       {
2372          gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2373          return;
2374       }
2375
2376       // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..." 
2377
2378       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2379          {
2380             Filetype = ImplicitVR;
2381          }
2382        
2383       // FIXME Strangely, this works with 
2384       //'Implicit VR Transfer Syntax (GE Private)
2385       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2386       {
2387          gdcmVerboseMacro("Transfer Syntax Name = [" 
2388                         << GetTransferSyntaxName() << "]" );
2389          SwitchByteSwapCode();
2390          group = SwapShort(group);
2391          elem  = SwapShort(elem);
2392       }
2393    }
2394 }
2395
2396 /**
2397  * \brief   Read the next tag but WITHOUT loading it's value
2398  *          (read the 'Group Number', the 'Element Number',
2399  *          gets the Dict Entry
2400  *          gets the VR, gets the length, gets the offset value)
2401  * @return  On succes the newly created DocEntry, NULL on failure.      
2402  */
2403 DocEntry *Document::ReadNextDocEntry()
2404 {
2405    uint16_t group;
2406    uint16_t elem;
2407
2408    try
2409    {
2410       group = ReadInt16();
2411       elem  = ReadInt16();
2412    }
2413    catch ( FormatError e )
2414    {
2415       // We reached the EOF (or an error occured) therefore 
2416       // header parsing has to be considered as finished.
2417       //std::cout << e;
2418       return 0;
2419    }
2420
2421    // Sometimes file contains groups of tags with reversed endianess.
2422    HandleBrokenEndian(group, elem);
2423
2424 // In 'true DICOM' files Group 0002 is always little endian
2425    if ( HasDCMPreamble )
2426       HandleOutOfGroup0002(group, elem);
2427  
2428    std::string vr = FindDocEntryVR();
2429    std::string realVR = vr;
2430
2431    if( vr == GDCM_UNKNOWN)
2432    {
2433       DictEntry *dictEntry = GetDictEntry(group,elem);
2434       if( dictEntry )
2435          realVR = dictEntry->GetVR();
2436    }
2437
2438    DocEntry *newEntry;
2439    if( Global::GetVR()->IsVROfSequence(realVR) )
2440       newEntry = NewSeqEntry(group, elem);
2441    else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2442       newEntry = NewValEntry(group, elem,vr);
2443    else
2444       newEntry = NewBinEntry(group, elem,vr);
2445
2446    if( vr == GDCM_UNKNOWN )
2447    {
2448       if( Filetype == ExplicitVR )
2449       {
2450          // We thought this was explicit VR, but we end up with an
2451          // implicit VR tag. Let's backtrack.
2452          if ( newEntry->GetGroup() != 0xfffe )
2453          { 
2454             std::string msg;
2455             msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n", 
2456                           newEntry->GetGroup(), newEntry->GetElement());
2457             gdcmVerboseMacro( msg.c_str() );
2458           }
2459       }
2460       newEntry->SetImplicitVR();
2461    }
2462
2463    try
2464    {
2465       FindDocEntryLength(newEntry);
2466    }
2467    catch ( FormatError e )
2468    {
2469       // Call it quits
2470       //std::cout << e;
2471       delete newEntry;
2472       return 0;
2473    }
2474
2475    newEntry->SetOffset(Fp->tellg());  
2476
2477    return newEntry;
2478 }
2479
2480
2481 /**
2482  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2483  *          in the TagHt dictionary.
2484  * @param   group The generated tag must belong to this group.  
2485  * @return  The element of tag with given group which is fee.
2486  */
2487 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group) 
2488 {
2489    for (uint32_t elem = 0; elem < UINT32_MAX; elem++) 
2490    {
2491       TagKey key = DictEntry::TranslateToKey(group, elem);
2492       if (TagHT.count(key) == 0)
2493       {
2494          return elem;
2495       }
2496    }
2497    return UINT32_MAX;
2498 }
2499
2500 /**
2501  * \brief   Assuming the internal file pointer \ref Document::Fp 
2502  *          is placed at the beginning of a tag check whether this
2503  *          tag is (TestGroup, TestElement).
2504  * \warning On success the internal file pointer \ref Document::Fp
2505  *          is modified to point after the tag.
2506  *          On failure (i.e. when the tag wasn't the expected tag
2507  *          (TestGroup, TestElement) the internal file pointer
2508  *          \ref Document::Fp is restored to it's original position.
2509  * @param   testGroup   The expected group of the tag.
2510  * @param   testElement The expected Element of the tag.
2511  * @return  True on success, false otherwise.
2512  */
2513 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2514 {
2515    long positionOnEntry = Fp->tellg();
2516    long currentPosition = Fp->tellg();          // On debugging purposes
2517
2518    //// Read the Item Tag group and element, and make
2519    // sure they are what we expected:
2520    uint16_t itemTagGroup;
2521    uint16_t itemTagElement;
2522    try
2523    {
2524       itemTagGroup   = ReadInt16();
2525       itemTagElement = ReadInt16();
2526    }
2527    catch ( FormatError e )
2528    {
2529       //std::cerr << e << std::endl;
2530       return false;
2531    }
2532    if ( itemTagGroup != testGroup || itemTagElement != testElement )
2533    {
2534       gdcmVerboseMacro( "Wrong Item Tag found:"
2535        << "   We should have found tag ("
2536        << std::hex << testGroup << "," << testElement << ")" << std::endl
2537        << "   but instead we encountered tag ("
2538        << std::hex << itemTagGroup << "," << itemTagElement << ")"
2539        << "  at address: " << "  0x(" << (unsigned int)currentPosition  << ")" 
2540        ) ;
2541       Fp->seekg(positionOnEntry, std::ios::beg);
2542
2543       return false;
2544    }
2545    return true;
2546 }
2547
2548 /**
2549  * \brief   Assuming the internal file pointer \ref Document::Fp 
2550  *          is placed at the beginning of a tag (TestGroup, TestElement),
2551  *          read the length associated to the Tag.
2552  * \warning On success the internal file pointer \ref Document::Fp
2553  *          is modified to point after the tag and it's length.
2554  *          On failure (i.e. when the tag wasn't the expected tag
2555  *          (TestGroup, TestElement) the internal file pointer
2556  *          \ref Document::Fp is restored to it's original position.
2557  * @param   testGroup   The expected group of the tag.
2558  * @param   testElement The expected Element of the tag.
2559  * @return  On success returns the length associated to the tag. On failure
2560  *          returns 0.
2561  */
2562 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2563 {
2564
2565    if ( !ReadTag(testGroup, testElement) )
2566    {
2567       return 0;
2568    }
2569                                                                                 
2570    //// Then read the associated Item Length
2571    long currentPosition = Fp->tellg();
2572    uint32_t itemLength  = ReadInt32();
2573    {
2574       gdcmVerboseMacro( "Basic Item Length is: "
2575         << itemLength << std::endl
2576         << "  at address: " << std::hex << (unsigned int)currentPosition);
2577    }
2578    return itemLength;
2579 }
2580
2581 /**
2582  * \brief When parsing the Pixel Data of an encapsulated file, read
2583  *        the basic offset table (when present, and BTW dump it).
2584  */
2585 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2586 {
2587    //// Read the Basic Offset Table Item Tag length...
2588    uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2589
2590    // When present, read the basic offset table itself.
2591    // Notes: - since the presence of this basic offset table is optional
2592    //          we can't rely on it for the implementation, and we will simply
2593    //          trash it's content (when present).
2594    //        - still, when present, we could add some further checks on the
2595    //          lengths, but we won't bother with such fuses for the time being.
2596    if ( itemLength != 0 )
2597    {
2598       char *basicOffsetTableItemValue = new char[itemLength + 1];
2599       Fp->read(basicOffsetTableItemValue, itemLength);
2600
2601 #ifdef GDCM_DEBUG
2602       for (unsigned int i=0; i < itemLength; i += 4 )
2603       {
2604          uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2605                                               uint32_t);
2606          gdcmVerboseMacro( "Read one length: " << 
2607                           std::hex << individualLength );
2608       }
2609 #endif //GDCM_DEBUG
2610
2611       delete[] basicOffsetTableItemValue;
2612    }
2613 }
2614
2615 /**
2616  * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2617  *        Compute the RLE extra information and store it in \ref RLEInfo
2618  *        for later pixel retrieval usage.
2619  */
2620 void Document::ComputeRLEInfo()
2621 {
2622    std::string ts = GetTransferSyntax();
2623    if ( !Global::GetTS()->IsRLELossless(ts) ) 
2624    {
2625       return;
2626    }
2627
2628    // Encoded pixel data: for the time being we are only concerned with
2629    // Jpeg or RLE Pixel data encodings.
2630    // As stated in PS 3.5-2003, section 8.2 p44:
2631    // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2632    //  value representation OB is used".
2633    // Hence we expect an OB value representation. Concerning OB VR,
2634    // the section PS 3.5-2003, section A.4.c p 58-59, states:
2635    // "For the Value Representations OB and OW, the encoding shall meet the
2636    //   following specifications depending on the Data element tag:"
2637    //   [...snip...]
2638    //    - the first item in the sequence of items before the encoded pixel
2639    //      data stream shall be basic offset table item. The basic offset table
2640    //      item value, however, is not required to be present"
2641
2642    ReadAndSkipEncapsulatedBasicOffsetTable();
2643
2644    // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2645    // Loop on the individual frame[s] and store the information
2646    // on the RLE fragments in a RLEFramesInfo.
2647    // Note: - when only a single frame is present, this is a
2648    //         classical image.
2649    //       - when more than one frame are present, then we are in 
2650    //         the case of a multi-frame image.
2651    long frameLength;
2652    while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2653    { 
2654       // Parse the RLE Header and store the corresponding RLE Segment
2655       // Offset Table information on fragments of this current Frame.
2656       // Note that the fragment pixels themselves are not loaded
2657       // (but just skipped).
2658       long frameOffset = Fp->tellg();
2659
2660       uint32_t nbRleSegments = ReadInt32();
2661       if ( nbRleSegments > 16 )
2662       {
2663          // There should be at most 15 segments (refer to RLEFrame class)
2664          gdcmVerboseMacro( "Too many segments.");
2665       }
2666  
2667       uint32_t rleSegmentOffsetTable[16];
2668       for( int k = 1; k <= 15; k++ )
2669       {
2670          rleSegmentOffsetTable[k] = ReadInt32();
2671       }
2672
2673       // Deduce from both the RLE Header and the frameLength the
2674       // fragment length, and again store this info in a
2675       // RLEFramesInfo.
2676       long rleSegmentLength[15];
2677       // skipping (not reading) RLE Segments
2678       if ( nbRleSegments > 1)
2679       {
2680          for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2681          {
2682              rleSegmentLength[k] =  rleSegmentOffsetTable[k+1]
2683                                   - rleSegmentOffsetTable[k];
2684              SkipBytes(rleSegmentLength[k]);
2685           }
2686        }
2687
2688        rleSegmentLength[nbRleSegments] = frameLength 
2689                                       - rleSegmentOffsetTable[nbRleSegments];
2690        SkipBytes(rleSegmentLength[nbRleSegments]);
2691
2692        // Store the collected info
2693        RLEFrame *newFrameInfo = new RLEFrame;
2694        newFrameInfo->NumberFragments = nbRleSegments;
2695        for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2696        {
2697           newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2698           newFrameInfo->Length[uk] = rleSegmentLength[uk];
2699        }
2700        RLEInfo->Frames.push_back( newFrameInfo );
2701    }
2702
2703    // Make sure that at the end of the item we encounter a 'Sequence
2704    // Delimiter Item':
2705    if ( !ReadTag(0xfffe, 0xe0dd) )
2706    {
2707       gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2708    }
2709 }
2710
2711 /**
2712  * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2713  *        Compute the jpeg extra information (fragment[s] offset[s] and
2714  *        length) and store it[them] in \ref JPEGInfo for later pixel
2715  *        retrieval usage.
2716  */
2717 void Document::ComputeJPEGFragmentInfo()
2718 {
2719    // If you need to, look for comments of ComputeRLEInfo().
2720    std::string ts = GetTransferSyntax();
2721    if ( ! Global::GetTS()->IsJPEG(ts) )
2722    {
2723       return;
2724    }
2725
2726    ReadAndSkipEncapsulatedBasicOffsetTable();
2727
2728    // Loop on the fragments[s] and store the parsed information in a
2729    // JPEGInfo.
2730    long fragmentLength;
2731    while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2732    { 
2733       long fragmentOffset = Fp->tellg();
2734
2735        // Store the collected info
2736        JPEGFragment *newFragment = new JPEGFragment;
2737        newFragment->Offset = fragmentOffset;
2738        newFragment->Length = fragmentLength;
2739        JPEGInfo->Fragments.push_back( newFragment );
2740
2741        SkipBytes( fragmentLength );
2742    }
2743
2744    // Make sure that at the end of the item we encounter a 'Sequence
2745    // Delimiter Item':
2746    if ( !ReadTag(0xfffe, 0xe0dd) )
2747    {
2748       gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2749    }
2750 }
2751
2752 /**
2753  * \brief Walk recursively the given \ref DocEntrySet, and feed
2754  *        the given hash table (\ref TagDocEntryHT) with all the
2755  *        \ref DocEntry (Dicom entries) encountered.
2756  *        This method does the job for \ref BuildFlatHashTable.
2757  * @param builtHT Where to collect all the \ref DocEntry encountered
2758  *        when recursively walking the given set.
2759  * @param set The structure to be traversed (recursively).
2760  */
2761 /*void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2762                                           DocEntrySet *set )
2763
2764    if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2765    {
2766       TagDocEntryHT const &currentHT = elementSet->GetTagHT();
2767       for( TagDocEntryHT::const_iterator i  = currentHT.begin();
2768                                          i != currentHT.end();
2769                                        ++i)
2770       {
2771          DocEntry *entry = i->second;
2772          if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2773          {
2774             const ListSQItem& items = seqEntry->GetSQItems();
2775             for( ListSQItem::const_iterator item  = items.begin();
2776                                             item != items.end();
2777                                           ++item)
2778             {
2779                BuildFlatHashTableRecurse( builtHT, *item );
2780             }
2781             continue;
2782          }
2783          builtHT[entry->GetKey()] = entry;
2784       }
2785       return;
2786     }
2787
2788    if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2789    {
2790       const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2791       for (ListDocEntry::const_iterator i  = currentList.begin();
2792                                         i != currentList.end();
2793                                       ++i)
2794       {
2795          DocEntry *entry = *i;
2796          if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2797          {
2798             const ListSQItem& items = seqEntry->GetSQItems();
2799             for( ListSQItem::const_iterator item  = items.begin();
2800                                             item != items.end();
2801                                           ++item)
2802             {
2803                BuildFlatHashTableRecurse( builtHT, *item );
2804             }
2805             continue;
2806          }
2807          builtHT[entry->GetKey()] = entry;
2808       }
2809
2810    }
2811 }*/
2812
2813 /**
2814  * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2815  *        Document.
2816  *
2817  *        The structure used by a Document (through \ref ElementSet),
2818  *        in order to hold the parsed entries of a Dicom header, is a recursive
2819  *        one. This is due to the fact that the sequences (when present)
2820  *        can be nested. Additionaly, the sequence items (represented in
2821  *        gdcm as \ref SQItem) add an extra complexity to the data
2822  *        structure. Hence, a gdcm user whishing to visit all the entries of
2823  *        a Dicom header will need to dig in the gdcm internals (which
2824  *        implies exposing all the internal data structures to the API).
2825  *        In order to avoid this burden to the user, \ref BuildFlatHashTable
2826  *        recursively builds a temporary hash table, which holds all the
2827  *        Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2828  *        std::map<>).
2829  * \warning Of course there is NO integrity constrain between the 
2830  *        returned \ref TagDocEntryHT and the \ref ElementSet used
2831  *        to build it. Hence if the underlying \ref ElementSet is
2832  *        altered, then it is the caller responsability to invoke 
2833  *        \ref BuildFlatHashTable again...
2834  * @return The flat std::map<> we juste build.
2835  */
2836 /*TagDocEntryHT *Document::BuildFlatHashTable()
2837 {
2838    TagDocEntryHT *FlatHT = new TagDocEntryHT;
2839    BuildFlatHashTableRecurse( *FlatHT, this );
2840    return FlatHT;
2841 }*/
2842
2843
2844
2845 /**
2846  * \brief   Compares two documents, according to \ref DicomDir rules
2847  * \warning Does NOT work with ACR-NEMA files
2848  * \todo    Find a trick to solve the pb (use RET fields ?)
2849  * @param   document
2850  * @return  true if 'smaller'
2851  */
2852 bool Document::operator<(Document &document)
2853 {
2854    // Patient Name
2855    std::string s1 = GetEntry(0x0010,0x0010);
2856    std::string s2 = document.GetEntry(0x0010,0x0010);
2857    if(s1 < s2)
2858    {
2859       return true;
2860    }
2861    else if( s1 > s2 )
2862    {
2863       return false;
2864    }
2865    else
2866    {
2867       // Patient ID
2868       s1 = GetEntry(0x0010,0x0020);
2869       s2 = document.GetEntry(0x0010,0x0020);
2870       if ( s1 < s2 )
2871       {
2872          return true;
2873       }
2874       else if ( s1 > s2 )
2875       {
2876          return false;
2877       }
2878       else
2879       {
2880          // Study Instance UID
2881          s1 = GetEntry(0x0020,0x000d);
2882          s2 = document.GetEntry(0x0020,0x000d);
2883          if ( s1 < s2 )
2884          {
2885             return true;
2886          }
2887          else if( s1 > s2 )
2888          {
2889             return false;
2890          }
2891          else
2892          {
2893             // Serie Instance UID
2894             s1 = GetEntry(0x0020,0x000e);
2895             s2 = document.GetEntry(0x0020,0x000e);    
2896             if ( s1 < s2 )
2897             {
2898                return true;
2899             }
2900             else if( s1 > s2 )
2901             {
2902                return false;
2903             }
2904          }
2905       }
2906    }
2907    return false;
2908 }
2909
2910
2911 /**
2912  * \brief   Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
2913  * @param filetype Type of the File to be written 
2914  */
2915 int Document::ComputeGroup0002Length( FileType filetype ) 
2916 {
2917    uint16_t gr, el;
2918    std::string vr;
2919    
2920    int groupLength = 0;
2921    bool found0002 = false;   
2922   
2923    // for each zero-level Tag in the DCM Header
2924    DocEntry *entry = GetFirstEntry();
2925    while(entry)
2926    {
2927       gr = entry->GetGroup();
2928
2929       if (gr == 0x0002)
2930       {
2931          found0002 = true;
2932
2933          el = entry->GetElement();
2934          vr = entry->GetVR();            
2935  
2936          if (filetype == ExplicitVR) 
2937          {
2938             if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) 
2939             {
2940                groupLength +=  4; // explicit VR AND OB, OW, SQ : 4 more bytes
2941             }
2942          }
2943          groupLength += 2 + 2 + 4 + entry->GetLength();   
2944       }
2945       else if (found0002 )
2946          break;
2947
2948       entry = GetNextEntry();
2949    }
2950    return groupLength; 
2951 }
2952
2953 } // end namespace gdcm
2954
2955 //-----------------------------------------------------------------------------