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