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