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