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