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