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