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