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