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