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