]> Creatis software - gdcm.git/blob - src/gdcmParser.cxx
8c3ca926c578762074aa707bed9751ebc6c7a8d0
[gdcm.git] / src / gdcmParser.cxx
1 // gdcmParser.cxx
2 //-----------------------------------------------------------------------------
3 #include <errno.h>
4 #include <vector>
5
6 // For nthos:
7 #ifdef _MSC_VER
8    #include <winsock.h>
9 #else
10    #include <netinet/in.h>
11 #endif
12
13 #ifdef GDCM_NO_ANSI_STRING_STREAM
14 #  include <strstream>
15 #  define  ostringstream ostrstream
16 # else
17 #  include <sstream>
18 #endif
19 #  include <iomanip>
20
21 #include "gdcmParser.h"
22 #include "gdcmGlobal.h"
23 #include "gdcmUtil.h"
24 #include "gdcmDebug.h"
25
26 #define UI1_2_840_10008_1_2      "1.2.840.10008.1.2"
27 #define UI1_2_840_10008_1_2_1    "1.2.840.10008.1.2.1"
28 #define UI1_2_840_10008_1_2_2    "1.2.840.10008.1.2.2"
29 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
30
31 //-----------------------------------------------------------------------------
32 // Refer to gdcmParser::CheckSwap()
33 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
34
35 // Refer to gdcmParser::SetMaxSizeLoadEntry()
36 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
37
38 // Refer to gdcmParser::SetMaxSizePrintEntry()
39 // TODO : Right now, better see "define, in gdcmHederEntry.cxx
40 const unsigned int gdcmParser::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
41
42 //-----------------------------------------------------------------------------
43 // Constructor / Destructor
44
45 /**
46  * \brief   constructor  
47  * @param   inFilename
48  * @param   exception_on_error whether we throw an exception or not
49  * @param   enable_sequences = true to allow the header 
50  *          to be parsed *inside* the SeQuences, 
51  *          when they have an actual length 
52  * @param   ignore_shadow to allow skipping the shadow elements, 
53  *          to save memory space.
54  * \warning The TRUE value for this param has to be used 
55  *          with a FALSE value for the 'enable_sequence' param.
56  *          ('public elements' may be embedded in 'shadow Sequences')
57  */
58 gdcmParser::gdcmParser(const char *inFilename, 
59                        bool exception_on_error,
60                        bool enable_sequences,
61                        bool ignore_shadow) {
62    enableSequences=enable_sequences;
63    ignoreShadow   =ignore_shadow;
64    
65    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE); 
66    filename = inFilename;
67    Initialise();
68
69    if ( !OpenFile(exception_on_error))
70       return;
71    if (ParseHeader()) {
72      LoadHeaderEntries();
73    }
74    CloseFile();
75
76    wasUpdated = 0;  // will be set to 1 if user adds an entry
77    printLevel = 1;  // 'Medium' print level by default
78 }
79
80 /**
81  * \ingroup gdcmParser
82  * \brief  constructor 
83  * @param   exception_on_error
84  */
85 gdcmParser::gdcmParser(bool exception_on_error) {
86    enableSequences=0;
87
88    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
89    Initialise();
90
91    wasUpdated = 0;  // will be set to 1 if user adds an entry
92    printLevel = 1;  // 'Medium' print level by default
93 }
94
95 /**
96  * \ingroup gdcmParser
97  * \brief   Canonical destructor.
98  */
99 gdcmParser::~gdcmParser (void) {
100    RefPubDict = NULL;
101    RefShaDict = NULL;
102 }
103
104 //-----------------------------------------------------------------------------
105 // Print
106 /**
107   * \ingroup gdcmParser
108   * \brief   Prints the Header Entries (Dicom Elements)
109   *          both from the H Table and the chained list
110   * @return
111   */ 
112 void gdcmParser::PrintEntry(std::ostream & os) {
113    std::ostringstream s;   
114
115    for (ListTag::iterator i = listEntries.begin();  
116         i != listEntries.end();
117         ++i)
118    {
119       (*i)->SetPrintLevel(printLevel);
120       (*i)->Print(os);   
121    } 
122    os<<s.str();
123 }
124
125 /**
126   * \ingroup gdcmParser
127   * \brief   Prints The Dict Entries of THE public Dicom Dictionnry
128   * @return
129   */  
130 void gdcmParser::PrintPubDict(std::ostream & os) {
131    RefPubDict->Print(os);
132 }
133
134 /**
135   * \ingroup gdcmParser
136   * \brief   Prints The Dict Entries of THE shadow Dicom Dictionnary
137   * @return
138   */
139 void gdcmParser::PrintShaDict(std::ostream & os) {
140    RefShaDict->Print(os);
141 }
142
143 //-----------------------------------------------------------------------------
144 // Public
145 /**
146  * \ingroup gdcmParser
147  * \brief   Get the public dictionary used
148  */
149 gdcmDict *gdcmParser::GetPubDict(void) {
150    return(RefPubDict);
151 }
152
153 /**
154  * \ingroup gdcmParser
155  * \brief   Get the shadow dictionary used
156  */
157 gdcmDict *gdcmParser::GetShaDict(void) {
158    return(RefShaDict);
159 }
160
161 /**
162  * \ingroup gdcmParser
163  * \brief   Set the shadow dictionary used
164  * \param   dict dictionary to use in shadow
165  */
166 bool gdcmParser::SetShaDict(gdcmDict *dict){
167    RefShaDict=dict;
168    return(!RefShaDict);
169 }
170
171 /**
172  * \ingroup gdcmParser
173  * \brief   Set the shadow dictionary used
174  * \param   dictName name of the dictionary to use in shadow
175  */
176 bool gdcmParser::SetShaDict(DictKey dictName){
177    RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
178    return(!RefShaDict);
179 }
180
181 /**
182  * \ingroup gdcmParser
183  * \brief  This predicate, based on hopefully reasonable heuristics,
184  *         decides whether or not the current gdcmParser was properly parsed
185  *         and contains the mandatory information for being considered as
186  *         a well formed and usable Dicom/Acr File.
187  * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
188  *         false otherwise. 
189  */
190 bool gdcmParser::IsReadable(void) { 
191    if(filetype==Unknown) {
192       return(false);
193    }
194    if(listEntries.size()<=0) {    
195       return(false);
196    }
197
198    return(true);
199 }
200
201 /**
202  * \ingroup gdcmParser
203  * \brief   Determines if the Transfer Syntax was already encountered
204  *          and if it corresponds to a ImplicitVRLittleEndian one.
205  * @return  True when ImplicitVRLittleEndian found. False in all other cases.
206  */
207 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
208    gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
209    if ( !Element )
210       return false;
211    LoadHeaderEntrySafe(Element);
212
213    std::string Transfer = Element->GetValue();
214    if ( Transfer == UI1_2_840_10008_1_2 )
215       return true;
216    return false;
217 }
218
219 /**
220  * \ingroup gdcmParser
221  * \brief   Determines if the Transfer Syntax was already encountered
222  *          and if it corresponds to a ExplicitVRLittleEndian one.
223  * @return  True when ExplicitVRLittleEndian found. False in all other cases.
224  */
225 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
226    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
227    if ( !Element )
228       return false;
229    LoadHeaderEntrySafe(Element);
230
231    std::string Transfer = Element->GetValue();
232    if ( Transfer == UI1_2_840_10008_1_2_1 )
233       return true;
234    return false;
235 }
236
237 /**
238  * \ingroup gdcmParser
239  * \brief   Determines if the Transfer Syntax was already encountered
240  *          and if it corresponds to a DeflatedExplicitVRLittleEndian one.
241  * @return  True when DeflatedExplicitVRLittleEndian found. False in all other cases.
242  */
243 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
244    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
245    if ( !Element )
246       return false;
247    LoadHeaderEntrySafe(Element);
248
249    std::string Transfer = Element->GetValue();
250    if ( Transfer == UI1_2_840_10008_1_2_1_99 )
251       return true;
252    return false;
253 }
254
255 /**
256  * \ingroup gdcmParser
257  * \brief   Determines if the Transfer Syntax was already encountered
258  *          and if it corresponds to a Explicit VR Big Endian one.
259  * @return  True when big endian found. False in all other cases.
260  */
261 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
262    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
263    if ( !Element )
264       return false;
265    LoadHeaderEntrySafe(Element);
266
267    std::string Transfer = Element->GetValue();
268    if ( Transfer == UI1_2_840_10008_1_2_2 )  //1.2.2 ??? A verifier !
269       return true;
270    return false;
271 }
272
273 /**
274  * \ingroup gdcmParser
275  * \brief  returns the File Type 
276  *         (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
277  * @return the FileType code
278  */
279 FileType gdcmParser::GetFileType(void) {
280    return(filetype);
281 }
282
283 /**
284  * \ingroup gdcmParser
285  * \brief   opens the file
286  * @param   exception_on_error
287  * @return  
288  */
289 FILE *gdcmParser::OpenFile(bool exception_on_error)
290   throw(gdcmFileError) 
291 {
292   fp=fopen(filename.c_str(),"rb");
293   if(exception_on_error) 
294   {
295     if(!fp)
296       throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
297   }
298
299   if ( fp ) 
300   {
301      guint16 zero;
302      fread(&zero,  (size_t)2, (size_t)1, fp);
303
304     //ACR -- or DICOM with no Preamble --
305     if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
306        return(fp);
307
308     //DICOM
309     fseek(fp, 126L, SEEK_CUR);
310     char dicm[4];
311     fread(dicm,  (size_t)4, (size_t)1, fp);
312     if( memcmp(dicm, "DICM", 4) == 0 )
313        return(fp);
314
315     fclose(fp);
316     dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
317   }
318   else {
319     dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
320   }
321   return(NULL);
322 }
323
324 /**
325  * \ingroup gdcmParser
326  * \brief closes the file  
327  * @return  TRUE if the close was successfull 
328  */
329 bool gdcmParser::CloseFile(void) {
330   int closed = fclose(fp);
331   fp = (FILE *)0;
332   if (! closed)
333      return false;
334   return true;
335 }
336
337 /**
338  * \ingroup gdcmParser
339  * \brief writes on disc all the Header Entries (Dicom Elements) 
340  *        of the Chained List
341  * @param fp file pointer on an already open file
342  * @param   type type of the File to be written 
343  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
344  * @return  always "True" ?!
345  */
346 bool gdcmParser::Write(FILE *fp, FileType type) {
347 // ==============
348 // TODO The stuff was rewritten using the chained list instead 
349 //      of the H table
350 //      so we could remove the GroupHT from the gdcmParser
351 // To be checked
352 // =============
353
354    // TODO : move the following lines (and a lot of others, to be written)
355    // to a future function CheckAndCorrectHeader
356    
357    // Question :
358    // Comment pourrait-on savoir si le DcmHeader vient d'un fichier
359    // DicomV3 ou non (FileType est un champ de gdcmParser ...)
360    // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
361    // no way 
362    // a moins de se livrer a un tres complique ajout des champs manquants.
363    // faire un CheckAndCorrectHeader (?)  
364
365    if (type == ImplicitVR) 
366    {
367       std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
368       ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
369       
370       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
371       //      values with a VR of UI shall be padded with a single trailing null
372       //      Dans le cas suivant on doit pader manuellement avec un 0
373       
374       SetEntryLengthByNumber(18, 0x0002, 0x0010);
375    } 
376
377    if (type == ExplicitVR) 
378    {
379       std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
380       ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
381       
382       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
383       //      values with a VR of UI shall be padded with a single trailing null
384       //      Dans le cas suivant on doit pader manuellement avec un 0
385       
386       SetEntryLengthByNumber(20, 0x0002, 0x0010);
387    }
388
389 /* TODO : rewrite later, if really usefull
390
391    if ( (type == ImplicitVR) || (type == ExplicitVR) )
392       UpdateGroupLength(false,type);
393    if ( type == ACR)
394       UpdateGroupLength(true,ACR);
395 */
396
397    WriteEntries(fp,type);
398    return(true);
399  }
400
401 /**
402  * \ingroup gdcmParser
403  * \brief   Modifies the value of a given Header Entry (Dicom Element)
404  *          if it exists; Creates it with the given value if it doesn't
405  * \warning : adds the Header Entry to the HTable, NOT to the chained List
406  * @param   Value passed as a std::string
407  * @param Group   group of the Entry 
408  * @param Elem element of the Entry
409  * \return  pointer to the created Header Entry
410  *          NULL if creation failed
411  */
412 gdcmHeaderEntry * gdcmParser::ReplaceOrCreateByNumber(
413                                          std::string Value, 
414                                          guint16 Group, 
415                                          guint16 Elem ){
416    gdcmHeaderEntry* a;
417    a = GetHeaderEntryByNumber( Group, Elem);
418    if (a == NULL) {
419       gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
420       if (a == NULL) 
421          return NULL;
422       AddHeaderEntry(a);
423    }   
424    //SetEntryByNumber(Value, Group, Elem);
425    a->SetValue(Value);
426    return(a);
427 }   
428
429 /**
430  * \ingroup gdcmParser
431  * \brief   Modifies the value of a given Header Entry (Dicom Element)
432  *          if it exists; Creates it with the given value if it doesn't
433  * @param   Value passed as a char*
434  * @param Group   group of the Entry 
435  * @param Elem element of the Entry
436  * \return  pointer to the created Header Entry
437  *          NULL if creation failed 
438  * 
439  */
440 gdcmHeaderEntry *  gdcmParser::ReplaceOrCreateByNumber(
441                                      char* Value, 
442                                      guint16 Group, 
443                                      guint16 Elem ) {
444    gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
445
446    if(!nvHeaderEntry)
447       return(NULL);
448
449    AddHeaderEntry(nvHeaderEntry);
450
451    std::string v = Value;
452    SetEntryByNumber(v, Group, Elem);
453    return(nvHeaderEntry);
454 }  
455
456 /**
457  * \ingroup gdcmParser
458  * \brief   Set a new value if the invoked element exists
459  *          Seems to be useless !!!
460  * @param Value new element value
461  * @param Group   group of the Entry 
462  * @param Elem element of the Entry
463  * \return  boolean 
464  */
465 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) 
466 {
467    std::string v = Value;
468    SetEntryByNumber(v, Group, Elem);
469    return true;
470
471
472 //-----------------------------------------------------------------------------
473 // Protected
474
475 /**
476  * \ingroup gdcmParser
477  * \brief   Checks if a given Dicom Element exists
478  *          within the H table
479  * @param   group Group   number of the searched Dicom Element 
480  * @param   element  Element number of the searched Dicom Element 
481  * @return  number of occurences
482  */
483 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
484    std::string key = gdcmDictEntry::TranslateToKey(group, element );
485    return (tagHT.count(key));
486 }
487
488 /**
489  * \ingroup gdcmParser
490  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
491  *          the public and private dictionaries 
492  *          for the element value of a given tag.
493  * \warning Don't use any longer : use GetPubEntryByName
494  * @param   tagName name of the searched element.
495  * @return  Corresponding element value when it exists,
496  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
497  */
498 std::string gdcmParser::GetEntryByName(std::string tagName) {
499    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
500    if( dictEntry == NULL)
501       return GDCM_UNFOUND;
502
503    return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));  
504 }
505
506 /**
507  * \ingroup gdcmParser
508  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
509  *          the public and private dictionaries 
510  *          for the element value representation of a given tag.
511  *
512  *          Obtaining the VR (Value Representation) might be needed by caller
513  *          to convert the string typed content to caller's native type 
514  *          (think of C++ vs Python). The VR is actually of a higher level
515  *          of semantics than just the native C++ type.
516  * @param   tagName name of the searched element.
517  * @return  Corresponding element value representation when it exists,
518  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
519  */
520 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
521    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
522    if( dictEntry == NULL)
523       return GDCM_UNFOUND;
524
525    gdcmHeaderEntry* elem =  GetHeaderEntryByNumber(dictEntry->GetGroup(),
526                                                    dictEntry->GetElement());
527    return elem->GetVR();
528 }
529
530
531 /**
532  * \ingroup gdcmParser
533  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
534  *          the public and private dictionaries 
535  *          for the element value representation of a given tag.
536  * @param   group Group of the searched tag.
537  * @param   element Element of the searched tag.
538  * @return  Corresponding element value representation when it exists,
539  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
540  */
541 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
542    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
543    if ( ! tagHT.count(key))
544       return GDCM_UNFOUND;
545    return tagHT.find(key)->second->GetValue();
546 }
547
548 /**
549  * \ingroup gdcmParser
550  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
551  *          the public and private dictionaries 
552  *          for the element value representation of a given tag..
553  *
554  *          Obtaining the VR (Value Representation) might be needed by caller
555  *          to convert the string typed content to caller's native type 
556  *          (think of C++ vs Python). The VR is actually of a higher level
557  *          of semantics than just the native C++ type.
558  * @param   group Group of the searched tag.
559  * @param   element Element of the searched tag.
560  * @return  Corresponding element value representation when it exists,
561  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
562  */
563 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
564    gdcmHeaderEntry* elem =  GetHeaderEntryByNumber(group, element);
565    if ( !elem )
566       return GDCM_UNFOUND;
567    return elem->GetVR();
568 }
569
570 /**
571  * \ingroup gdcmParser
572  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
573  *          the public and private dictionaries 
574  *          for the value length of a given tag..
575  * @param   group Group of the searched tag.
576  * @param   element Element of the searched tag.
577  * @return  Corresponding element length; -2 if not found
578  */
579 int gdcmParser::GetEntryLengthByNumber(guint16 group, guint16 element) {
580    gdcmHeaderEntry* elem =  GetHeaderEntryByNumber(group, element);
581    if ( !elem )
582       return -2;
583    return elem->GetLength();
584 }
585 /**
586  * \ingroup gdcmParser
587  * \brief   Sets the value (string) of the Header Entry (Dicom Element)
588  * @param   content string value of the Dicom Element
589  * @param   tagName name of the searched Dicom Element.
590  * @return  true when found
591  */
592 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
593    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
594    if( dictEntry == NULL)
595       return false;    
596
597    return(SetEntryByNumber(content,dictEntry->GetGroup(),
598                                    dictEntry->GetElement()));
599 }
600
601 /**
602  * \ingroup gdcmParser
603  * \brief   Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
604  *          through it's (group, element) and modifies it's content with
605  *          the given value.
606  * \warning Don't use any longer : use SetPubEntryByNumber
607  * @param   content new value to substitute with
608  * @param   group   group of the Dicom Element to modify
609  * @param   element element of the Dicom Element to modify
610  */
611 bool gdcmParser::SetEntryByNumber(std::string content, 
612                                   guint16 group,
613                                   guint16 element) 
614 {
615    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
616    if ( ! tagHT.count(key))
617       return false;
618    int l = content.length();
619    if(l%2) // Non even length are padded with a space (020H).
620    {  
621       l++;
622       content = content + '\0';
623    }
624       
625    gdcmHeaderEntry * a;
626    IterHT p;
627    TagHeaderEntryHT::iterator p2;
628    // DO NOT remove the following lines : they explain the stuff   
629    //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
630    //p2=p.first;                // iterator on the first synonym 
631    //a=p2->second;              // H Table target column (2-nd col)
632     
633    // or, easier :
634    a = ((tagHT.equal_range(key)).first)->second; 
635        
636    a-> SetValue(content); 
637    
638    std::string vr = a->GetVR();
639    
640    guint32 lgr;
641    if( (vr == "US") || (vr == "SS") ) 
642       lgr = 2;
643    else if( (vr == "UL") || (vr == "SL") )
644       lgr = 4;
645    else
646       lgr = l;   
647
648    a->SetLength(lgr);   
649    return true;
650 }  
651
652 /**
653  * \ingroup gdcmParser
654  * \brief   Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
655  *          in the PubHeaderEntrySet of this instance
656  *          through it's (group, element) and modifies it's length with
657  *          the given value.
658  * \warning Use with extreme caution.
659  * @param l new length to substitute with
660  * @param group   group of the Entry to modify
661  * @param element element of the Entry to modify
662  * @return  true on success, false otherwise.
663  */
664 bool gdcmParser::SetEntryLengthByNumber(guint32 l, 
665                                         guint16 group, 
666                                         guint16 element) 
667 {
668    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
669    if ( ! tagHT.count(key))
670       return false;
671    if (l%2) l++; // length must be even
672    ( ((tagHT.equal_range(key)).first)->second )->SetLength(l); 
673
674    return true ;
675 }
676
677 /**
678  * \ingroup gdcmParser
679  * \brief   Gets (from Header) the offset  of a 'non string' element value 
680  *          (LoadElementValues has already be executed)
681  * @param Group   group of the Entry 
682  * @param Elem  element of the Entry
683  * @return File Offset of the Element Value 
684  */
685 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem) 
686 {
687    gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
688    if (!Entry) 
689    {
690       dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
691                       "failed to Locate gdcmHeaderEntry");
692       return (size_t)0;
693    }
694    return Entry->GetOffset();
695 }
696
697 /**
698  * \ingroup gdcmParser
699  * \brief   Gets (from Header) a 'non string' element value 
700  *          (LoadElementValues has already be executed)  
701  * @param Group   group of the Entry 
702  * @param Elem element of the Entry
703  * @return Pointer to the 'non string' area
704  */
705 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem) 
706 {
707    gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
708    if (!Entry) 
709    {
710       dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
711                   "failed to Locate gdcmHeaderEntry");
712       return (NULL);
713    }
714    return Entry->GetVoidArea();
715 }
716
717 /**
718  * \ingroup       gdcmParser
719  * \brief         Loads (from disk) the element content 
720  *                when a string is not suitable
721  * @param Group   group of the Entry 
722  * @param Elem element of the Entry
723  */
724 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem) 
725 {
726    gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
727    if ( !Element )
728       return NULL;
729    size_t o =(size_t)Element->GetOffset();
730    fseek(fp, o, SEEK_SET);
731    int l=Element->GetLength();
732    void * a = malloc(l);
733    if(!a) 
734       return NULL;
735
736    SetEntryVoidAreaByNumber(a, Group, Elem);
737    // TODO check the result 
738    size_t l2 = fread(a, 1, l ,fp);
739    if(l != l2) 
740    {
741       free(a);
742       return NULL;
743    }
744
745    return a;  
746 }
747
748 /**
749  * \ingroup gdcmParser
750  * \brief   Sets a 'non string' value to a given Dicom Element
751  * @param   area
752  * @param   group Group number of the searched Dicom Element 
753  * @param   element Element number of the searched Dicom Element 
754  * @return  
755  */
756 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
757                                           guint16 group, 
758                                           guint16 element) 
759 {
760    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
761    if ( ! tagHT.count(key))
762       return false;
763    ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area); 
764    return true;
765 }
766
767 /**
768  * \ingroup gdcmParser
769  * \brief   Update the entries with the shadow dictionary. 
770  *          Only non even entries are analyzed       
771  */
772 void gdcmParser::UpdateShaEntries(void) {
773    gdcmDictEntry *entry;
774    std::string vr;
775
776    for(ListTag::iterator it=listEntries.begin();
777        it!=listEntries.end();
778        ++it)
779    {
780       // Odd group => from public dictionary
781       if((*it)->GetGroup()%2==0)
782          continue;
783
784       // Peer group => search the corresponding dict entry
785       if(RefShaDict)
786          entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
787       else
788          entry=NULL;
789
790       if((*it)->IsImplicitVR())
791          vr="Implicit";
792       else
793          vr=(*it)->GetVR();
794
795       (*it)->SetValue(GetHeaderEntryUnvalue(*it));
796       if(entry){
797          // Set the new entry and the new value
798          (*it)->SetDictEntry(entry);
799          CheckHeaderEntryVR(*it,vr);
800
801          (*it)->SetValue(GetHeaderEntryValue(*it));
802       }
803       else
804       {
805          // Remove precedent value transformation
806          (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
807       }
808    }
809 }
810
811 /**
812  * \ingroup gdcmParser
813  * \brief   Searches within the Header Entries for a Dicom Element of
814  *          a given tag.
815  * @param   tagName name of the searched Dicom Element.
816  * @return  Corresponding Dicom Element when it exists, and NULL
817  *          otherwise.
818  */
819  gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
820    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
821    if( dictEntry == NULL)
822       return NULL;
823
824   return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
825 }
826
827 /**
828  * \ingroup gdcmParser
829  * \brief  retrieves a Dicom Element (the first one) using (group, element)
830  * \warning (group, element) IS NOT an identifier inside the Dicom Header
831  *           if you think it's NOT UNIQUE, check the count number
832  *           and use iterators to retrieve ALL the Dicoms Elements within
833  *           a given couple (group, element)
834  * @param   group Group number of the searched Dicom Element 
835  * @param   element Element number of the searched Dicom Element 
836  * @return  
837  */
838 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element) 
839 {
840    TagKey key = gdcmDictEntry::TranslateToKey(group, element);   
841    if ( ! tagHT.count(key))
842       return NULL;
843    return tagHT.find(key)->second;
844 }
845
846 /**
847  * \ingroup gdcmParser
848  * \brief   retrieves the Dicom Elements (all of them) using (group, element) 
849  * @param   group Group number of the searched Dicom Element.
850  * @param   element Element number of the searched Dicom Element.
851  * @return  a range (i.e.pair<,>) containing all elements whose key is group|element) 
852  */
853  
854 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
855    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
856    return (tagHT.equal_range(key));
857 }
858
859 /**
860  * \ingroup       gdcmParser
861  * \brief         Loads the element while preserving the current
862  *                underlying file position indicator as opposed to
863  *                to LoadHeaderEntry that modifies it.
864  * @param entry   Header Entry whose value shall be loaded. 
865  * @return  
866  */
867 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
868    long PositionOnEntry = ftell(fp);
869    LoadHeaderEntry(entry);
870    fseek(fp, PositionOnEntry, SEEK_SET);
871 }
872
873 /**
874  * \ingroup gdcmParser
875  * \brief   Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
876  * \warning : to be re-written using the chained list instead of the H table.
877  * \warning : DO NOT use (doesn't work any longer because of the multimap)
878  * \todo : to be re-written using the chained list instead of the H table
879  * @param   SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
880  * @param   type Type of the File (ExplicitVR,ImplicitVR, ACR, ...) 
881  */
882 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
883    guint16 gr, el;
884    std::string vr;
885    
886    gdcmHeaderEntry *elem;
887    char trash[10];
888    std::string str_trash;
889    
890    GroupKey key;
891    GroupHT groupHt;  // to hold the length of each group
892    TagKey tk;
893    // remember :
894    // typedef std::map<GroupKey, int> GroupHT;
895    
896    gdcmHeaderEntry *elemZ;
897   
898    // for each Tag in the DCM Header
899    
900    for (TagHeaderEntryHT::iterator tag2 = tagHT.begin(); 
901         tag2 != tagHT.end();
902         ++tag2)
903    {
904       elem  = tag2->second;
905       gr = elem->GetGroup();
906       el = elem->GetElement();
907       vr = elem->GetVR(); 
908                  
909       sprintf(trash, "%04x", gr);
910       key = trash;   // generate 'group tag'
911       
912       // if the caller decided not to take SEQUENCEs into account 
913       // e.g : he wants to write an ACR-NEMA File 
914                 
915       if (SkipSequence && vr == "SQ") 
916          continue;
917       
918       // Still unsolved problem :
919       // we cannot find the 'Sequence Delimitation Item'
920       // since it's at the end of the Hash Table
921       // (fffe,e0dd) 
922        
923       // pas SEQUENCE en ACR-NEMA
924       // WARNING : 
925       // --> la descente a l'interieur' des SQ 
926       // devrait etre faite avec une liste chainee, pas avec une HTable...
927             
928       if ( groupHt.count(key) == 0) // we just read the first elem of a given group
929       { 
930          if (el == 0x0000) // the first elem is 0x0000
931          {
932             groupHt[key] = 0;      // initialize group length 
933          } 
934          else 
935          {
936             groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
937          } 
938       } 
939       else // any elem but the first
940       {   
941          if (type == ExplicitVR) 
942          {
943             if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) 
944             {
945                groupHt[key] +=  4; // explicit VR AND OB, OW, SQ : 4 more bytes
946             }
947          }
948          groupHt[key] += 2 + 2 + 4 + elem->GetLength(); 
949       } 
950    }
951
952    unsigned short int gr_bid;
953   
954    for (GroupHT::iterator g = groupHt.begin(); // for each group we found
955         g != groupHt.end();
956         ++g)
957    { 
958       // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
959       //        warning: unsigned int format, different type arg
960       sscanf(g->first.c_str(),"%x",&gr_bid);
961       tk = g->first + "|0000";   // generate the element full tag
962                      
963       if ( tagHT.count(tk) == 0) // if element 0x0000 not found
964       {
965          gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");       
966          elemZ = new gdcmHeaderEntry(tagZ);
967          elemZ->SetLength(4);
968          AddHeaderEntry(elemZ);   // create it
969       } 
970       else 
971       {
972          elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
973       }     
974       sprintf(trash ,"%d",g->second);
975       str_trash=trash;
976       elemZ->SetValue(str_trash);
977    }   
978 }
979
980 /**
981  * \ingroup gdcmParser
982  * \brief   writes on disc according to the requested format
983  *          (ACR-NEMA, ExplicitVR, ImplicitVR) ONE
984  *          gdcmHeaderEntry 
985  * @param   tag pointer on the gdcmHeaderEntry to be written
986  * @param   type type of the File to be written 
987  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
988  * @param   _fp already open file pointer
989  */
990 void gdcmParser::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
991 {
992    guint16 gr, el;
993    guint32 lgr;
994    std::string value;
995    const char * val;
996    std::string vr;
997    guint32 val_uint32;
998    guint16 val_uint16;
999    guint16 valZero =0;
1000    void *voidArea;
1001    std::vector<std::string> tokens;
1002
1003    void *ptr;
1004    int ff=0xffffffff;
1005    // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1006    int compte =0;
1007    itsTimeToWritePixels = false;
1008
1009    gr    = tag->GetGroup();
1010    el    = tag->GetElement();
1011    lgr   = tag->GetReadLength();
1012    val   = tag->GetValue().c_str();
1013    vr    = tag->GetVR();
1014    voidArea = tag->GetVoidArea();
1015            
1016    // === Deal with the length
1017    //     --------------------
1018    if((tag->GetLength())%2==1)
1019    { 
1020       tag->SetValue(tag->GetValue()+"\0");
1021       tag->SetLength(tag->GetReadLength()+1);
1022    }
1023
1024    fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp);  //group
1025    fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp);  //element
1026       
1027    if ( (type == ExplicitVR) || (type == DICOMDIR) ) {
1028       // EXPLICIT VR
1029       guint16 z=0, shortLgr;
1030
1031       if (gr == 0xfffe) { // NO Value Representation for 'delimiters'
1032                           // no length : write ffffffff
1033
1034           // special patch to make some MR PHILIPS images e-film readable
1035           // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1036           // from Hospital Guy de Chauliac, Montpellier
1037           // we just ignore spurious fffe|0000 tag !
1038           if (el == 0x0000) return;
1039
1040          fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1041          return;       // NO value for 'delimiters'
1042       }
1043
1044       shortLgr=lgr;
1045       if (vr == "unkn") {     // Unknown was 'written'
1046          // deal with Little Endian            
1047          fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1048          fwrite ( &z,  (size_t)2 ,(size_t)1 ,_fp);
1049       } else {
1050          fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);                     
1051          if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1052          {
1053             fwrite ( &z,  (size_t)2 ,(size_t)1 ,_fp);
1054             fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1055          } else {
1056             fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1057          }
1058       }
1059    } 
1060    else // IMPLICIT VR 
1061    { 
1062       fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1063    }
1064       
1065    // === Deal with the value
1066    //     -------------------
1067    if (vr == "SQ")  return; // no "value" to write for the SEQuences
1068    if (gr == 0xfffe)return; // no "value" to write for the delimiters
1069       
1070    if (voidArea != NULL) 
1071    { // there is a 'non string' LUT, overlay, etc
1072       fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1073       return;            
1074    }
1075       
1076    if (vr == "US" || vr == "SS") 
1077    {
1078       tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1079       Tokenize (tag->GetValue(), tokens, "\\");
1080       for (unsigned int i=0; i<tokens.size();i++) 
1081       {
1082          val_uint16 = atoi(tokens[i].c_str());
1083          ptr = &val_uint16;
1084          fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1085       }
1086       tokens.clear();
1087       return;
1088    }
1089
1090    if (vr == "UL" || vr == "SL") 
1091    {
1092       tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1093       Tokenize (tag->GetValue(), tokens, "\\");
1094       for (unsigned int i=0; i<tokens.size();i++) 
1095       {
1096          val_uint32 = atoi(tokens[i].c_str());
1097          ptr = &val_uint32;
1098          fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1099       }
1100       tokens.clear();
1101       return;
1102    } 
1103           
1104    // Pixels are never loaded in the element !
1105    // we stop writting when Pixel are processed
1106    // FIX : we loose trailing elements (RAB, right now)           
1107             
1108    if ((gr == GrPixel) && (el == NumPixel) ) {
1109       compte++;
1110       if (compte == countGrPixel) {// we passed *all* the GrPixel,NumPixel   
1111          itsTimeToWritePixels = true;
1112          return;
1113       }
1114    }       
1115    fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1116 }
1117
1118 /**
1119  * \ingroup gdcmParser
1120  * \brief   writes on disc according to the requested format
1121  *          (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1122  *          using the Chained List
1123  * \warning does NOT add the missing elements in the header :
1124  *           it's up to the user doing it !
1125  *           (function CheckHeaderCoherence to be written)
1126  * \warning DON'T try, right now, to write a DICOM image
1127  *           from an ACR Header (meta elements will be missing!)
1128  * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1129  * @param   type type of the File to be written 
1130  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
1131  * @param   _fp already open file pointer
1132  */
1133
1134 void gdcmParser::WriteEntries(FILE *_fp,FileType type)
1135 {   
1136    // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1137    
1138    for (ListTag::iterator tag2=listEntries.begin();
1139                           tag2 != listEntries.end();
1140                           ++tag2)
1141    {
1142       if ( type == ACR ){ 
1143          if ((*tag2)->GetGroup() < 0x0008)   continue; // ignore pure DICOM V3 groups
1144          if ((*tag2)->GetElement() %2)       continue; // ignore shadow groups
1145          if ((*tag2)->GetVR() == "SQ" )      continue; // ignore Sequences
1146          // TODO : find a trick to *skip* the SeQuences !
1147          // Not only ignore the SQ element
1148          // --> will be done with the next organization
1149          if ((*tag2)->GetGroup() == 0xfffe ) continue; // ignore delimiters
1150    } 
1151    WriteEntry(*tag2,_fp,type);
1152    if (itsTimeToWritePixels) 
1153       break;
1154    }
1155 }   
1156
1157 /**
1158  * \ingroup gdcmParser
1159  * \brief   writes on disc according to the requested format
1160  *          (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1161  *          using only the last synonym of each mutimap H Table post.
1162  * \warning Uses the H Table, instead of the Chained List
1163  *          in order to be compliant with the old way to proceed
1164  *         (added elements taken in to account)
1165  *         Only THERALYS, during a transitory phase is supposed
1166  *         to use this method !!!
1167  * \warning DON'T try, right now, to write a DICOM image
1168  *           from an ACR Header (meta elements will be missing!)
1169  * \sa WriteEntries
1170  * @param   _fp already open file pointer
1171  * @param   type type of the File to be written 
1172  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
1173  */
1174 void gdcmParser::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1175
1176    // restent a tester les echecs en ecriture (apres chaque fwrite)
1177
1178    for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1179         tag2 != tagHT.end();
1180         ++tag2){
1181       if ( type == ACR ){ 
1182          if ((*tag2->second).GetGroup() < 0x0008)   continue; // ignore pure DICOM V3 groups
1183          if ((*tag2->second).GetElement() %2)       continue; // ignore shadow groups
1184          if ((*tag2->second).GetVR() == "SQ" )      continue; // ignore Sequences
1185          // TODO : find a trick to *skip* the SeQuences !
1186          // Not only ignore the SQ element
1187          // --> will be done with the next organization
1188          if ((*tag2->second).GetGroup() == 0xfffe ) continue; // ignore delimiters      
1189       }
1190       WriteEntry(tag2->second,_fp,type);
1191       if (itsTimeToWritePixels) 
1192          break;
1193    }
1194 }
1195
1196 /**
1197  * \ingroup gdcmParser
1198  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1199  *          processor order.
1200  * @return  The properly swaped 32 bits integer.
1201  */
1202 guint32 gdcmParser::SwapLong(guint32 a) {
1203    switch (sw) {
1204       case    0 :
1205          break;
1206       case 4321 :
1207          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
1208              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1209          break;
1210    
1211       case 3412 :
1212          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1213          break;
1214    
1215       case 2143 :
1216          a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1217          break;
1218       default :
1219          dbg.Error(" gdcmParser::SwapLong : unset swap code");
1220          a=0;
1221    }
1222    return(a);
1223 }
1224
1225 /**
1226  * \ingroup gdcmParser
1227  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
1228  *          processor order.
1229  * @return  The properly unswaped 32 bits integer.
1230  */
1231 guint32 gdcmParser::UnswapLong(guint32 a) {
1232    return (SwapLong(a));
1233 }
1234
1235 /**
1236  * \ingroup gdcmParser
1237  * \brief   Swaps the bytes so they agree with the processor order
1238  * @return  The properly swaped 16 bits integer.
1239  */
1240 guint16 gdcmParser::SwapShort(guint16 a) {
1241    if ( (sw==4321)  || (sw==2143) )
1242       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1243    return (a);
1244 }
1245
1246 /**
1247  * \ingroup gdcmParser
1248  * \brief   Unswaps the bytes so they agree with the processor order
1249  * @return  The properly unswaped 16 bits integer.
1250  */
1251 guint16 gdcmParser::UnswapShort(guint16 a) {
1252    return (SwapShort(a));
1253 }
1254
1255 //-----------------------------------------------------------------------------
1256 // Private
1257 /**
1258  * \ingroup gdcmParser
1259  * \brief   Parses the header of the file but WITHOUT loading element values.
1260  * @return  false if file is not ACR-NEMA / DICOM
1261  */
1262 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1263    
1264    rewind(fp);
1265    if (!CheckSwap())
1266       return false;
1267       
1268    gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;   
1269    while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1270      SkipHeaderEntry(newHeaderEntry);
1271      if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) { 
1272         AddHeaderEntry(newHeaderEntry); 
1273      }     
1274    }
1275    return true;
1276 }
1277
1278 /**
1279  * \ingroup gdcmParser
1280  * \brief   Loads the element values of all the Header Entries pointed in the
1281  *          public Chained List.
1282  */
1283 void gdcmParser::LoadHeaderEntries(void) {
1284    rewind(fp);
1285    for (ListTag::iterator i = GetListEntry().begin();
1286       i != GetListEntry().end();
1287       ++i)
1288    {
1289       LoadHeaderEntry(*i);
1290    }
1291             
1292    rewind(fp);
1293
1294    // Load 'non string' values   
1295    std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);   
1296    if( PhotometricInterpretation == "PALETTE COLOR " ) {
1297       LoadEntryVoidArea(0x0028,0x1200);  // gray LUT   
1298       LoadEntryVoidArea(0x0028,0x1201);  // R    LUT
1299       LoadEntryVoidArea(0x0028,0x1202);  // G    LUT
1300       LoadEntryVoidArea(0x0028,0x1203);  // B    LUT
1301       
1302       LoadEntryVoidArea(0x0028,0x1221);  // Segmented Red   Palette Color LUT Data
1303       LoadEntryVoidArea(0x0028,0x1222);  // Segmented Green Palette Color LUT Data
1304       LoadEntryVoidArea(0x0028,0x1223);  // Segmented Blue  Palette Color LUT Data
1305    } 
1306    //FIXME : how to use it?
1307    LoadEntryVoidArea(0x0028,0x3006);  //LUT Data (CTX dependent)     
1308    
1309    // --------------------------------------------------------------
1310    // Special Patch to allow gdcm to read ACR-LibIDO formated images
1311    //
1312    // if recognition code tells us we deal with a LibIDO image
1313    // we switch lineNumber and columnNumber
1314    //
1315    std::string RecCode;
1316    RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1317    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1318        RecCode == "CANRME_AILIBOD1_1." ) 
1319    {
1320          filetype = ACR_LIBIDO; 
1321          std::string rows    = GetEntryByNumber(0x0028, 0x0010);
1322          std::string columns = GetEntryByNumber(0x0028, 0x0011);
1323          SetEntryByNumber(columns, 0x0028, 0x0010);
1324          SetEntryByNumber(rows   , 0x0028, 0x0011);
1325    }
1326    // ----------------- End of Special Patch ----------------
1327 }
1328
1329 /**
1330  * \ingroup       gdcmParser
1331  * \brief         Loads the element content if its length doesn't exceed
1332  *                the value specified with gdcmParser::SetMaxSizeLoadEntry()
1333  * @param         Entry Header Entry (Dicom Element) to be dealt with
1334  */
1335 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry)  {
1336    size_t item_read;
1337    guint16 group  = Entry->GetGroup();
1338    std::string  vr= Entry->GetVR();
1339    guint32 length = Entry->GetLength();
1340    bool SkipLoad  = false;
1341
1342    fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1343    
1344    // the test was commented out to 'go inside' the SeQuences
1345    // we don't any longer skip them !
1346     
1347    // if( vr == "SQ" )  //  (DO NOT remove this comment)
1348    //    SkipLoad = true;
1349
1350    // A SeQuence "contains" a set of Elements.  
1351    //          (fffe e000) tells us an Element is beginning
1352    //          (fffe e00d) tells us an Element just ended
1353    //          (fffe e0dd) tells us the current SeQuence just ended
1354    if( group == 0xfffe )
1355       SkipLoad = true;
1356
1357    if ( SkipLoad ) {
1358       Entry->SetLength(0);
1359       Entry->SetValue("gdcm::Skipped");
1360       return;
1361    }
1362
1363    // When the length is zero things are easy:
1364    if ( length == 0 ) {
1365       Entry->SetValue("");
1366       return;
1367    }
1368
1369    // The elements whose length is bigger than the specified upper bound
1370    // are not loaded. Instead we leave a short notice of the offset of
1371    // the element content and it's length.
1372    if (length > MaxSizeLoadEntry) {
1373       std::ostringstream s;
1374       s << "gdcm::NotLoaded.";
1375       s << " Address:" << (long)Entry->GetOffset();
1376       s << " Length:"  << Entry->GetLength();
1377       s << " x(" << std::hex << Entry->GetLength() << ")";
1378       Entry->SetValue(s.str());
1379       return;
1380    }
1381    
1382    // When integer(s) are expected, read and convert the following 
1383    // n *(two or four bytes)
1384    // properly i.e. as integers as opposed to strings.
1385    // Elements with Value Multiplicity > 1
1386    // contain a set of integers (not a single one) 
1387     
1388    // Any compacter code suggested (?)
1389    if ( IsHeaderEntryAnInteger(Entry) ) {   
1390       guint32 NewInt;
1391       std::ostringstream s;
1392       int nbInt;
1393       if (vr == "US" || vr == "SS") {
1394          nbInt = length / 2;
1395          NewInt = ReadInt16();
1396          s << NewInt;
1397          if (nbInt > 1){
1398             for (int i=1; i < nbInt; i++) {
1399                s << '\\';
1400                NewInt = ReadInt16();
1401                s << NewInt;
1402             }
1403          }
1404       }
1405       else if (vr == "UL" || vr == "SL") {
1406          nbInt = length / 4;
1407          NewInt = ReadInt32();
1408          s << NewInt;
1409          if (nbInt > 1) {
1410             for (int i=1; i < nbInt; i++) {
1411                s << '\\';
1412                NewInt = ReadInt32();
1413                s << NewInt;
1414             }
1415          }
1416       }
1417 #ifdef GDCM_NO_ANSI_STRING_STREAM
1418       s << std::ends; // to avoid oddities on Solaris
1419 #endif //GDCM_NO_ANSI_STRING_STREAM
1420
1421       Entry->SetValue(s.str());
1422       return;
1423    }
1424    
1425    // We need an additional byte for storing \0 that is not on disk
1426    std::string NewValue(length,0);
1427    item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1428    if ( item_read != 1 ) {
1429       dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1430       Entry->SetValue("gdcm::UnRead");
1431       return;
1432    }
1433
1434    if( (vr == "UI") ) // Because of correspondance with the VR dic
1435       Entry->SetValue(NewValue.c_str());
1436    else
1437       Entry->SetValue(NewValue);
1438 }
1439
1440 /**
1441  * \ingroup gdcmParser
1442  * \brief   add a new Dicom Element pointer to 
1443  *          the H Table and at the end of the chained List
1444  * \warning push_bash in listEntries ONLY during ParseHeader
1445  * \todo    something to allow further Elements addition,
1446  *          (at their right place in the chained list)
1447  *          when position to be taken care of     
1448  * @param   newHeaderEntry
1449  */
1450 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1451    tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1452    listEntries.push_back(newHeaderEntry); 
1453    wasUpdated = 1;
1454 }
1455
1456 /**
1457  * \ingroup gdcmParser
1458  * \brief  Find the value Length of the passed Header Entry
1459  * @param  Entry Header Entry whose length of the value shall be loaded. 
1460  */
1461  void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1462    guint16 element = Entry->GetElement();
1463    guint16 group   = Entry->GetGroup();
1464    std::string  vr = Entry->GetVR();
1465    guint16 length16;
1466    
1467    if( (element == NumPixel) && (group == GrPixel) ) 
1468    {
1469       dbg.SetDebug(GDCM_DEBUG);
1470       dbg.Verbose(2, "gdcmParser::FindLength: ",
1471                      "we reached (GrPixel,NumPixel)");
1472    }   
1473    
1474    if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) ) 
1475    {
1476       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) 
1477       {
1478          // The following reserved two bytes (see PS 3.5-2001, section
1479          // 7.1.2 Data element structure with explicit vr p27) must be
1480          // skipped before proceeding on reading the length on 4 bytes.
1481          fseek(fp, 2L, SEEK_CUR);
1482          guint32 length32 = ReadInt32();
1483
1484          if ( (vr == "OB") && (length32 == 0xffffffff) ) 
1485          {
1486             Entry->SetLength(FindHeaderEntryLengthOB());
1487             return;
1488          }
1489          FixHeaderEntryFoundLength(Entry, length32); 
1490          return;
1491       }
1492
1493       // Length is encoded on 2 bytes.
1494       length16 = ReadInt16();
1495       
1496       // We can tell the current file is encoded in big endian (like
1497       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1498       // and it's value is the one of the encoding of a big endian file.
1499       // In order to deal with such big endian encoded files, we have
1500       // (at least) two strategies:
1501       // * when we load the "Transfer Syntax" tag with value of big endian
1502       //   encoding, we raise the proper flags. Then we wait for the end
1503       //   of the META group (0x0002) among which is "Transfer Syntax",
1504       //   before switching the swap code to big endian. We have to postpone
1505       //   the switching of the swap code since the META group is fully encoded
1506       //   in little endian, and big endian coding only starts at the next
1507       //   group. The corresponding code can be hard to analyse and adds
1508       //   many additional unnecessary tests for regular tags.
1509       // * the second strategy consists in waiting for trouble, that shall
1510       //   appear when we find the first group with big endian encoding. This
1511       //   is easy to detect since the length of a "Group Length" tag (the
1512       //   ones with zero as element number) has to be of 4 (0x0004). When we
1513       //   encounter 1024 (0x0400) chances are the encoding changed and we
1514       //   found a group with big endian encoding.
1515       // We shall use this second strategy. In order to make sure that we
1516       // can interpret the presence of an apparently big endian encoded
1517       // length of a "Group Length" without committing a big mistake, we
1518       // add an additional check: we look in the already parsed elements
1519       // for the presence of a "Transfer Syntax" whose value has to be "big
1520       // endian encoding". When this is the case, chances are we have got our
1521       // hands on a big endian encoded file: we switch the swap code to
1522       // big endian and proceed...
1523       if ( (element  == 0x0000) && (length16 == 0x0400) ) 
1524       {
1525          if ( ! IsExplicitVRBigEndianTransferSyntax() ) 
1526          {
1527             dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1528             errno = 1;
1529             return;
1530          }
1531          length16 = 4;
1532          SwitchSwapToBigEndian();
1533          // Restore the unproperly loaded values i.e. the group, the element
1534          // and the dictionary entry depending on them.
1535          guint16 CorrectGroup   = SwapShort(Entry->GetGroup());
1536          guint16 CorrectElem    = SwapShort(Entry->GetElement());
1537          gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1538                                                        CorrectElem);
1539          if (!NewTag) 
1540          {
1541             // This correct tag is not in the dictionary. Create a new one.
1542             NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1543          }
1544          // FIXME this can create a memory leaks on the old entry that be
1545          // left unreferenced.
1546          Entry->SetDictEntry(NewTag);
1547       }
1548        
1549       // Heuristic: well some files are really ill-formed.
1550       if ( length16 == 0xffff) 
1551       {
1552          length16 = 0;
1553          //dbg.Verbose(0, "gdcmParser::FindLength",
1554          //            "Erroneous element length fixed.");
1555          // Actually, length= 0xffff means that we deal with
1556          // Unknown Sequence Length 
1557       }
1558       FixHeaderEntryFoundLength(Entry, (guint32)length16);
1559       return;
1560    }
1561    else
1562    {
1563       // Either implicit VR or a non DICOM conformal (see note below) explicit
1564       // VR that ommited the VR of (at least) this element. Farts happen.
1565       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1566       // on Data elements "Implicit and Explicit VR Data Elements shall
1567       // not coexist in a Data Set and Data Sets nested within it".]
1568       // Length is on 4 bytes.
1569       
1570       FixHeaderEntryFoundLength(Entry, ReadInt32());
1571       return;
1572    }
1573 }
1574
1575 /**
1576  * \ingroup   gdcmParser
1577  * \brief     Find the Value Representation of the current Dicom Element.
1578  * @param     Entry
1579  */
1580 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry) 
1581 {
1582    if (filetype != ExplicitVR)
1583       return;
1584
1585    char VR[3];
1586
1587    long PositionOnEntry = ftell(fp);
1588    // Warning: we believe this is explicit VR (Value Representation) because
1589    // we used a heuristic that found "UL" in the first tag. Alas this
1590    // doesn't guarantee that all the tags will be in explicit VR. In some
1591    // cases (see e-film filtered files) one finds implicit VR tags mixed
1592    // within an explicit VR file. Hence we make sure the present tag
1593    // is in explicit VR and try to fix things if it happens not to be
1594    // the case.
1595    
1596    int lgrLue=fread (&VR, (size_t)2,(size_t)1, fp); // lgrLue not used
1597    VR[2]=0;
1598    if(!CheckHeaderEntryVR(Entry,VR))
1599    {
1600       fseek(fp, PositionOnEntry, SEEK_SET);
1601       // When this element is known in the dictionary we shall use, e.g. for
1602       // the semantics (see the usage of IsAnInteger), the VR proposed by the
1603       // dictionary entry. Still we have to flag the element as implicit since
1604       // we know now our assumption on expliciteness is not furfilled.
1605       // avoid  .
1606       if ( Entry->IsVRUnknown() )
1607          Entry->SetVR("Implicit");
1608       Entry->SetImplicitVR();
1609    }
1610 }
1611
1612 /**
1613  * \ingroup   gdcmParser
1614  * \brief     Check the correspondance between the VR of the header entry
1615  *            and the taken VR. If they are different, the header entry is 
1616  *            updated with the new VR.
1617  * @param     Entry Header Entry to check
1618  * @param     vr    Dicom Value Representation
1619  * @return    false if the VR is incorrect of if the VR isn't referenced
1620  *            otherwise, it returns true
1621 */
1622 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1623 {
1624    char msg[100]; // for sprintf
1625    bool RealExplicit = true;
1626
1627    // Assume we are reading a falsely explicit VR file i.e. we reached
1628    // a tag where we expect reading a VR but are in fact we read the
1629    // first to bytes of the length. Then we will interogate (through find)
1630    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1631    // both GCC and VC++ implementations of the STL map. Hence when the
1632    // expected VR read happens to be non-ascii characters we consider
1633    // we hit falsely explicit VR tag.
1634
1635    if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1636       RealExplicit = false;
1637
1638    // CLEANME searching the dicom_vr at each occurence is expensive.
1639    // PostPone this test in an optional integrity check at the end
1640    // of parsing or only in debug mode.
1641    if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1642       RealExplicit= false;
1643
1644    if ( !RealExplicit ) 
1645    {
1646       // We thought this was explicit VR, but we end up with an
1647       // implicit VR tag. Let's backtrack.   
1648       sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", 
1649                    Entry->GetGroup(),Entry->GetElement());
1650       dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1651       if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1652          gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1653                                    Entry->GetGroup(),Entry->GetElement(),
1654                                    "UL","FIXME","Group Length");
1655          Entry->SetDictEntry(NewEntry);     
1656       }
1657       return(false);
1658    }
1659
1660    if ( Entry->IsVRUnknown() ) 
1661    {
1662       // When not a dictionary entry, we can safely overwrite the VR.
1663       if (Entry->GetElement() == 0x0000) { // Group length is UL !
1664          Entry->SetVR("UL");
1665       } else {
1666          Entry->SetVR(vr);
1667       }
1668    }
1669    else if ( Entry->GetVR() != vr ) 
1670    {
1671       // The VR present in the file and the dictionary disagree. We assume
1672       // the file writer knew best and use the VR of the file. Since it would
1673       // be unwise to overwrite the VR of a dictionary (since it would
1674       // compromise it's next user), we need to clone the actual DictEntry
1675       // and change the VR for the read one.
1676       gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1677                                  Entry->GetGroup(),Entry->GetElement(),
1678                                  vr,"FIXME",Entry->GetName());
1679       Entry->SetDictEntry(NewEntry);
1680    }
1681    return(true); 
1682 }
1683
1684 /**
1685  * \ingroup gdcmParser
1686  * \brief   Get the transformed value of the header entry. The VR value 
1687  *          is used to define the transformation to operate on the value
1688  * \warning NOT end user intended method !
1689  * @param   Entry 
1690  * @return  Transformed entry value
1691  */
1692 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1693 {
1694    if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1695    {
1696       std::string val=Entry->GetValue();
1697       std::string vr=Entry->GetVR();
1698       guint32 length = Entry->GetLength();
1699       std::ostringstream s;
1700       int nbInt;
1701
1702       if (vr == "US" || vr == "SS")
1703       {
1704          guint16 NewInt16;
1705
1706          nbInt = length / 2;
1707          for (int i=0; i < nbInt; i++) 
1708          {
1709             if(i!=0)
1710                s << '\\';
1711             NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1712             NewInt16 = SwapShort(NewInt16);
1713             s << NewInt16;
1714          }
1715       }
1716
1717       else if (vr == "UL" || vr == "SL")
1718       {
1719          guint32 NewInt32;
1720
1721          nbInt = length / 4;
1722          for (int i=0; i < nbInt; i++) 
1723          {
1724             if(i!=0)
1725                s << '\\';
1726             NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1727                      ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1728             NewInt32=SwapLong(NewInt32);
1729             s << NewInt32;
1730          }
1731       }
1732 #ifdef GDCM_NO_ANSI_STRING_STREAM
1733       s << std::ends; // to avoid oddities on Solaris
1734 #endif //GDCM_NO_ANSI_STRING_STREAM
1735       return(s.str());
1736    }
1737
1738    return(Entry->GetValue());
1739 }
1740
1741 /**
1742  * \ingroup gdcmParser
1743  * \brief   Get the reverse transformed value of the header entry. The VR 
1744  *          value is used to define the reverse transformation to operate on
1745  *          the value
1746  * \warning NOT end user intended method !
1747  * @param   Entry 
1748  * @return  Reverse transformed entry value
1749  */
1750 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1751 {
1752    if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1753    {
1754       std::string vr=Entry->GetVR();
1755       std::ostringstream s;
1756       std::vector<std::string> tokens;
1757
1758       if (vr == "US" || vr == "SS") 
1759       {
1760          guint16 NewInt16;
1761
1762          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1763          Tokenize (Entry->GetValue(), tokens, "\\");
1764          for (unsigned int i=0; i<tokens.size();i++) 
1765          {
1766             NewInt16 = atoi(tokens[i].c_str());
1767             s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1768          }
1769          tokens.clear();
1770       }
1771       if (vr == "UL" || vr == "SL") 
1772       {
1773          guint32 NewInt32;
1774
1775          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1776          Tokenize (Entry->GetValue(), tokens, "\\");
1777          for (unsigned int i=0; i<tokens.size();i++) 
1778          {
1779             NewInt32 = atoi(tokens[i].c_str());
1780             s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1781                <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1782          }
1783          tokens.clear();
1784       }
1785
1786 #ifdef GDCM_NO_ANSI_STRING_STREAM
1787       s << std::ends; // to avoid oddities on Solaris
1788 #endif //GDCM_NO_ANSI_STRING_STREAM
1789       return(s.str());
1790    }
1791
1792    return(Entry->GetValue());
1793 }
1794
1795 /**
1796  * \ingroup gdcmParser
1797  * \brief   Skip a given Header Entry 
1798  * \warning NOT end user intended method !
1799  * @param   entry 
1800  */
1801 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry) 
1802 {
1803     SkipBytes(entry->GetLength());
1804 }
1805
1806 /**
1807  * \ingroup gdcmParser
1808  * \brief   When the length of an element value is obviously wrong (because
1809  *          the parser went Jabberwocky) one can hope improving things by
1810  *          applying this heuristic.
1811  */
1812 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength) 
1813 {
1814    Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1815      
1816    if ( FoundLength == 0xffffffff) {
1817       FoundLength = 0;
1818    }
1819    
1820    guint16 gr =Entry->GetGroup();
1821    guint16 el =Entry->GetElement(); 
1822      
1823    if (FoundLength%2) {
1824       std::ostringstream s;
1825       s << "Warning : Tag with uneven length " << FoundLength 
1826          <<  " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1827       dbg.Verbose(0,s.str().c_str());
1828    }
1829       
1830    // Sorry for the patch!  
1831    // XMedCom did the trick to read some nasty GE images ...
1832    if (FoundLength == 13) {
1833       // The following 'if' will be removed when there is no more
1834       // images on Creatis HDs with a 13 length for Manufacturer...
1835       if ( (Entry->GetGroup() != 0x0008) ||  
1836            ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1837       // end of remove area
1838          FoundLength =10;
1839          Entry->SetReadLength(10); // a bug is to be fixed
1840       }
1841    }
1842
1843    // to fix some garbage 'Leonardo' Siemens images
1844    // May be commented out to avoid overhead
1845    else if ( (Entry->GetGroup() == 0x0009) &&
1846        ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1847       FoundLength =4;
1848       Entry->SetReadLength(4); // a bug is to be fixed 
1849    } 
1850    // end of fix
1851  
1852    // to try to 'go inside' SeQuences (with length), and not to skip them        
1853    else if ( Entry->GetVR() == "SQ") 
1854    { 
1855       if (enableSequences)    // only if the user does want to !
1856          FoundLength =0;      // ReadLength is unchanged 
1857    } 
1858     
1859    // a SeQuence Element is beginning                                          
1860    // fffe|e000 is just a marker, its length *should be* zero                                               
1861    else if(Entry->GetGroup() == 0xfffe)
1862    { 
1863                                          // *normally, fffe|0000 doesn't exist ! 
1864      if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1865                                          // causes extra troubles :-(                                                        
1866          FoundLength =0;
1867    }         
1868    Entry->SetUsableLength(FoundLength);
1869 }
1870
1871 /**
1872  * \ingroup gdcmParser
1873  * \brief   Apply some heuristics to predict whether the considered 
1874  *          element value contains/represents an integer or not.
1875  * @param   Entry The element value on which to apply the predicate.
1876  * @return  The result of the heuristical predicate.
1877  */
1878 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1879    guint16 element = Entry->GetElement();
1880    guint16 group   = Entry->GetGroup();
1881    std::string  vr = Entry->GetVR();
1882    guint32 length  = Entry->GetLength();
1883    // When we have some semantics on the element we just read, and if we
1884    // a priori know we are dealing with an integer, then we shall be
1885    // able to swap it's element value properly.
1886    if ( element == 0 )  // This is the group length of the group
1887    {  
1888       if (length == 4)
1889          return true;
1890       else 
1891       {
1892          std::ostringstream s;
1893          int filePosition = ftell(fp);
1894          s << "Erroneous Group Length element length  on : (" \
1895            << std::hex << group << " , " << element 
1896            << ") -before- position x(" << filePosition << ")"
1897            << "lgt : " << length;
1898          // These 2 lines commented out : a *very dirty* patch
1899          // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1900          // have a glance at offset  x(8336) ...
1901          // For *regular* headers, the test is useless..
1902          // lets's print a warning message and go on, 
1903          // instead of giving up with an error message
1904
1905          //std::cout << s.str().c_str() << std::endl;
1906          // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1907          //           s.str().c_str());     
1908       }
1909    }
1910    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1911       return true;
1912    
1913    return false;
1914 }
1915 /**
1916  * \ingroup gdcmParser
1917  * \brief  Find the Length till the next sequence delimiter
1918  * \warning NOT end user intended method !
1919  * @return 
1920  */
1921
1922  guint32 gdcmParser::FindHeaderEntryLengthOB(void)  {
1923    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1924    guint16 g;
1925    guint16 n; 
1926    long PositionOnEntry = ftell(fp);
1927    bool FoundSequenceDelimiter = false;
1928    guint32 TotalLength = 0;
1929    guint32 ItemLength;
1930
1931    while ( ! FoundSequenceDelimiter) 
1932    {
1933       g = ReadInt16();
1934       n = ReadInt16();   
1935       if (errno == 1)
1936          return 0;
1937       TotalLength += 4;  // We even have to decount the group and element 
1938      
1939       if ( g != 0xfffe && g!=0xb00c ) //for bogus header  
1940       {
1941          char msg[100]; // for sprintf. Sorry
1942          sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1943          dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg); 
1944          errno = 1;
1945          return 0;
1946       }
1947       if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header 
1948          FoundSequenceDelimiter = true;
1949       else if ( n != 0xe000 )
1950       {
1951          char msg[100];  // for sprintf. Sorry
1952          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1953                       n, g,n);
1954          dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1955          errno = 1;
1956          return 0;
1957       }
1958       ItemLength = ReadInt32();
1959       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
1960                                       // the ItemLength with ReadInt32                                     
1961       SkipBytes(ItemLength);
1962    }
1963    fseek(fp, PositionOnEntry, SEEK_SET);
1964    return TotalLength;
1965 }
1966
1967 /**
1968  * \ingroup gdcmParser
1969  * \brief Reads a supposed to be 16 Bits integer
1970  *       (swaps it depending on processor endianity) 
1971  * @return read value
1972  */
1973 guint16 gdcmParser::ReadInt16(void) {
1974    guint16 g;
1975    size_t item_read;
1976    item_read = fread (&g, (size_t)2,(size_t)1, fp);
1977    if ( item_read != 1 ) {
1978       if(ferror(fp)) 
1979          dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1980       errno = 1;
1981       return 0;
1982    }
1983    errno = 0;
1984    g = SwapShort(g);   
1985    return g;
1986 }
1987
1988 /**
1989  * \ingroup gdcmParser
1990  * \brief  Reads a supposed to be 32 Bits integer
1991  *         (swaps it depending on processor endianity)  
1992  * @return read value
1993  */
1994 guint32 gdcmParser::ReadInt32(void) {
1995    guint32 g;
1996    size_t item_read;
1997    item_read = fread (&g, (size_t)4,(size_t)1, fp);
1998    if ( item_read != 1 ) { 
1999      if(ferror(fp)) 
2000          dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");   
2001       errno = 1;
2002       return 0;
2003    }
2004    errno = 0;   
2005    g = SwapLong(g);
2006    return g;
2007 }
2008
2009 /**
2010  * \ingroup gdcmParser
2011  * \brief skips bytes inside the source file 
2012  * \warning NOT end user intended method !
2013  * @return 
2014  */
2015 void gdcmParser::SkipBytes(guint32 NBytes) {
2016    //FIXME don't dump the returned value
2017    (void)fseek(fp, (long)NBytes, SEEK_CUR);
2018 }
2019
2020 /**
2021  * \ingroup gdcmParser
2022  * \brief Loads all the needed Dictionaries
2023  * \warning NOT end user intended method !   
2024  */
2025 void gdcmParser::Initialise(void) 
2026 {
2027    RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2028    RefShaDict = (gdcmDict*)0;
2029 }
2030
2031 /**
2032  * \ingroup gdcmParser
2033  * \brief   Discover what the swap code is (among little endian, big endian,
2034  *          bad little endian, bad big endian).
2035  *          sw is set
2036  * @return false when we are absolutely sure 
2037  *               it's neither ACR-NEMA nor DICOM
2038  *         true  when we hope ours assuptions are OK
2039  */
2040 bool gdcmParser::CheckSwap() {
2041
2042    // The only guaranted way of finding the swap code is to find a
2043    // group tag since we know it's length has to be of four bytes i.e.
2044    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2045    // occurs when we can't find such group...
2046    
2047    guint32  x=4;  // x : for ntohs
2048    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2049    guint32  s32;
2050    guint16  s16;
2051        
2052    int lgrLue;
2053    char *entCur;
2054    char deb[HEADER_LENGTH_TO_READ];
2055     
2056    // First, compare HostByteOrder and NetworkByteOrder in order to
2057    // determine if we shall need to swap bytes (i.e. the Endian type).
2058    if (x==ntohs(x))
2059       net2host = true;
2060    else
2061       net2host = false; 
2062          
2063    // The easiest case is the one of a DICOM header, since it possesses a
2064    // file preamble where it suffice to look for the string "DICM".
2065    lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2066    
2067    entCur = deb + 128;
2068    if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2069       dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2070       
2071       // Next, determine the value representation (VR). Let's skip to the
2072       // first element (0002, 0000) and check there if we find "UL" 
2073       // - or "OB" if the 1st one is (0002,0001) -,
2074       // in which case we (almost) know it is explicit VR.
2075       // WARNING: if it happens to be implicit VR then what we will read
2076       // is the length of the group. If this ascii representation of this
2077       // length happens to be "UL" then we shall believe it is explicit VR.
2078       // FIXME: in order to fix the above warning, we could read the next
2079       // element value (or a couple of elements values) in order to make
2080       // sure we are not commiting a big mistake.
2081       // We need to skip :
2082       // * the 128 bytes of File Preamble (often padded with zeroes),
2083       // * the 4 bytes of "DICM" string,
2084       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2085       // i.e. a total of  136 bytes.
2086       entCur = deb + 136;
2087      
2088       // FIXME : FIXME:
2089       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2090       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2091       // *Implicit* VR.  -and it is !- 
2092       
2093       if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2094           (memcmp(entCur, "OB", (size_t)2) == 0) ||
2095           (memcmp(entCur, "UI", (size_t)2) == 0) ||
2096           (memcmp(entCur, "CS", (size_t)2) == 0) )  // CS, to remove later
2097                                                     // when Write DCM *adds*
2098       // FIXME
2099       // Use gdcmParser::dicom_vr to test all the possibilities
2100       // instead of just checking for UL, OB and UI !? group 0000 
2101       {
2102          filetype = ExplicitVR;
2103          dbg.Verbose(1, "gdcmParser::CheckSwap:",
2104                      "explicit Value Representation");
2105       } 
2106       else 
2107       {
2108          filetype = ImplicitVR;
2109          dbg.Verbose(1, "gdcmParser::CheckSwap:",
2110                      "not an explicit Value Representation");
2111       }
2112       
2113       if (net2host) 
2114       {
2115          sw = 4321;
2116          dbg.Verbose(1, "gdcmParser::CheckSwap:",
2117                         "HostByteOrder != NetworkByteOrder");
2118       } 
2119       else 
2120       {
2121          sw = 0;
2122          dbg.Verbose(1, "gdcmParser::CheckSwap:",
2123                         "HostByteOrder = NetworkByteOrder");
2124       }
2125       
2126       // Position the file position indicator at first tag (i.e.
2127       // after the file preamble and the "DICM" string).
2128       rewind(fp);
2129       fseek (fp, 132L, SEEK_SET);
2130       return true;
2131    } // End of DicomV3
2132
2133    // Alas, this is not a DicomV3 file and whatever happens there is no file
2134    // preamble. We can reset the file position indicator to where the data
2135    // is (i.e. the beginning of the file).
2136    dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2137    rewind(fp);
2138
2139    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2140    // By clean we mean that the length of the first tag is written down.
2141    // If this is the case and since the length of the first group HAS to be
2142    // four (bytes), then determining the proper swap code is straightforward.
2143
2144    entCur = deb + 4;
2145    // We assume the array of char we are considering contains the binary
2146    // representation of a 32 bits integer. Hence the following dirty
2147    // trick :
2148    s32 = *((guint32 *)(entCur));
2149       
2150    switch (s32) {
2151       case 0x00040000 :
2152          sw = 3412;
2153          filetype = ACR;
2154          return true;
2155       case 0x04000000 :
2156          sw = 4321;
2157          filetype = ACR;
2158          return true;
2159       case 0x00000400 :
2160          sw = 2143;
2161          filetype = ACR;
2162          return true;
2163       case 0x00000004 :
2164          sw = 0;
2165          filetype = ACR;
2166          return true;
2167       default :
2168
2169       // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2170       // It is time for despaired wild guesses. 
2171       // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2172       //  i.e. the 'group length' element is not present :     
2173       
2174       //  check the supposed to be 'group number'
2175       //  0x0002 or 0x0004 or 0x0008
2176       //  to determine ' sw' value .
2177       //  Only 0 or 4321 will be possible 
2178       //  (no oportunity to check for the formerly well known
2179       //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2180       //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-) 
2181       //  the file IS NOT ACR-NEMA nor DICOM V3
2182       //  Find a trick to tell it the caller...
2183       
2184       s16 = *((guint16 *)(deb));
2185       
2186       switch (s16) {
2187       case 0x0002 :
2188       case 0x0004 :
2189       case 0x0008 :      
2190          sw = 0;
2191          filetype = ACR;
2192          return true;
2193       case 0x0200 :
2194       case 0x0400 :
2195       case 0x0800 : 
2196          sw = 4321;
2197          filetype = ACR;
2198          return true;
2199       default :
2200          dbg.Verbose(0, "gdcmParser::CheckSwap:",
2201                      "ACR/NEMA unfound swap info (Really hopeless !)"); 
2202          filetype = Unknown;     
2203          return false;
2204       }
2205       
2206       // Then the only info we have is the net2host one.
2207       //if (! net2host )
2208          //   sw = 0;
2209          //else
2210          //  sw = 4321;
2211          //return;
2212    }
2213 }
2214
2215 /**
2216  * \ingroup gdcmParser
2217  * \brief Restore the unproperly loaded values i.e. the group, the element
2218  *        and the dictionary entry depending on them. 
2219  */
2220 void gdcmParser::SwitchSwapToBigEndian(void) 
2221 {
2222    dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2223                   "Switching to BigEndian mode.");
2224    if ( sw == 0    ) 
2225    {
2226       sw = 4321;
2227       return;
2228    }
2229    if ( sw == 4321 ) 
2230    {
2231       sw = 0;
2232       return;
2233    }
2234    if ( sw == 3412 ) 
2235    {
2236       sw = 2143;
2237       return;
2238    }
2239    if ( sw == 2143 )
2240       sw = 3412;
2241 }
2242
2243 /**
2244  * \ingroup gdcmParser
2245  * \brief  during parsing, Header Elements too long are not loaded in memory 
2246  * @param NewSize
2247  */
2248 void gdcmParser::SetMaxSizeLoadEntry(long NewSize) 
2249 {
2250    if (NewSize < 0)
2251       return;
2252    if ((guint32)NewSize >= (guint32)0xffffffff) 
2253    {
2254       MaxSizeLoadEntry = 0xffffffff;
2255       return;
2256    }
2257    MaxSizeLoadEntry = NewSize;
2258 }
2259
2260
2261 /**
2262  * \ingroup gdcmParser
2263  * \brief Header Elements too long will not be printed
2264  * \warning 
2265  * \todo : not yet usable 
2266  *          (see MAX_SIZE_PRINT_ELEMENT_VALUE 
2267  *           in gdcmHeaderEntry gdcmLoadEntry)
2268  *             
2269  * @param NewSize
2270  */
2271 void gdcmParser::SetMaxSizePrintEntry(long NewSize) 
2272 {
2273    if (NewSize < 0)
2274       return;
2275    if ((guint32)NewSize >= (guint32)0xffffffff) 
2276    {
2277       MaxSizePrintEntry = 0xffffffff;
2278       return;
2279    }
2280    MaxSizePrintEntry = NewSize;
2281 }
2282
2283 /**
2284  * \ingroup gdcmParser
2285  * \brief   Searches both the public and the shadow dictionary (when they
2286  *          exist) for the presence of the DictEntry with given name.
2287  *          The public dictionary has precedence on the shadow one.
2288  * @param   Name name of the searched DictEntry
2289  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2290  */
2291 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name) 
2292 {
2293    gdcmDictEntry *found = (gdcmDictEntry *)0;
2294    if (!RefPubDict && !RefShaDict) 
2295    {
2296       dbg.Verbose(0, "gdcmParser::GetDictEntry",
2297                      "we SHOULD have a default dictionary");
2298    }
2299    if (RefPubDict) 
2300    {
2301       found = RefPubDict->GetDictEntryByName(Name);
2302       if (found)
2303          return found;
2304    }
2305    if (RefShaDict) 
2306    {
2307       found = RefShaDict->GetDictEntryByName(Name);
2308       if (found)
2309          return found;
2310    }
2311    return found;
2312 }
2313
2314 /**
2315  * \ingroup gdcmParser
2316  * \brief   Searches both the public and the shadow dictionary (when they
2317  *          exist) for the presence of the DictEntry with given
2318  *          group and element. The public dictionary has precedence on the
2319  *          shadow one.
2320  * @param   group   group of the searched DictEntry
2321  * @param   element element of the searched DictEntry
2322  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2323  */
2324 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element) 
2325 {
2326    gdcmDictEntry *found = (gdcmDictEntry *)0;
2327    if (!RefPubDict && !RefShaDict) 
2328    {
2329       dbg.Verbose(0, "gdcmParser::GetDictEntry",
2330                      "we SHOULD have a default dictionary");
2331    }
2332    if (RefPubDict) 
2333    {
2334       found = RefPubDict->GetDictEntryByNumber(group, element);
2335       if (found)
2336          return found;
2337    }
2338    if (RefShaDict) 
2339    {
2340       found = RefShaDict->GetDictEntryByNumber(group, element);
2341       if (found)
2342          return found;
2343    }
2344    return found;
2345 }
2346
2347 /**
2348  * \ingroup gdcmParser
2349  * \brief   Read the next tag but WITHOUT loading it's value
2350  * @return  On succes the newly created HeaderEntry, NULL on failure.      
2351  */
2352 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2353    guint16 g,n;
2354    gdcmHeaderEntry *NewEntry;
2355    g = ReadInt16();
2356    n = ReadInt16();
2357       
2358    if (errno == 1)
2359       // We reached the EOF (or an error occured) therefore 
2360       // header parsing has to be considered as finished.
2361       return (gdcmHeaderEntry *)0;
2362
2363 // Pb : how to propagate the element length (used in SkipHeaderEntry)
2364 //       direct call to SkipBytes ?
2365    
2366 //   if (ignoreShadow == 1 && g%2 ==1)
2367       // if user wants to skip shadow groups
2368       // and current element *is* a shadow element
2369       // we don't create anything
2370 //      return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2371   
2372    NewEntry = NewHeaderEntryByNumber(g, n);
2373    FindHeaderEntryVR(NewEntry);
2374    FindHeaderEntryLength(NewEntry);
2375
2376    if (errno == 1) {
2377       // Call it quits
2378       return NULL;
2379    }
2380    NewEntry->SetOffset(ftell(fp));  
2381    return NewEntry;
2382 }
2383
2384 /**
2385  * \ingroup gdcmParser
2386  * \brief   Build a new Element Value from all the low level arguments. 
2387  *          Check for existence of dictionary entry, and build
2388  *          a default one when absent.
2389  * @param   Name    Name of the underlying DictEntry
2390  */
2391 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name) 
2392 {
2393    gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2394    if (!NewTag)
2395       NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2396
2397    gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2398    if (!NewEntry) 
2399    {
2400       dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2401                   "failed to allocate gdcmHeaderEntry");
2402       return (gdcmHeaderEntry *)0;
2403    }
2404    return NewEntry;
2405 }  
2406
2407 /**
2408  * \ingroup gdcmParser
2409  * \brief   Request a new virtual dict entry to the dict set
2410  * @param   group  group   of the underlying DictEntry
2411  * @param   element  element of the underlying DictEntry
2412  * @param   vr     VR of the underlying DictEntry
2413  * @param   fourth owner group
2414  * @param   name   english name
2415  */
2416 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2417                                                std::string vr,
2418                                                std::string fourth,
2419                                                std::string name)
2420 {
2421    return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2422 }
2423
2424 /**
2425  * \ingroup gdcmParser
2426  * \brief   Build a new Element Value from all the low level arguments. 
2427  *          Check for existence of dictionary entry, and build
2428  *          a default one when absent.
2429  * @param   Group group   of the underlying DictEntry
2430  * @param   Elem  element of the underlying DictEntry
2431  */
2432 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem) 
2433 {
2434    // Find out if the tag we encountered is in the dictionaries:
2435    gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2436    if (!DictEntry)
2437       DictEntry = NewVirtualDictEntry(Group, Elem);
2438
2439    gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2440    if (!NewEntry) 
2441    {
2442       dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2443                   "failed to allocate gdcmHeaderEntry");
2444       return NULL;
2445    }
2446    return NewEntry;
2447 }
2448
2449 // Never used; commented out, waiting for removal.
2450 /**
2451  * \ingroup gdcmParser
2452  * \brief   Small utility function that creates a new manually crafted
2453  *          (as opposed as read from the file) gdcmHeaderEntry with user
2454  *          specified name and adds it to the public tag hash table.
2455  * \note    A fake TagKey is generated so the PubDict can keep it's coherence.
2456  * @param   NewTagName The name to be given to this new tag.
2457  * @param   VR The Value Representation to be given to this new tag.
2458  * @return  The newly hand crafted Element Value.
2459  */
2460 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName, 
2461 //                                                           std::string VR) 
2462 //{
2463 //   gdcmHeaderEntry *NewEntry = NULL;
2464 //   guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
2465 //   guint32 FreeElem = 0;
2466 //   gdcmDictEntry *DictEntry = NULL;
2467 //
2468 //   FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2469 //   if (FreeElem == UINT32_MAX) 
2470 //   {
2471 //      dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2472 //                     "Group 0xffff in Public Dict is full");
2473 //      return NULL;
2474 //   }
2475 //
2476 //   DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2477 //                                VR, "GDCM", NewTagName);
2478 //   NewEntry = new gdcmHeaderEntry(DictEntry);
2479 //   AddHeaderEntry(NewEntry);
2480 //   return NewEntry;
2481 //}
2482
2483 /**
2484  * \ingroup gdcmParser
2485  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2486  *          in the TagHt dictionary.
2487  * @param   group The generated tag must belong to this group.  
2488  * @return  The element of tag with given group which is fee.
2489  */
2490 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group) 
2491 {
2492    for (guint32 elem = 0; elem < UINT32_MAX; elem++) 
2493    {
2494       TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2495       if (tagHT.count(key) == 0)
2496          return elem;
2497    }
2498    return UINT32_MAX;
2499 }
2500
2501 //-----------------------------------------------------------------------------