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