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