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