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