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