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