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