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