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