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