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