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