]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
73c7ecf74cd10d2e3c127b600eb3b826b9f09c68
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/11/25 10:24:34 $
7   Version:   $Revision: 1.138 $
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    if(Fp)
1290    {
1291       long PositionOnEntry = Fp->tellg();
1292       LoadDocEntry(entry);
1293       Fp->seekg(PositionOnEntry, std::ios_base::beg);
1294    }
1295 }
1296
1297 /**
1298  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1299  *          processor order.
1300  * @return  The properly swaped 32 bits integer.
1301  */
1302 uint32_t Document::SwapLong(uint32_t a)
1303 {
1304    switch (SwapCode)
1305    {
1306       case    0 :
1307          break;
1308       case 4321 :
1309          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
1310              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1311          break;
1312    
1313       case 3412 :
1314          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1315          break;
1316    
1317       case 2143 :
1318          a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1319          break;
1320       default :
1321          //std::cout << "swapCode= " << SwapCode << std::endl;
1322          dbg.Error(" Document::SwapLong : unset swap code");
1323          a = 0;
1324    }
1325    return a;
1326
1327
1328 /**
1329  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
1330  *          processor order.
1331  * @return  The properly unswaped 32 bits integer.
1332  */
1333 uint32_t Document::UnswapLong(uint32_t a)
1334 {
1335    return SwapLong(a);
1336 }
1337
1338 /**
1339  * \brief   Swaps the bytes so they agree with the processor order
1340  * @return  The properly swaped 16 bits integer.
1341  */
1342 uint16_t Document::SwapShort(uint16_t a)
1343 {
1344    if ( SwapCode == 4321 || SwapCode == 2143 )
1345    {
1346       a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1347    }
1348    return a;
1349 }
1350
1351 /**
1352  * \brief   Unswaps the bytes so they agree with the processor order
1353  * @return  The properly unswaped 16 bits integer.
1354  */
1355 uint16_t Document::UnswapShort(uint16_t a)
1356 {
1357    return SwapShort(a);
1358 }
1359
1360 //-----------------------------------------------------------------------------
1361 // Private
1362
1363 /**
1364  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1365  * @return  length of the parsed set. 
1366  */ 
1367 void Document::ParseDES(DocEntrySet *set, long offset, 
1368                         long l_max, bool delim_mode)
1369 {
1370    DocEntry *newDocEntry = 0;
1371
1372    while (true)
1373    {
1374       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1375       {
1376          break;
1377       }
1378       newDocEntry = ReadNextDocEntry( );
1379       if ( !newDocEntry )
1380       {
1381          break;
1382       }
1383
1384       VRKey vr = newDocEntry->GetVR();
1385       if ( vr != "SQ" )
1386       {
1387                
1388          if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1389          {
1390          /////////////////////// ValEntry
1391             ValEntry* newValEntry =
1392                new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1393             newValEntry->Copy( newDocEntry );
1394              
1395             // When "set" is a Document, then we are at the top of the
1396             // hierarchy and the Key is simply of the form ( group, elem )...
1397             if (Document* dummy = dynamic_cast< Document* > ( set ) )
1398             {
1399                (void)dummy;
1400                newValEntry->SetKey( newValEntry->GetKey() );
1401             }
1402             // ...but when "set" is a SQItem, we are inserting this new
1403             // valEntry in a sequence item. Hence the key has the
1404             // generalized form (refer to \ref BaseTagKey):
1405             if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1406             {
1407                newValEntry->SetKey(  parentSQItem->GetBaseTagKey()
1408                                    + newValEntry->GetKey() );
1409             }
1410              
1411             LoadDocEntry( newValEntry );
1412             bool delimitor=newValEntry->IsItemDelimitor();
1413             if( !set->AddEntry( newValEntry ) )
1414             {
1415               // If here expect big troubles
1416               delete newValEntry; //otherwise mem leak
1417             }
1418
1419             if (delimitor)
1420             {
1421                delete newDocEntry;
1422                break;
1423             }
1424             if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1425             {
1426                delete newDocEntry;
1427                break;
1428             }
1429          }
1430          else
1431          {
1432             if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1433             { 
1434                 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1435                 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1436                                "nor BinEntry. Probably unknown VR.");
1437             }
1438
1439          //////////////////// BinEntry or UNKOWN VR:
1440 /*            BinEntry* newBinEntry =
1441                new BinEntry( newDocEntry->GetDictEntry() );  //LEAK
1442             newBinEntry->Copy( newDocEntry );*/
1443             BinEntry* newBinEntry = new BinEntry( newDocEntry );  //LEAK
1444
1445             // When "this" is a Document the Key is simply of the
1446             // form ( group, elem )...
1447             if (Document* dummy = dynamic_cast< Document* > ( set ) )
1448             {
1449                (void)dummy;
1450                newBinEntry->SetKey( newBinEntry->GetKey() );
1451             }
1452             // but when "this" is a SQItem, we are inserting this new
1453             // valEntry in a sequence item, and the kay has the
1454             // generalized form (refer to \ref BaseTagKey):
1455             if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1456             {
1457                newBinEntry->SetKey(  parentSQItem->GetBaseTagKey()
1458                                    + newBinEntry->GetKey() );
1459             }
1460
1461             LoadDocEntry( newBinEntry );
1462             if( !set->AddEntry( newBinEntry ) )
1463             {
1464               //Expect big troubles if here
1465               delete newBinEntry;
1466             }
1467          }
1468
1469          if (    ( newDocEntry->GetGroup()   == 0x7fe0 )
1470               && ( newDocEntry->GetElement() == 0x0010 ) )
1471          {
1472              TransferSyntaxType ts = GetTransferSyntax();
1473              if ( ts == RLELossless ) 
1474              {
1475                 long PositionOnEntry = Fp->tellg();
1476                 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1477                 ComputeRLEInfo();
1478                 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1479              }
1480              else if ( IsJPEG() )
1481              {
1482                 long PositionOnEntry = Fp->tellg();
1483                 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1484                 ComputeJPEGFragmentInfo();
1485                 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1486              }
1487          }
1488     
1489          // Just to make sure we are at the beginning of next entry.
1490          SkipToNextDocEntry(newDocEntry);
1491          //delete newDocEntry;
1492       }
1493       else
1494       {
1495          // VR = "SQ"
1496          unsigned long l = newDocEntry->GetReadLength();            
1497          if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1498          {
1499             if ( l == 0xffffffff )
1500             {
1501               delim_mode = true;
1502             }
1503             else
1504             {
1505               delim_mode = false;
1506             }
1507          }
1508          // no other way to create it ...
1509          SeqEntry* newSeqEntry =
1510             new SeqEntry( newDocEntry->GetDictEntry() );
1511          newSeqEntry->Copy( newDocEntry );
1512          newSeqEntry->SetDelimitorMode( delim_mode );
1513
1514          // At the top of the hierarchy, stands a Document. When "set"
1515          // is a Document, then we are building the first depth level.
1516          // Hence the SeqEntry we are building simply has a depth
1517          // level of one:
1518          if (Document* dummy = dynamic_cast< Document* > ( set ) )
1519          {
1520             (void)dummy;
1521             newSeqEntry->SetDepthLevel( 1 );
1522             newSeqEntry->SetKey( newSeqEntry->GetKey() );
1523          }
1524          // But when "set" is allready a SQItem, we are building a nested
1525          // sequence, and hence the depth level of the new SeqEntry
1526          // we are building, is one level deeper:
1527          if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1528          {
1529             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1530             newSeqEntry->SetKey(  parentSQItem->GetBaseTagKey()
1531                                 + newSeqEntry->GetKey() );
1532          }
1533
1534          if ( l != 0 )
1535          {  // Don't try to parse zero-length sequences
1536             ParseSQ( newSeqEntry, 
1537                      newDocEntry->GetOffset(),
1538                      l, delim_mode);
1539          }
1540          set->AddEntry( newSeqEntry );
1541          if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1542          {
1543             delete newDocEntry;
1544             break;
1545          }
1546       }
1547       delete newDocEntry;
1548    }
1549 }
1550
1551 /**
1552  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1553  * @return  parsed length for this level
1554  */ 
1555 void Document::ParseSQ( SeqEntry* seqEntry,
1556                         long offset, long l_max, bool delim_mode)
1557 {
1558    int SQItemNumber = 0;
1559    bool dlm_mod;
1560
1561    while (true)
1562    {
1563       DocEntry* newDocEntry = ReadNextDocEntry();   
1564       if ( !newDocEntry )
1565       {
1566          // FIXME Should warn user
1567          break;
1568       }
1569       if( delim_mode )
1570       {
1571          if ( newDocEntry->IsSequenceDelimitor() )
1572          {
1573             seqEntry->SetSequenceDelimitationItem( newDocEntry ); 
1574             break;
1575          }
1576       }
1577       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1578       {
1579          delete newDocEntry;
1580          break;
1581       }
1582
1583       SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1584       std::ostringstream newBase;
1585       newBase << seqEntry->GetKey()
1586               << "/"
1587               << SQItemNumber
1588               << "#";
1589       itemSQ->SetBaseTagKey( newBase.str() );
1590       unsigned int l = newDocEntry->GetReadLength();
1591       
1592       if ( l == 0xffffffff )
1593       {
1594          dlm_mod = true;
1595       }
1596       else
1597       {
1598          dlm_mod = false;
1599       }
1600    
1601       ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1602       delete newDocEntry;
1603       
1604       seqEntry->AddEntry( itemSQ, SQItemNumber ); 
1605       SQItemNumber++;
1606       if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1607       {
1608          break;
1609       }
1610    }
1611 }
1612
1613 /**
1614  * \brief         Loads the element content if its length doesn't exceed
1615  *                the value specified with Document::SetMaxSizeLoadEntry()
1616  * @param         entry Header Entry (Dicom Element) to be dealt with
1617  */
1618 void Document::LoadDocEntry(DocEntry* entry)
1619 {
1620    uint16_t group  = entry->GetGroup();
1621    std::string  vr = entry->GetVR();
1622    uint32_t length = entry->GetLength();
1623
1624    Fp->seekg((long)entry->GetOffset(), std::ios_base::beg);
1625
1626    // A SeQuence "contains" a set of Elements.  
1627    //          (fffe e000) tells us an Element is beginning
1628    //          (fffe e00d) tells us an Element just ended
1629    //          (fffe e0dd) tells us the current SeQuence just ended
1630    if( group == 0xfffe )
1631    {
1632       // NO more value field for SQ !
1633       return;
1634    }
1635
1636    // When the length is zero things are easy:
1637    if ( length == 0 )
1638    {
1639       ((ValEntry *)entry)->SetValue("");
1640       return;
1641    }
1642
1643    // The elements whose length is bigger than the specified upper bound
1644    // are not loaded. Instead we leave a short notice of the offset of
1645    // the element content and it's length.
1646
1647    std::ostringstream s;
1648    if (length > MaxSizeLoadEntry)
1649    {
1650       if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1651       {  
1652          //s << "gdcm::NotLoaded (BinEntry)";
1653          s << GDCM_NOTLOADED;
1654          s << " Address:" << (long)entry->GetOffset();
1655          s << " Length:"  << entry->GetLength();
1656          s << " x(" << std::hex << entry->GetLength() << ")";
1657          binEntryPtr->SetValue(s.str());
1658       }
1659       // Be carefull : a BinEntry IS_A ValEntry ... 
1660       else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1661       {
1662         // s << "gdcm::NotLoaded. (ValEntry)";
1663          s << GDCM_NOTLOADED;  
1664          s << " Address:" << (long)entry->GetOffset();
1665          s << " Length:"  << entry->GetLength();
1666          s << " x(" << std::hex << entry->GetLength() << ")";
1667          valEntryPtr->SetValue(s.str());
1668       }
1669       else
1670       {
1671          // fusible
1672          std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1673                   << "nor a ValEntry ?! Should never print that !" << std::endl;
1674       }
1675
1676       // to be sure we are at the end of the value ...
1677       Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1678                 std::ios_base::beg);
1679       return;
1680    }
1681
1682    // When we find a BinEntry not very much can be done :
1683    if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1684    {
1685       s << GDCM_BINLOADED;
1686       binEntryPtr->SetValue(s.str());
1687       LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1688       return;
1689    }
1690     
1691    /// \todo Any compacter code suggested (?)
1692    if ( IsDocEntryAnInteger(entry) )
1693    {   
1694       uint32_t NewInt;
1695       int nbInt;
1696       // When short integer(s) are expected, read and convert the following 
1697       // n *two characters properly i.e. consider them as short integers as
1698       // opposed to strings.
1699       // Elements with Value Multiplicity > 1
1700       // contain a set of integers (not a single one)       
1701       if (vr == "US" || vr == "SS")
1702       {
1703          nbInt = length / 2;
1704          NewInt = ReadInt16();
1705          s << NewInt;
1706          if (nbInt > 1)
1707          {
1708             for (int i=1; i < nbInt; i++)
1709             {
1710                s << '\\';
1711                NewInt = ReadInt16();
1712                s << NewInt;
1713             }
1714          }
1715       }
1716       // See above comment on multiple integers (mutatis mutandis).
1717       else if (vr == "UL" || vr == "SL")
1718       {
1719          nbInt = length / 4;
1720          NewInt = ReadInt32();
1721          s << NewInt;
1722          if (nbInt > 1)
1723          {
1724             for (int i=1; i < nbInt; i++)
1725             {
1726                s << '\\';
1727                NewInt = ReadInt32();
1728                s << NewInt;
1729             }
1730          }
1731       }
1732 #ifdef GDCM_NO_ANSI_STRING_STREAM
1733       s << std::ends; // to avoid oddities on Solaris
1734 #endif //GDCM_NO_ANSI_STRING_STREAM
1735
1736       ((ValEntry *)entry)->SetValue(s.str());
1737       return;
1738    }
1739    
1740   // FIXME: We need an additional byte for storing \0 that is not on disk
1741    char *str = new char[length+1];
1742    Fp->read(str, (size_t)length);
1743    str[length] = '\0'; //this is only useful when length is odd
1744    // Special DicomString call to properly handle \0 and even length
1745    std::string newValue;
1746    if( length % 2 )
1747    {
1748       newValue = Util::DicomString(str, length+1);
1749       //dbg.Verbose(0, "Warning: bad length: ", length );
1750       dbg.Verbose(0, "For string :",  newValue.c_str()); 
1751       // Since we change the length of string update it length
1752       entry->SetReadLength(length+1);
1753    }
1754    else
1755    {
1756       newValue = Util::DicomString(str, length);
1757    }
1758    delete[] str;
1759
1760    if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1761    {
1762       if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1763       {
1764          dbg.Verbose(1, "Document::LoadDocEntry",
1765                         "unread element value");
1766          valEntry->SetValue(GDCM_UNREAD);
1767          return;
1768       }
1769
1770       if( vr == "UI" )
1771       {
1772          // Because of correspondance with the VR dic
1773          valEntry->SetValue(newValue);
1774       }
1775       else
1776       {
1777          valEntry->SetValue(newValue);
1778       }
1779    }
1780    else
1781    {
1782       dbg.Error(true, "Document::LoadDocEntry"
1783                       "Should have a ValEntry, here !");
1784    }
1785 }
1786
1787
1788 /**
1789  * \brief  Find the value Length of the passed Header Entry
1790  * @param  entry Header Entry whose length of the value shall be loaded. 
1791  */
1792 void Document::FindDocEntryLength( DocEntry *entry )
1793    throw ( FormatError )
1794 {
1795    uint16_t element = entry->GetElement();
1796    std::string  vr  = entry->GetVR();
1797    uint16_t length16;       
1798    
1799    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1800    {
1801       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" ) 
1802       {
1803          // The following reserved two bytes (see PS 3.5-2003, section
1804          // "7.1.2 Data element structure with explicit vr", p 27) must be
1805          // skipped before proceeding on reading the length on 4 bytes.
1806          Fp->seekg( 2L, std::ios_base::cur);
1807          uint32_t length32 = ReadInt32();
1808
1809          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1810          {
1811             uint32_t lengthOB;
1812             try 
1813             {
1814                /// \todo rename that to FindDocEntryLengthOBOrOW since
1815                ///       the above test is on both OB and OW...
1816                lengthOB = FindDocEntryLengthOB();
1817             }
1818             catch ( FormatUnexpected )
1819             {
1820                // Computing the length failed (this happens with broken
1821                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1822                // chance to get the pixels by deciding the element goes
1823                // until the end of the file. Hence we artificially fix the
1824                // the length and proceed.
1825                long currentPosition = Fp->tellg();
1826                Fp->seekg(0L,std::ios_base::end);
1827                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1828                Fp->seekg(currentPosition, std::ios_base::beg);
1829                entry->SetLength(lengthUntilEOF);
1830                return;
1831             }
1832             entry->SetLength(lengthOB);
1833             return;
1834          }
1835          FixDocEntryFoundLength(entry, length32); 
1836          return;
1837       }
1838
1839       // Length is encoded on 2 bytes.
1840       length16 = ReadInt16();
1841       
1842       // We can tell the current file is encoded in big endian (like
1843       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1844       // and it's value is the one of the encoding of a big endian file.
1845       // In order to deal with such big endian encoded files, we have
1846       // (at least) two strategies:
1847       // * when we load the "Transfer Syntax" tag with value of big endian
1848       //   encoding, we raise the proper flags. Then we wait for the end
1849       //   of the META group (0x0002) among which is "Transfer Syntax",
1850       //   before switching the swap code to big endian. We have to postpone
1851       //   the switching of the swap code since the META group is fully encoded
1852       //   in little endian, and big endian coding only starts at the next
1853       //   group. The corresponding code can be hard to analyse and adds
1854       //   many additional unnecessary tests for regular tags.
1855       // * the second strategy consists in waiting for trouble, that shall
1856       //   appear when we find the first group with big endian encoding. This
1857       //   is easy to detect since the length of a "Group Length" tag (the
1858       //   ones with zero as element number) has to be of 4 (0x0004). When we
1859       //   encounter 1024 (0x0400) chances are the encoding changed and we
1860       //   found a group with big endian encoding.
1861       // We shall use this second strategy. In order to make sure that we
1862       // can interpret the presence of an apparently big endian encoded
1863       // length of a "Group Length" without committing a big mistake, we
1864       // add an additional check: we look in the already parsed elements
1865       // for the presence of a "Transfer Syntax" whose value has to be "big
1866       // endian encoding". When this is the case, chances are we have got our
1867       // hands on a big endian encoded file: we switch the swap code to
1868       // big endian and proceed...
1869       if ( element  == 0x0000 && length16 == 0x0400 ) 
1870       {
1871          TransferSyntaxType ts = GetTransferSyntax();
1872          if ( ts != ExplicitVRBigEndian ) 
1873          {
1874             throw FormatError( "Document::FindDocEntryLength()",
1875                                " not explicit VR." );
1876             return;
1877          }
1878          length16 = 4;
1879          SwitchSwapToBigEndian();
1880          // Restore the unproperly loaded values i.e. the group, the element
1881          // and the dictionary entry depending on them.
1882          uint16_t correctGroup = SwapShort( entry->GetGroup() );
1883          uint16_t correctElem  = SwapShort( entry->GetElement() );
1884          DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1885                                                        correctElem );
1886          if ( !newTag )
1887          {
1888             // This correct tag is not in the dictionary. Create a new one.
1889             newTag = NewVirtualDictEntry(correctGroup, correctElem);
1890          }
1891          // FIXME this can create a memory leaks on the old entry that be
1892          // left unreferenced.
1893          entry->SetDictEntry( newTag );
1894       }
1895        
1896       // Heuristic: well, some files are really ill-formed.
1897       if ( length16 == 0xffff) 
1898       {
1899          // 0xffff means that we deal with 'Unknown Length' Sequence  
1900          length16 = 0;
1901       }
1902       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1903       return;
1904    }
1905    else
1906    {
1907       // Either implicit VR or a non DICOM conformal (see note below) explicit
1908       // VR that ommited the VR of (at least) this element. Farts happen.
1909       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1910       // on Data elements "Implicit and Explicit VR Data Elements shall
1911       // not coexist in a Data Set and Data Sets nested within it".]
1912       // Length is on 4 bytes.
1913       
1914       FixDocEntryFoundLength( entry, ReadInt32() );
1915       return;
1916    }
1917 }
1918
1919 /**
1920  * \brief     Find the Value Representation of the current Dicom Element.
1921  * @param     entry
1922  */
1923 void Document::FindDocEntryVR( DocEntry *entry )
1924 {
1925    if ( Filetype != ExplicitVR )
1926    {
1927       return;
1928    }
1929
1930    char vr[3];
1931
1932    long positionOnEntry = Fp->tellg();
1933    // Warning: we believe this is explicit VR (Value Representation) because
1934    // we used a heuristic that found "UL" in the first tag. Alas this
1935    // doesn't guarantee that all the tags will be in explicit VR. In some
1936    // cases (see e-film filtered files) one finds implicit VR tags mixed
1937    // within an explicit VR file. Hence we make sure the present tag
1938    // is in explicit VR and try to fix things if it happens not to be
1939    // the case.
1940    
1941    Fp->read (vr, (size_t)2);
1942    vr[2] = 0;
1943
1944    if( !CheckDocEntryVR(entry, vr) )
1945    {
1946       Fp->seekg(positionOnEntry, std::ios_base::beg);
1947       // When this element is known in the dictionary we shall use, e.g. for
1948       // the semantics (see the usage of IsAnInteger), the VR proposed by the
1949       // dictionary entry. Still we have to flag the element as implicit since
1950       // we know now our assumption on expliciteness is not furfilled.
1951       // avoid  .
1952       if ( entry->IsVRUnknown() )
1953       {
1954          entry->SetVR("Implicit");
1955       }
1956       entry->SetImplicitVR();
1957    }
1958 }
1959
1960 /**
1961  * \brief     Check the correspondance between the VR of the header entry
1962  *            and the taken VR. If they are different, the header entry is 
1963  *            updated with the new VR.
1964  * @param     entry Header Entry to check
1965  * @param     vr    Dicom Value Representation
1966  * @return    false if the VR is incorrect of if the VR isn't referenced
1967  *            otherwise, it returns true
1968 */
1969 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1970 {
1971    std::string msg;
1972    bool realExplicit = true;
1973
1974    // Assume we are reading a falsely explicit VR file i.e. we reached
1975    // a tag where we expect reading a VR but are in fact we read the
1976    // first to bytes of the length. Then we will interogate (through find)
1977    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1978    // both GCC and VC++ implementations of the STL map. Hence when the
1979    // expected VR read happens to be non-ascii characters we consider
1980    // we hit falsely explicit VR tag.
1981
1982    if ( !isalpha((unsigned char)vr[0]) && !isalpha((unsigned char)vr[1]) )
1983    {
1984       realExplicit = false;
1985    }
1986
1987    // CLEANME searching the dicom_vr at each occurence is expensive.
1988    // PostPone this test in an optional integrity check at the end
1989    // of parsing or only in debug mode.
1990    if ( realExplicit && !Global::GetVR()->Count(vr) )
1991    {
1992       realExplicit = false;
1993    }
1994
1995    if ( !realExplicit ) 
1996    {
1997       // We thought this was explicit VR, but we end up with an
1998       // implicit VR tag. Let's backtrack.   
1999       msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n", 
2000                     entry->GetGroup(), entry->GetElement());
2001       dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
2002
2003       if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
2004       {
2005          // Group length is UL !
2006          DictEntry* newEntry = NewVirtualDictEntry(
2007                                    entry->GetGroup(), entry->GetElement(),
2008                                    "UL", "FIXME", "Group Length");
2009          entry->SetDictEntry( newEntry );
2010       }
2011       return false;
2012    }
2013
2014    if ( entry->IsVRUnknown() )
2015    {
2016       // When not a dictionary entry, we can safely overwrite the VR.
2017       if( entry->GetElement() == 0x0000 )
2018       {
2019          // Group length is UL !
2020          entry->SetVR("UL");
2021       }
2022       else
2023       {
2024          entry->SetVR(vr);
2025       }
2026    }
2027    else if ( entry->GetVR() != vr ) 
2028    {
2029       // The VR present in the file and the dictionary disagree. We assume
2030       // the file writer knew best and use the VR of the file. Since it would
2031       // be unwise to overwrite the VR of a dictionary (since it would
2032       // compromise it's next user), we need to clone the actual DictEntry
2033       // and change the VR for the read one.
2034       DictEntry* newEntry = NewVirtualDictEntry(
2035                                 entry->GetGroup(), entry->GetElement(),
2036                                 vr, "FIXME", entry->GetName());
2037       entry->SetDictEntry(newEntry);
2038    }
2039
2040    return true; 
2041 }
2042
2043 /**
2044  * \brief   Get the transformed value of the header entry. The VR value 
2045  *          is used to define the transformation to operate on the value
2046  * \warning NOT end user intended method !
2047  * @param   entry entry to tranform
2048  * @return  Transformed entry value
2049  */
2050 std::string Document::GetDocEntryValue(DocEntry *entry)
2051 {
2052    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2053    {
2054       std::string val = ((ValEntry *)entry)->GetValue();
2055       std::string vr  = entry->GetVR();
2056       uint32_t length = entry->GetLength();
2057       std::ostringstream s;
2058       int nbInt;
2059
2060       // When short integer(s) are expected, read and convert the following 
2061       // n * 2 bytes properly i.e. as a multivaluated strings
2062       // (each single value is separated fromthe next one by '\'
2063       // as usual for standard multivaluated filels
2064       // Elements with Value Multiplicity > 1
2065       // contain a set of short integers (not a single one) 
2066    
2067       if( vr == "US" || vr == "SS" )
2068       {
2069          uint16_t newInt16;
2070
2071          nbInt = length / 2;
2072          for (int i=0; i < nbInt; i++) 
2073          {
2074             if( i != 0 )
2075             {
2076                s << '\\';
2077             }
2078             newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2079             newInt16 = SwapShort( newInt16 );
2080             s << newInt16;
2081          }
2082       }
2083
2084       // When integer(s) are expected, read and convert the following 
2085       // n * 4 bytes properly i.e. as a multivaluated strings
2086       // (each single value is separated fromthe next one by '\'
2087       // as usual for standard multivaluated filels
2088       // Elements with Value Multiplicity > 1
2089       // contain a set of integers (not a single one) 
2090       else if( vr == "UL" || vr == "SL" )
2091       {
2092          uint32_t newInt32;
2093
2094          nbInt = length / 4;
2095          for (int i=0; i < nbInt; i++) 
2096          {
2097             if( i != 0)
2098             {
2099                s << '\\';
2100             }
2101             newInt32 = ( val[4*i+0] & 0xFF )
2102                     + (( val[4*i+1] & 0xFF ) <<  8 )
2103                     + (( val[4*i+2] & 0xFF ) << 16 )
2104                     + (( val[4*i+3] & 0xFF ) << 24 );
2105             newInt32 = SwapLong( newInt32 );
2106             s << newInt32;
2107          }
2108       }
2109 #ifdef GDCM_NO_ANSI_STRING_STREAM
2110       s << std::ends; // to avoid oddities on Solaris
2111 #endif //GDCM_NO_ANSI_STRING_STREAM
2112       return s.str();
2113    }
2114
2115    return ((ValEntry *)entry)->GetValue();
2116 }
2117
2118 /**
2119  * \brief   Get the reverse transformed value of the header entry. The VR 
2120  *          value is used to define the reverse transformation to operate on
2121  *          the value
2122  * \warning NOT end user intended method !
2123  * @param   entry Entry to reverse transform
2124  * @return  Reverse transformed entry value
2125  */
2126 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2127 {
2128    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2129    {
2130       std::string vr = entry->GetVR();
2131       std::vector<std::string> tokens;
2132       std::ostringstream s;
2133
2134       if ( vr == "US" || vr == "SS" ) 
2135       {
2136          uint16_t newInt16;
2137
2138          tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2139          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2140          for (unsigned int i=0; i<tokens.size(); i++) 
2141          {
2142             newInt16 = atoi(tokens[i].c_str());
2143             s << (  newInt16        & 0xFF ) 
2144               << (( newInt16 >> 8 ) & 0xFF );
2145          }
2146          tokens.clear();
2147       }
2148       if ( vr == "UL" || vr == "SL")
2149       {
2150          uint32_t newInt32;
2151
2152          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2153          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2154          for (unsigned int i=0; i<tokens.size();i++) 
2155          {
2156             newInt32 = atoi(tokens[i].c_str());
2157             s << (char)(  newInt32         & 0xFF ) 
2158               << (char)(( newInt32 >>  8 ) & 0xFF )
2159               << (char)(( newInt32 >> 16 ) & 0xFF )
2160               << (char)(( newInt32 >> 24 ) & 0xFF );
2161          }
2162          tokens.clear();
2163       }
2164
2165 #ifdef GDCM_NO_ANSI_STRING_STREAM
2166       s << std::ends; // to avoid oddities on Solaris
2167 #endif //GDCM_NO_ANSI_STRING_STREAM
2168       return s.str();
2169    }
2170
2171    return ((ValEntry *)entry)->GetValue();
2172 }
2173
2174 /**
2175  * \brief   Skip a given Header Entry 
2176  * \warning NOT end user intended method !
2177  * @param   entry entry to skip
2178  */
2179 void Document::SkipDocEntry(DocEntry *entry) 
2180 {
2181    SkipBytes(entry->GetLength());
2182 }
2183
2184 /**
2185  * \brief   Skips to the begining of the next Header Entry 
2186  * \warning NOT end user intended method !
2187  * @param   entry entry to skip
2188  */
2189 void Document::SkipToNextDocEntry(DocEntry *entry) 
2190 {
2191    Fp->seekg((long)(entry->GetOffset()),     std::ios_base::beg);
2192    Fp->seekg( (long)(entry->GetReadLength()), std::ios_base::cur);
2193 }
2194
2195 /**
2196  * \brief   When the length of an element value is obviously wrong (because
2197  *          the parser went Jabberwocky) one can hope improving things by
2198  *          applying some heuristics.
2199  * @param   entry entry to check
2200  * @param   foundLength fist assumption about length    
2201  */
2202 void Document::FixDocEntryFoundLength(DocEntry *entry,
2203                                       uint32_t foundLength)
2204 {
2205    entry->SetReadLength( foundLength ); // will be updated only if a bug is found        
2206    if ( foundLength == 0xffffffff)
2207    {
2208       foundLength = 0;
2209    }
2210    
2211    uint16_t gr = entry->GetGroup();
2212    uint16_t el = entry->GetElement(); 
2213      
2214    if ( foundLength % 2)
2215    {
2216       std::ostringstream s;
2217       s << "Warning : Tag with uneven length "
2218         << foundLength 
2219         <<  " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2220       dbg.Verbose(0, s.str().c_str());
2221    }
2222       
2223    //////// Fix for some naughty General Electric images.
2224    // Allthough not recent many such GE corrupted images are still present
2225    // on Creatis hard disks. Hence this fix shall remain when such images
2226    // are no longer in user (we are talking a few years, here)...
2227    // Note: XMedCom probably uses such a trick since it is able to read
2228    //       those pesky GE images ...
2229    if ( foundLength == 13)
2230    {
2231       // Only happens for this length !
2232       if ( entry->GetGroup()   != 0x0008
2233       || ( entry->GetElement() != 0x0070
2234         && entry->GetElement() != 0x0080 ) )
2235       {
2236          foundLength = 10;
2237          entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2238       }
2239    }
2240
2241    //////// Fix for some brain-dead 'Leonardo' Siemens images.
2242    // Occurence of such images is quite low (unless one leaves close to a
2243    // 'Leonardo' source. Hence, one might consider commenting out the
2244    // following fix on efficiency reasons.
2245    else if ( entry->GetGroup()   == 0x0009 
2246         && ( entry->GetElement() == 0x1113
2247           || entry->GetElement() == 0x1114 ) )
2248    {
2249       foundLength = 4;
2250       entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2251    } 
2252  
2253    else if ( entry->GetVR() == "SQ" )
2254    {
2255       foundLength = 0;      // ReadLength is unchanged 
2256    } 
2257     
2258    //////// We encountered a 'delimiter' element i.e. a tag of the form 
2259    // "fffe|xxxx" which is just a marker. Delimiters length should not be
2260    // taken into account.
2261    else if( entry->GetGroup() == 0xfffe )
2262    {    
2263      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2264      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2265      // causes extra troubles...
2266      if( entry->GetElement() != 0x0000 )
2267      {
2268         foundLength = 0;
2269      }
2270    } 
2271            
2272    entry->SetUsableLength(foundLength);
2273 }
2274
2275 /**
2276  * \brief   Apply some heuristics to predict whether the considered 
2277  *          element value contains/represents an integer or not.
2278  * @param   entry The element value on which to apply the predicate.
2279  * @return  The result of the heuristical predicate.
2280  */
2281 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2282 {
2283    uint16_t element = entry->GetElement();
2284    uint16_t group   = entry->GetGroup();
2285    const std::string & vr  = entry->GetVR();
2286    uint32_t length  = entry->GetLength();
2287
2288    // When we have some semantics on the element we just read, and if we
2289    // a priori know we are dealing with an integer, then we shall be
2290    // able to swap it's element value properly.
2291    if ( element == 0 )  // This is the group length of the group
2292    {  
2293       if ( length == 4 )
2294       {
2295          return true;
2296       }
2297       else 
2298       {
2299          // Allthough this should never happen, still some images have a
2300          // corrupted group length [e.g. have a glance at offset x(8336) of
2301          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2302          // Since for dicom compliant and well behaved headers, the present
2303          // test is useless (and might even look a bit paranoid), when we
2304          // encounter such an ill-formed image, we simply display a warning
2305          // message and proceed on parsing (while crossing fingers).
2306          std::ostringstream s;
2307          long filePosition = Fp->tellg();
2308          s << "Erroneous Group Length element length  on : (" \
2309            << std::hex << group << " , " << element 
2310            << ") -before- position x(" << filePosition << ")"
2311            << "lgt : " << length;
2312          dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2313       }
2314    }
2315
2316    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2317    {
2318       return true;
2319    }
2320    
2321    return false;
2322 }
2323
2324 /**
2325  * \brief  Find the Length till the next sequence delimiter
2326  * \warning NOT end user intended method !
2327  * @return 
2328  */
2329
2330 uint32_t Document::FindDocEntryLengthOB()
2331    throw( FormatUnexpected )
2332 {
2333    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2334    long positionOnEntry = Fp->tellg();
2335    bool foundSequenceDelimiter = false;
2336    uint32_t totalLength = 0;
2337
2338    while ( !foundSequenceDelimiter )
2339    {
2340       uint16_t group;
2341       uint16_t elem;
2342       try
2343       {
2344          group = ReadInt16();
2345          elem  = ReadInt16();   
2346       }
2347       catch ( FormatError )
2348       {
2349          throw FormatError("Document::FindDocEntryLengthOB()",
2350                            " group or element not present.");
2351       }
2352
2353       // We have to decount the group and element we just read
2354       totalLength += 4;
2355      
2356       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2357       {
2358          dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2359                         "tag nor a Sequence delimiter tag."); 
2360          Fp->seekg(positionOnEntry, std::ios_base::beg);
2361          throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2362                                 "Neither an Item tag nor a Sequence "
2363                                 "delimiter tag.");
2364       }
2365
2366       if ( elem == 0xe0dd )
2367       {
2368          foundSequenceDelimiter = true;
2369       }
2370
2371       uint32_t itemLength = ReadInt32();
2372       // We add 4 bytes since we just read the ItemLength with ReadInt32
2373       totalLength += itemLength + 4;
2374       SkipBytes(itemLength);
2375       
2376       if ( foundSequenceDelimiter )
2377       {
2378          break;
2379       }
2380    }
2381    Fp->seekg( positionOnEntry, std::ios_base::beg);
2382    return totalLength;
2383 }
2384
2385 /**
2386  * \brief Reads a supposed to be 16 Bits integer
2387  *       (swaps it depending on processor endianity) 
2388  * @return read value
2389  */
2390 uint16_t Document::ReadInt16()
2391    throw( FormatError )
2392 {
2393    uint16_t g;
2394    Fp->read ((char*)&g, (size_t)2);
2395    if ( Fp->fail() )
2396    {
2397       throw FormatError( "Document::ReadInt16()", " file error." );
2398    }
2399    if( Fp->eof() )
2400    {
2401       throw FormatError( "Document::ReadInt16()", "EOF." );
2402    }
2403    g = SwapShort(g); 
2404    return g;
2405 }
2406
2407 /**
2408  * \brief  Reads a supposed to be 32 Bits integer
2409  *         (swaps it depending on processor endianity)  
2410  * @return read value
2411  */
2412 uint32_t Document::ReadInt32()
2413    throw( FormatError )
2414 {
2415    uint32_t g;
2416    Fp->read ((char*)&g, (size_t)4);
2417    if ( Fp->fail() )
2418    {
2419       throw FormatError( "Document::ReadInt32()", " file error." );
2420    }
2421    if( Fp->eof() )
2422    {
2423       throw FormatError( "Document::ReadInt32()", "EOF." );
2424    }
2425    g = SwapLong(g);
2426    return g;
2427 }
2428
2429 /**
2430  * \brief skips bytes inside the source file 
2431  * \warning NOT end user intended method !
2432  * @return 
2433  */
2434 void Document::SkipBytes(uint32_t nBytes)
2435 {
2436    //FIXME don't dump the returned value
2437    Fp->seekg((long)nBytes, std::ios_base::cur);
2438 }
2439
2440 /**
2441  * \brief Loads all the needed Dictionaries
2442  * \warning NOT end user intended method !   
2443  */
2444 void Document::Initialise() 
2445 {
2446    RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2447    RefShaDict = NULL;
2448    RLEInfo  = new RLEFramesInfo;
2449    JPEGInfo = new JPEGFragmentsInfo;
2450 }
2451
2452 /**
2453  * \brief   Discover what the swap code is (among little endian, big endian,
2454  *          bad little endian, bad big endian).
2455  *          sw is set
2456  * @return false when we are absolutely sure 
2457  *               it's neither ACR-NEMA nor DICOM
2458  *         true  when we hope ours assuptions are OK
2459  */
2460 bool Document::CheckSwap()
2461 {
2462    // The only guaranted way of finding the swap code is to find a
2463    // group tag since we know it's length has to be of four bytes i.e.
2464    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2465    // occurs when we can't find such group...
2466    
2467    uint32_t  x = 4;  // x : for ntohs
2468    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2469    uint32_t  s32;
2470    uint16_t  s16;
2471        
2472    char deb[256]; //HEADER_LENGTH_TO_READ];
2473     
2474    // First, compare HostByteOrder and NetworkByteOrder in order to
2475    // determine if we shall need to swap bytes (i.e. the Endian type).
2476    if ( x == ntohs(x) )
2477    {
2478       net2host = true;
2479    }
2480    else
2481    {
2482       net2host = false;
2483    }
2484          
2485    // The easiest case is the one of a DICOM header, since it possesses a
2486    // file preamble where it suffice to look for the string "DICM".
2487    Fp->read(deb, HEADER_LENGTH_TO_READ);
2488    
2489    char *entCur = deb + 128;
2490    if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2491    {
2492       dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2493       
2494       // Next, determine the value representation (VR). Let's skip to the
2495       // first element (0002, 0000) and check there if we find "UL" 
2496       // - or "OB" if the 1st one is (0002,0001) -,
2497       // in which case we (almost) know it is explicit VR.
2498       // WARNING: if it happens to be implicit VR then what we will read
2499       // is the length of the group. If this ascii representation of this
2500       // length happens to be "UL" then we shall believe it is explicit VR.
2501       // FIXME: in order to fix the above warning, we could read the next
2502       // element value (or a couple of elements values) in order to make
2503       // sure we are not commiting a big mistake.
2504       // We need to skip :
2505       // * the 128 bytes of File Preamble (often padded with zeroes),
2506       // * the 4 bytes of "DICM" string,
2507       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2508       // i.e. a total of  136 bytes.
2509       entCur = deb + 136;
2510      
2511       // FIXME : FIXME:
2512       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2513       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2514       // *Implicit* VR.  -and it is !- 
2515       
2516       if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2517           memcmp(entCur, "OB", (size_t)2) == 0 ||
2518           memcmp(entCur, "UI", (size_t)2) == 0 ||
2519           memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
2520                                                     // when Write DCM *adds*
2521       // FIXME
2522       // Use Document::dicom_vr to test all the possibilities
2523       // instead of just checking for UL, OB and UI !? group 0000 
2524       {
2525          Filetype = ExplicitVR;
2526          dbg.Verbose(1, "Document::CheckSwap:",
2527                      "explicit Value Representation");
2528       } 
2529       else 
2530       {
2531          Filetype = ImplicitVR;
2532          dbg.Verbose(1, "Document::CheckSwap:",
2533                      "not an explicit Value Representation");
2534       }
2535       
2536       if ( net2host )
2537       {
2538          SwapCode = 4321;
2539          dbg.Verbose(1, "Document::CheckSwap:",
2540                         "HostByteOrder != NetworkByteOrder");
2541       }
2542       else 
2543       {
2544          SwapCode = 0;
2545          dbg.Verbose(1, "Document::CheckSwap:",
2546                         "HostByteOrder = NetworkByteOrder");
2547       }
2548       
2549       // Position the file position indicator at first tag (i.e.
2550       // after the file preamble and the "DICM" string).
2551       Fp->seekg(0, std::ios_base::beg);
2552       Fp->seekg ( 132L, std::ios_base::beg);
2553       return true;
2554    } // End of DicomV3
2555
2556    // Alas, this is not a DicomV3 file and whatever happens there is no file
2557    // preamble. We can reset the file position indicator to where the data
2558    // is (i.e. the beginning of the file).
2559    dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2560    Fp->seekg(0, std::ios_base::beg);
2561
2562    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2563    // By clean we mean that the length of the first tag is written down.
2564    // If this is the case and since the length of the first group HAS to be
2565    // four (bytes), then determining the proper swap code is straightforward.
2566
2567    entCur = deb + 4;
2568    // We assume the array of char we are considering contains the binary
2569    // representation of a 32 bits integer. Hence the following dirty
2570    // trick :
2571    s32 = *((uint32_t *)(entCur));
2572       
2573    switch( s32 )
2574    {
2575       case 0x00040000 :
2576          SwapCode = 3412;
2577          Filetype = ACR;
2578          return true;
2579       case 0x04000000 :
2580          SwapCode = 4321;
2581          Filetype = ACR;
2582          return true;
2583       case 0x00000400 :
2584          SwapCode = 2143;
2585          Filetype = ACR;
2586          return true;
2587       case 0x00000004 :
2588          SwapCode = 0;
2589          Filetype = ACR;
2590          return true;
2591       default :
2592          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2593          // It is time for despaired wild guesses. 
2594          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2595          //  i.e. the 'group length' element is not present :     
2596          
2597          //  check the supposed-to-be 'group number'
2598          //  in ( 0x0001 .. 0x0008 )
2599          //  to determine ' SwapCode' value .
2600          //  Only 0 or 4321 will be possible 
2601          //  (no oportunity to check for the formerly well known
2602          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2603          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-) 
2604          //  the file IS NOT ACR-NEMA nor DICOM V3
2605          //  Find a trick to tell it the caller...
2606       
2607          s16 = *((uint16_t *)(deb));
2608       
2609          switch ( s16 )
2610          {
2611             case 0x0001 :
2612             case 0x0002 :
2613             case 0x0003 :
2614             case 0x0004 :
2615             case 0x0005 :
2616             case 0x0006 :
2617             case 0x0007 :
2618             case 0x0008 :
2619                SwapCode = 0;
2620                Filetype = ACR;
2621                return true;
2622             case 0x0100 :
2623             case 0x0200 :
2624             case 0x0300 :
2625             case 0x0400 :
2626             case 0x0500 :
2627             case 0x0600 :
2628             case 0x0700 :
2629             case 0x0800 :
2630                SwapCode = 4321;
2631                Filetype = ACR;
2632                return true;
2633             default :
2634                dbg.Verbose(0, "Document::CheckSwap:",
2635                      "ACR/NEMA unfound swap info (Really hopeless !)");
2636                Filetype = Unknown;
2637                return false;
2638          }
2639          // Then the only info we have is the net2host one.
2640          //if (! net2host )
2641          //   SwapCode = 0;
2642          //else
2643          //  SwapCode = 4321;
2644          //return;
2645    }
2646 }
2647
2648
2649
2650 /**
2651  * \brief Restore the unproperly loaded values i.e. the group, the element
2652  *        and the dictionary entry depending on them. 
2653  */
2654 void Document::SwitchSwapToBigEndian() 
2655 {
2656    dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2657                   "Switching to BigEndian mode.");
2658    if ( SwapCode == 0    ) 
2659    {
2660       SwapCode = 4321;
2661    }
2662    else if ( SwapCode == 4321 ) 
2663    {
2664       SwapCode = 0;
2665    }
2666    else if ( SwapCode == 3412 ) 
2667    {
2668       SwapCode = 2143;
2669    }
2670    else if ( SwapCode == 2143 )
2671    {
2672       SwapCode = 3412;
2673    }
2674 }
2675
2676 /**
2677  * \brief  during parsing, Header Elements too long are not loaded in memory 
2678  * @param newSize
2679  */
2680 void Document::SetMaxSizeLoadEntry(long newSize) 
2681 {
2682    if ( newSize < 0 )
2683    {
2684       return;
2685    }
2686    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2687    {
2688       MaxSizeLoadEntry = 0xffffffff;
2689       return;
2690    }
2691    MaxSizeLoadEntry = newSize;
2692 }
2693
2694
2695 /**
2696  * \brief Header Elements too long will not be printed
2697  * \todo  See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE 
2698  * @param newSize
2699  */
2700 void Document::SetMaxSizePrintEntry(long newSize) 
2701 {
2702    //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2703    if ( newSize < 0 )
2704    {
2705       return;
2706    }
2707    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2708    {
2709       MaxSizePrintEntry = 0xffffffff;
2710       return;
2711    }
2712    MaxSizePrintEntry = newSize;
2713 }
2714
2715
2716
2717 /**
2718  * \brief   Handle broken private tag from Philips NTSCAN
2719  *          where the endianess is being switch to BigEndian for no
2720  *          apparent reason
2721  * @return  no return
2722  */
2723 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2724 {
2725    // Endian reversion. Some files contain groups of tags with reversed endianess.
2726    static int reversedEndian = 0;
2727    // try to fix endian switching in the middle of headers
2728    if ((group == 0xfeff) && (elem == 0x00e0))
2729    {
2730      // start endian swap mark for group found
2731      reversedEndian++;
2732      SwitchSwapToBigEndian();
2733      // fix the tag
2734      group = 0xfffe;
2735      elem = 0xe000;
2736    } 
2737    else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian) 
2738    {
2739      // end of reversed endian group
2740      reversedEndian--;
2741      SwitchSwapToBigEndian();
2742    }
2743
2744 }
2745
2746 /**
2747  * \brief   Read the next tag but WITHOUT loading it's value
2748  *          (read the 'Group Number', the 'Element Number',
2749  *           gets the Dict Entry
2750  *          gets the VR, gets the length, gets the offset value)
2751  * @return  On succes the newly created DocEntry, NULL on failure.      
2752  */
2753 DocEntry* Document::ReadNextDocEntry()
2754 {
2755    uint16_t group;
2756    uint16_t elem;
2757
2758    try
2759    {
2760       group = ReadInt16();
2761       elem  = ReadInt16();
2762    }
2763    catch ( FormatError e )
2764    {
2765       // We reached the EOF (or an error occured) therefore 
2766       // header parsing has to be considered as finished.
2767       //std::cout << e;
2768       return 0;
2769    }
2770
2771    HandleBrokenEndian(group, elem);
2772    DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2773    FindDocEntryVR(newEntry);
2774
2775    try
2776    {
2777       FindDocEntryLength(newEntry);
2778    }
2779    catch ( FormatError e )
2780    {
2781       // Call it quits
2782       //std::cout << e;
2783       delete newEntry;
2784       return 0;
2785    }
2786
2787    newEntry->SetOffset(Fp->tellg());  
2788
2789    return newEntry;
2790 }
2791
2792
2793 /**
2794  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2795  *          in the TagHt dictionary.
2796  * @param   group The generated tag must belong to this group.  
2797  * @return  The element of tag with given group which is fee.
2798  */
2799 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group) 
2800 {
2801    for (uint32_t elem = 0; elem < UINT32_MAX; elem++) 
2802    {
2803       TagKey key = DictEntry::TranslateToKey(group, elem);
2804       if (TagHT.count(key) == 0)
2805       {
2806          return elem;
2807       }
2808    }
2809    return UINT32_MAX;
2810 }
2811
2812 /**
2813  * \brief   Assuming the internal file pointer \ref Document::Fp 
2814  *          is placed at the beginning of a tag check whether this
2815  *          tag is (TestGroup, TestElement).
2816  * \warning On success the internal file pointer \ref Document::Fp
2817  *          is modified to point after the tag.
2818  *          On failure (i.e. when the tag wasn't the expected tag
2819  *          (TestGroup, TestElement) the internal file pointer
2820  *          \ref Document::Fp is restored to it's original position.
2821  * @param   testGroup   The expected group of the tag.
2822  * @param   testElement The expected Element of the tag.
2823  * @return  True on success, false otherwise.
2824  */
2825 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2826 {
2827    long positionOnEntry = Fp->tellg();
2828    long currentPosition = Fp->tellg();          // On debugging purposes
2829
2830    //// Read the Item Tag group and element, and make
2831    // sure they are what we expected:
2832    uint16_t itemTagGroup;
2833    uint16_t itemTagElement;
2834    try
2835    {
2836       itemTagGroup   = ReadInt16();
2837       itemTagElement = ReadInt16();
2838    }
2839    catch ( FormatError e )
2840    {
2841       //std::cerr << e << std::endl;
2842       return false;
2843    }
2844    if ( itemTagGroup != testGroup || itemTagElement != testElement )
2845    {
2846       std::ostringstream s;
2847       s << "   We should have found tag (";
2848       s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2849       s << "   but instead we encountered tag (";
2850       s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2851         << std::endl;
2852       s << "  at address: " << (unsigned)currentPosition << std::endl;
2853       dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2854       dbg.Verbose(0, s.str().c_str());
2855       Fp->seekg(positionOnEntry, std::ios_base::beg);
2856
2857       return false;
2858    }
2859    return true;
2860 }
2861
2862 /**
2863  * \brief   Assuming the internal file pointer \ref Document::Fp 
2864  *          is placed at the beginning of a tag (TestGroup, TestElement),
2865  *          read the length associated to the Tag.
2866  * \warning On success the internal file pointer \ref Document::Fp
2867  *          is modified to point after the tag and it's length.
2868  *          On failure (i.e. when the tag wasn't the expected tag
2869  *          (TestGroup, TestElement) the internal file pointer
2870  *          \ref Document::Fp is restored to it's original position.
2871  * @param   testGroup   The expected group of the tag.
2872  * @param   testElement The expected Element of the tag.
2873  * @return  On success returns the length associated to the tag. On failure
2874  *          returns 0.
2875  */
2876 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2877 {
2878    long positionOnEntry = Fp->tellg();
2879    (void)positionOnEntry;
2880
2881    if ( !ReadTag(testGroup, testElement) )
2882    {
2883       return 0;
2884    }
2885                                                                                 
2886    //// Then read the associated Item Length
2887    long currentPosition = Fp->tellg();
2888    uint32_t itemLength  = ReadInt32();
2889    {
2890       std::ostringstream s;
2891       s << "Basic Item Length is: "
2892         << itemLength << std::endl;
2893       s << "  at address: " << (unsigned)currentPosition << std::endl;
2894       dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2895    }
2896    return itemLength;
2897 }
2898
2899 /**
2900  * \brief When parsing the Pixel Data of an encapsulated file, read
2901  *        the basic offset table (when present, and BTW dump it).
2902  */
2903 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2904 {
2905    //// Read the Basic Offset Table Item Tag length...
2906    uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2907
2908    // When present, read the basic offset table itself.
2909    // Notes: - since the presence of this basic offset table is optional
2910    //          we can't rely on it for the implementation, and we will simply
2911    //          trash it's content (when present).
2912    //        - still, when present, we could add some further checks on the
2913    //          lengths, but we won't bother with such fuses for the time being.
2914    if ( itemLength != 0 )
2915    {
2916       char* basicOffsetTableItemValue = new char[itemLength + 1];
2917       Fp->read(basicOffsetTableItemValue, itemLength);
2918
2919 #ifdef GDCM_DEBUG
2920       for (unsigned int i=0; i < itemLength; i += 4 )
2921       {
2922          uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2923                                               uint32_t);
2924          std::ostringstream s;
2925          s << "   Read one length: ";
2926          s << std::hex << individualLength << std::endl;
2927          dbg.Verbose(0,
2928                      "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2929                      s.str().c_str());
2930       }
2931 #endif //GDCM_DEBUG
2932
2933       delete[] basicOffsetTableItemValue;
2934    }
2935 }
2936
2937 /**
2938  * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2939  *        Compute the RLE extra information and store it in \ref RLEInfo
2940  *        for later pixel retrieval usage.
2941  */
2942 void Document::ComputeRLEInfo()
2943 {
2944    TransferSyntaxType ts = GetTransferSyntax();
2945    if ( ts != RLELossless )
2946    {
2947       return;
2948    }
2949
2950    // Encoded pixel data: for the time being we are only concerned with
2951    // Jpeg or RLE Pixel data encodings.
2952    // As stated in PS 3.5-2003, section 8.2 p44:
2953    // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2954    //  value representation OB is used".
2955    // Hence we expect an OB value representation. Concerning OB VR,
2956    // the section PS 3.5-2003, section A.4.c p 58-59, states:
2957    // "For the Value Representations OB and OW, the encoding shall meet the
2958    //   following specifications depending on the Data element tag:"
2959    //   [...snip...]
2960    //    - the first item in the sequence of items before the encoded pixel
2961    //      data stream shall be basic offset table item. The basic offset table
2962    //      item value, however, is not required to be present"
2963
2964    ReadAndSkipEncapsulatedBasicOffsetTable();
2965
2966    // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2967    // Loop on the individual frame[s] and store the information
2968    // on the RLE fragments in a RLEFramesInfo.
2969    // Note: - when only a single frame is present, this is a
2970    //         classical image.
2971    //       - when more than one frame are present, then we are in 
2972    //         the case of a multi-frame image.
2973    long frameLength;
2974    while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2975    { 
2976       // Parse the RLE Header and store the corresponding RLE Segment
2977       // Offset Table information on fragments of this current Frame.
2978       // Note that the fragment pixels themselves are not loaded
2979       // (but just skipped).
2980       long frameOffset = Fp->tellg();
2981
2982       uint32_t nbRleSegments = ReadInt32();
2983       if ( nbRleSegments > 16 )
2984       {
2985          // There should be at most 15 segments (refer to RLEFrame class)
2986          dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2987       }
2988  
2989       uint32_t rleSegmentOffsetTable[16];
2990       for( int k = 1; k <= 15; k++ )
2991       {
2992          rleSegmentOffsetTable[k] = ReadInt32();
2993       }
2994
2995       // Deduce from both the RLE Header and the frameLength the
2996       // fragment length, and again store this info in a
2997       // RLEFramesInfo.
2998       long rleSegmentLength[15];
2999       // skipping (not reading) RLE Segments
3000       if ( nbRleSegments > 1)
3001       {
3002          for(unsigned int k = 1; k <= nbRleSegments-1; k++)
3003          {
3004              rleSegmentLength[k] =  rleSegmentOffsetTable[k+1]
3005                                   - rleSegmentOffsetTable[k];
3006              SkipBytes(rleSegmentLength[k]);
3007           }
3008        }
3009
3010        rleSegmentLength[nbRleSegments] = frameLength 
3011                                       - rleSegmentOffsetTable[nbRleSegments];
3012        SkipBytes(rleSegmentLength[nbRleSegments]);
3013
3014        // Store the collected info
3015        RLEFrame* newFrameInfo = new RLEFrame;
3016        newFrameInfo->NumberFragments = nbRleSegments;
3017        for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
3018        {
3019           newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
3020           newFrameInfo->Length[uk] = rleSegmentLength[uk];
3021        }
3022        RLEInfo->Frames.push_back( newFrameInfo );
3023    }
3024
3025    // Make sure that at the end of the item we encounter a 'Sequence
3026    // Delimiter Item':
3027    if ( !ReadTag(0xfffe, 0xe0dd) )
3028    {
3029       dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3030       dbg.Verbose(0, "    item at end of RLE item sequence");
3031    }
3032 }
3033
3034 /**
3035  * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
3036  *        Compute the jpeg extra information (fragment[s] offset[s] and
3037  *        length) and store it[them] in \ref JPEGInfo for later pixel
3038  *        retrieval usage.
3039  */
3040 void Document::ComputeJPEGFragmentInfo()
3041 {
3042    // If you need to, look for comments of ComputeRLEInfo().
3043    if ( ! IsJPEG() )
3044    {
3045       return;
3046    }
3047
3048    ReadAndSkipEncapsulatedBasicOffsetTable();
3049
3050    // Loop on the fragments[s] and store the parsed information in a
3051    // JPEGInfo.
3052    long fragmentLength;
3053    while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
3054    { 
3055       long fragmentOffset = Fp->tellg();
3056
3057        // Store the collected info
3058        JPEGFragment* newFragment = new JPEGFragment;
3059        newFragment->Offset = fragmentOffset;
3060        newFragment->Length = fragmentLength;
3061        JPEGInfo->Fragments.push_back( newFragment );
3062
3063        SkipBytes( fragmentLength );
3064    }
3065
3066    // Make sure that at the end of the item we encounter a 'Sequence
3067    // Delimiter Item':
3068    if ( !ReadTag(0xfffe, 0xe0dd) )
3069    {
3070       dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3071       dbg.Verbose(0, "    item at end of JPEG item sequence");
3072    }
3073 }
3074
3075 /**
3076  * \brief Walk recursively the given \ref DocEntrySet, and feed
3077  *        the given hash table (\ref TagDocEntryHT) with all the
3078  *        \ref DocEntry (Dicom entries) encountered.
3079  *        This method does the job for \ref BuildFlatHashTable.
3080  * @param builtHT Where to collect all the \ref DocEntry encountered
3081  *        when recursively walking the given set.
3082  * @param set The structure to be traversed (recursively).
3083  */
3084 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3085                                           DocEntrySet* set )
3086
3087    if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3088    {
3089       TagDocEntryHT const & currentHT = elementSet->GetTagHT();
3090       for( TagDocEntryHT::const_iterator i  = currentHT.begin();
3091                                          i != currentHT.end();
3092                                        ++i)
3093       {
3094          DocEntry* entry = i->second;
3095          if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3096          {
3097             const ListSQItem& items = seqEntry->GetSQItems();
3098             for( ListSQItem::const_iterator item  = items.begin();
3099                                             item != items.end();
3100                                           ++item)
3101             {
3102                BuildFlatHashTableRecurse( builtHT, *item );
3103             }
3104             continue;
3105          }
3106          builtHT[entry->GetKey()] = entry;
3107       }
3108       return;
3109     }
3110
3111    if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3112    {
3113       const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3114       for (ListDocEntry::const_iterator i  = currentList.begin();
3115                                         i != currentList.end();
3116                                       ++i)
3117       {
3118          DocEntry* entry = *i;
3119          if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3120          {
3121             const ListSQItem& items = seqEntry->GetSQItems();
3122             for( ListSQItem::const_iterator item  = items.begin();
3123                                             item != items.end();
3124                                           ++item)
3125             {
3126                BuildFlatHashTableRecurse( builtHT, *item );
3127             }
3128             continue;
3129          }
3130          builtHT[entry->GetKey()] = entry;
3131       }
3132
3133    }
3134 }
3135
3136 /**
3137  * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3138  *        Document.
3139  *
3140  *        The structure used by a Document (through \ref ElementSet),
3141  *        in order to hold the parsed entries of a Dicom header, is a recursive
3142  *        one. This is due to the fact that the sequences (when present)
3143  *        can be nested. Additionaly, the sequence items (represented in
3144  *        gdcm as \ref SQItem) add an extra complexity to the data
3145  *        structure. Hence, a gdcm user whishing to visit all the entries of
3146  *        a Dicom header will need to dig in the gdcm internals (which
3147  *        implies exposing all the internal data structures to the API).
3148  *        In order to avoid this burden to the user, \ref BuildFlatHashTable
3149  *        recursively builds a temporary hash table, which holds all the
3150  *        Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3151  *        std::map<>).
3152  * \warning Of course there is NO integrity constrain between the 
3153  *        returned \ref TagDocEntryHT and the \ref ElementSet used
3154  *        to build it. Hence if the underlying \ref ElementSet is
3155  *        altered, then it is the caller responsability to invoke 
3156  *        \ref BuildFlatHashTable again...
3157  * @return The flat std::map<> we juste build.
3158  */
3159 TagDocEntryHT* Document::BuildFlatHashTable()
3160 {
3161    TagDocEntryHT* FlatHT = new TagDocEntryHT;
3162    BuildFlatHashTableRecurse( *FlatHT, this );
3163    return FlatHT;
3164 }
3165
3166
3167
3168 /**
3169  * \brief   Compares two documents, according to \ref DicomDir rules
3170  * \warning Does NOT work with ACR-NEMA files
3171  * \todo    Find a trick to solve the pb (use RET fields ?)
3172  * @param   document
3173  * @return  true if 'smaller'
3174  */
3175 bool Document::operator<(Document &document)
3176 {
3177    // Patient Name
3178    std::string s1 = GetEntryByNumber(0x0010,0x0010);
3179    std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3180    if(s1 < s2)
3181    {
3182       return true;
3183    }
3184    else if( s1 > s2 )
3185    {
3186       return false;
3187    }
3188    else
3189    {
3190       // Patient ID
3191       s1 = GetEntryByNumber(0x0010,0x0020);
3192       s2 = document.GetEntryByNumber(0x0010,0x0020);
3193       if ( s1 < s2 )
3194       {
3195          return true;
3196       }
3197       else if ( s1 > s2 )
3198       {
3199          return false;
3200       }
3201       else
3202       {
3203          // Study Instance UID
3204          s1 = GetEntryByNumber(0x0020,0x000d);
3205          s2 = document.GetEntryByNumber(0x0020,0x000d);
3206          if ( s1 < s2 )
3207          {
3208             return true;
3209          }
3210          else if( s1 > s2 )
3211          {
3212             return false;
3213          }
3214          else
3215          {
3216             // Serie Instance UID
3217             s1 = GetEntryByNumber(0x0020,0x000e);
3218             s2 = document.GetEntryByNumber(0x0020,0x000e);    
3219             if ( s1 < s2 )
3220             {
3221                return true;
3222             }
3223             else if( s1 > s2 )
3224             {
3225                return false;
3226             }
3227          }
3228       }
3229    }
3230    return false;
3231 }
3232
3233 } // end namespace gdcm
3234
3235 //-----------------------------------------------------------------------------