]> Creatis software - gdcm.git/blob - src/gdcmParser.cxx
510742a5687f9505c38f48efb905cab7f51d55ef
[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    if ( type == ACR ) 
1025    { 
1026       if (gr < 0x0008)   return; // ignore pure DICOM V3 groups
1027       if (gr %2)         return; // ignore shadow groups
1028       if (vr == "SQ" )   return; // ignore Sequences
1029       // TODO : find a trick to *skip* the SeQuences !
1030       // Not only ignore the SQ element
1031       if (gr == 0xfffe ) return; // ignore delimiters
1032    } 
1033
1034    fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp);  //group
1035    fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp);  //element
1036       
1037    if ( (type == ExplicitVR) || (type == DICOMDIR) ) {
1038       // EXPLICIT VR
1039       guint16 z=0, shortLgr;
1040
1041       if (gr == 0xfffe) { // NO Value Representation for 'delimiters'
1042                           // no length : write ffffffff
1043
1044           // special patch to make some MR PHILIPS images e-film readable
1045           // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1046           // from Hospital Guy de Chauliac, Montpellier
1047           // we just ignore spurious fffe|0000 tag !
1048           if (el == 0x0000) return;
1049
1050          fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1051          return;       // NO value for 'delimiters'
1052       }
1053
1054       shortLgr=lgr;
1055       if (vr == "unkn") {     // Unknown was 'written'
1056          // deal with Little Endian            
1057          fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1058          fwrite ( &z,  (size_t)2 ,(size_t)1 ,_fp);
1059       } else {
1060          fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);                     
1061          if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1062          {
1063             fwrite ( &z,  (size_t)2 ,(size_t)1 ,_fp);
1064             fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1065          } else {
1066             fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1067          }
1068       }
1069    } 
1070    else // IMPLICIT VR 
1071    { 
1072       fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1073    }
1074       
1075    // === Deal with the value
1076    //     -------------------
1077    if (vr == "SQ")  return; // no "value" to write for the SEQuences
1078    if (gr == 0xfffe)return; // no "value" to write for the delimiters
1079       
1080    if (voidArea != NULL) 
1081    { // there is a 'non string' LUT, overlay, etc
1082       fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1083       return;            
1084    }
1085       
1086    if (vr == "US" || vr == "SS") 
1087    {
1088       tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1089       Tokenize (tag->GetValue(), tokens, "\\");
1090       for (unsigned int i=0; i<tokens.size();i++) 
1091       {
1092          val_uint16 = atoi(tokens[i].c_str());
1093          ptr = &val_uint16;
1094          fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1095       }
1096       tokens.clear();
1097       return;
1098    }
1099
1100    if (vr == "UL" || vr == "SL") 
1101    {
1102       tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1103       Tokenize (tag->GetValue(), tokens, "\\");
1104       for (unsigned int i=0; i<tokens.size();i++) 
1105       {
1106          val_uint32 = atoi(tokens[i].c_str());
1107          ptr = &val_uint32;
1108          fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1109       }
1110       tokens.clear();
1111       return;
1112    } 
1113           
1114    // Pixels are never loaded in the element !
1115    // we stop writting when Pixel are processed
1116    // FIX : we loose trailing elements (RAB, right now)           
1117             
1118    if ((gr == GrPixel) && (el == NumPixel) ) {
1119       compte++;
1120       if (compte == countGrPixel) {// we passed *all* the GrPixel,NumPixel   
1121          itsTimeToWritePixels = true;
1122          return;
1123       }
1124    }       
1125    fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1126 }
1127
1128 /**
1129  * \ingroup gdcmParser
1130  * \brief   writes on disc according to the requested format
1131  *          (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1132  *          using the Chained List
1133  * \warning does NOT add the missing elements in the header :
1134  *           it's up to the user doing it !
1135  *           (function CheckHeaderCoherence to be written)
1136  * \warning DON'T try, right now, to write a DICOM image
1137  *           from an ACR Header (meta elements will be missing!)
1138  * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1139  * @param   type type of the File to be written 
1140  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
1141  * @param   _fp already open file pointer
1142  */
1143
1144 void gdcmParser::WriteEntries(FILE *_fp,FileType type)
1145 {   
1146    // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1147    
1148    for (ListTag::iterator tag2=listEntries.begin();
1149                           tag2 != listEntries.end();
1150                           ++tag2)
1151    {
1152    WriteEntry(*tag2,_fp,type);
1153    if (itsTimeToWritePixels) 
1154       break;
1155    }
1156 }   
1157
1158 /**
1159  * \ingroup gdcmParser
1160  * \brief   writes on disc according to the requested format
1161  *          (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1162  *          using only the last synonym of each mutimap H Table post.
1163  * \warning Uses the H Table, instead of the Chained List
1164  *          in order to be compliant with the old way to proceed
1165  *         (added elements taken in to account)
1166  *         Only THERALYS, during a transitory phase is supposed
1167  *         to use this method !!!
1168  * \warning DON'T try, right now, to write a DICOM image
1169  *           from an ACR Header (meta elements will be missing!)
1170  * \sa WriteEntries
1171  * @param   _fp already open file pointer
1172  * @param   type type of the File to be written 
1173  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
1174  */
1175 void gdcmParser::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1176
1177    // restent a tester les echecs en ecriture (apres chaque fwrite)
1178
1179    for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1180         tag2 != tagHT.end();
1181         ++tag2){
1182       WriteEntry(tag2->second,_fp,type);
1183       if (itsTimeToWritePixels) 
1184          break;
1185    }
1186 }
1187
1188 /**
1189  * \ingroup gdcmParser
1190  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1191  *          processor order.
1192  * @return  The properly swaped 32 bits integer.
1193  */
1194 guint32 gdcmParser::SwapLong(guint32 a) {
1195    switch (sw) {
1196       case    0 :
1197          break;
1198       case 4321 :
1199          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
1200              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1201          break;
1202    
1203       case 3412 :
1204          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1205          break;
1206    
1207       case 2143 :
1208          a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1209          break;
1210       default :
1211          dbg.Error(" gdcmParser::SwapLong : unset swap code");
1212          a=0;
1213    }
1214    return(a);
1215 }
1216
1217 /**
1218  * \ingroup gdcmParser
1219  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
1220  *          processor order.
1221  * @return  The properly unswaped 32 bits integer.
1222  */
1223 guint32 gdcmParser::UnswapLong(guint32 a) {
1224    return (SwapLong(a));
1225 }
1226
1227 /**
1228  * \ingroup gdcmParser
1229  * \brief   Swaps the bytes so they agree with the processor order
1230  * @return  The properly swaped 16 bits integer.
1231  */
1232 guint16 gdcmParser::SwapShort(guint16 a) {
1233    if ( (sw==4321)  || (sw==2143) )
1234       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1235    return (a);
1236 }
1237
1238 /**
1239  * \ingroup gdcmParser
1240  * \brief   Unswaps the bytes so they agree with the processor order
1241  * @return  The properly unswaped 16 bits integer.
1242  */
1243 guint16 gdcmParser::UnswapShort(guint16 a) {
1244    return (SwapShort(a));
1245 }
1246
1247 //-----------------------------------------------------------------------------
1248 // Private
1249 /**
1250  * \ingroup gdcmParser
1251  * \brief   Parses the header of the file but WITHOUT loading element values.
1252  * @return  false if file is not ACR-NEMA / DICOM
1253  */
1254 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1255    
1256    rewind(fp);
1257    if (!CheckSwap())
1258       return false;
1259       
1260    gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;   
1261    while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1262      SkipHeaderEntry(newHeaderEntry);
1263      if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) { 
1264         AddHeaderEntry(newHeaderEntry); 
1265      }     
1266    }
1267    return true;
1268 }
1269
1270 /**
1271  * \ingroup gdcmParser
1272  * \brief   Loads the element values of all the Header Entries pointed in the
1273  *          public Chained List.
1274  */
1275 void gdcmParser::LoadHeaderEntries(void) {
1276    rewind(fp);
1277    for (ListTag::iterator i = GetListEntry().begin();
1278       i != GetListEntry().end();
1279       ++i)
1280    {
1281       LoadHeaderEntry(*i);
1282    }
1283             
1284    rewind(fp);
1285
1286    // Load 'non string' values   
1287    std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);   
1288    if( PhotometricInterpretation == "PALETTE COLOR " ) {
1289       LoadEntryVoidArea(0x0028,0x1200);  // gray LUT   
1290       LoadEntryVoidArea(0x0028,0x1201);  // R    LUT
1291       LoadEntryVoidArea(0x0028,0x1202);  // G    LUT
1292       LoadEntryVoidArea(0x0028,0x1203);  // B    LUT
1293       
1294       LoadEntryVoidArea(0x0028,0x1221);  // Segmented Red   Palette Color LUT Data
1295       LoadEntryVoidArea(0x0028,0x1222);  // Segmented Green Palette Color LUT Data
1296       LoadEntryVoidArea(0x0028,0x1223);  // Segmented Blue  Palette Color LUT Data
1297    } 
1298    //FIXME : how to use it?
1299    LoadEntryVoidArea(0x0028,0x3006);  //LUT Data (CTX dependent)     
1300    
1301    // --------------------------------------------------------------
1302    // Special Patch to allow gdcm to read ACR-LibIDO formated images
1303    //
1304    // if recognition code tells us we deal with a LibIDO image
1305    // we switch lineNumber and columnNumber
1306    //
1307    std::string RecCode;
1308    RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1309    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1310        RecCode == "CANRME_AILIBOD1_1." ) 
1311    {
1312          filetype = ACR_LIBIDO; 
1313          std::string rows    = GetEntryByNumber(0x0028, 0x0010);
1314          std::string columns = GetEntryByNumber(0x0028, 0x0011);
1315          SetEntryByNumber(columns, 0x0028, 0x0010);
1316          SetEntryByNumber(rows   , 0x0028, 0x0011);
1317    }
1318    // ----------------- End of Special Patch ----------------
1319 }
1320
1321 /**
1322  * \ingroup       gdcmParser
1323  * \brief         Loads the element content if its length doesn't exceed
1324  *                the value specified with gdcmParser::SetMaxSizeLoadEntry()
1325  * @param         Entry Header Entry (Dicom Element) to be dealt with
1326  */
1327 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry)  {
1328    size_t item_read;
1329    guint16 group  = Entry->GetGroup();
1330    std::string  vr= Entry->GetVR();
1331    guint32 length = Entry->GetLength();
1332    bool SkipLoad  = false;
1333
1334    fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1335    
1336    // the test was commented out to 'go inside' the SeQuences
1337    // we don't any longer skip them !
1338     
1339    // if( vr == "SQ" )  //  (DO NOT remove this comment)
1340    //    SkipLoad = true;
1341
1342    // A SeQuence "contains" a set of Elements.  
1343    //          (fffe e000) tells us an Element is beginning
1344    //          (fffe e00d) tells us an Element just ended
1345    //          (fffe e0dd) tells us the current SeQuence just ended
1346    if( group == 0xfffe )
1347       SkipLoad = true;
1348
1349    if ( SkipLoad ) {
1350       Entry->SetLength(0);
1351       Entry->SetValue("gdcm::Skipped");
1352       return;
1353    }
1354
1355    // When the length is zero things are easy:
1356    if ( length == 0 ) {
1357       Entry->SetValue("");
1358       return;
1359    }
1360
1361    // The elements whose length is bigger than the specified upper bound
1362    // are not loaded. Instead we leave a short notice of the offset of
1363    // the element content and it's length.
1364    if (length > MaxSizeLoadEntry) {
1365       std::ostringstream s;
1366       s << "gdcm::NotLoaded.";
1367       s << " Address:" << (long)Entry->GetOffset();
1368       s << " Length:"  << Entry->GetLength();
1369       s << " x(" << std::hex << Entry->GetLength() << ")";
1370       Entry->SetValue(s.str());
1371       return;
1372    }
1373    
1374    // When integer(s) are expected, read and convert the following 
1375    // n *(two or four bytes)
1376    // properly i.e. as integers as opposed to strings.
1377    // Elements with Value Multiplicity > 1
1378    // contain a set of integers (not a single one) 
1379     
1380    // Any compacter code suggested (?)
1381    if ( IsHeaderEntryAnInteger(Entry) ) {   
1382       guint32 NewInt;
1383       std::ostringstream s;
1384       int nbInt;
1385       if (vr == "US" || vr == "SS") {
1386          nbInt = length / 2;
1387          NewInt = ReadInt16();
1388          s << NewInt;
1389          if (nbInt > 1){
1390             for (int i=1; i < nbInt; i++) {
1391                s << '\\';
1392                NewInt = ReadInt16();
1393                s << NewInt;
1394             }
1395          }
1396       }
1397       else if (vr == "UL" || vr == "SL") {
1398          nbInt = length / 4;
1399          NewInt = ReadInt32();
1400          s << NewInt;
1401          if (nbInt > 1) {
1402             for (int i=1; i < nbInt; i++) {
1403                s << '\\';
1404                NewInt = ReadInt32();
1405                s << NewInt;
1406             }
1407          }
1408       }
1409 #ifdef GDCM_NO_ANSI_STRING_STREAM
1410       s << std::ends; // to avoid oddities on Solaris
1411 #endif //GDCM_NO_ANSI_STRING_STREAM
1412
1413       Entry->SetValue(s.str());
1414       return;
1415    }
1416    
1417    // We need an additional byte for storing \0 that is not on disk
1418    std::string NewValue(length,0);
1419    item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1420    if ( item_read != 1 ) {
1421       dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1422       Entry->SetValue("gdcm::UnRead");
1423       return;
1424    }
1425
1426    if( (vr == "UI") ) // Because of correspondance with the VR dic
1427       Entry->SetValue(NewValue.c_str());
1428    else
1429       Entry->SetValue(NewValue);
1430 }
1431
1432 /**
1433  * \ingroup gdcmParser
1434  * \brief   add a new Dicom Element pointer to 
1435  *          the H Table and at the end of the chained List
1436  * \warning push_bash in listEntries ONLY during ParseHeader
1437  * \todo    something to allow further Elements addition,
1438  *          (at their right place in the chained list)
1439  *          when position to be taken care of     
1440  * @param   newHeaderEntry
1441  */
1442 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1443    tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1444    listEntries.push_back(newHeaderEntry); 
1445    wasUpdated = 1;
1446 }
1447
1448 /**
1449  * \ingroup gdcmParser
1450  * \brief  Find the value Length of the passed Header Entry
1451  * @param  Entry Header Entry whose length of the value shall be loaded. 
1452  */
1453  void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1454    guint16 element = Entry->GetElement();
1455    guint16 group   = Entry->GetGroup();
1456    std::string  vr = Entry->GetVR();
1457    guint16 length16;
1458    
1459    if( (element == NumPixel) && (group == GrPixel) ) 
1460    {
1461       dbg.SetDebug(GDCM_DEBUG);
1462       dbg.Verbose(2, "gdcmParser::FindLength: ",
1463                      "we reached (GrPixel,NumPixel)");
1464    }   
1465    
1466    if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) ) 
1467    {
1468       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) 
1469       {
1470          // The following reserved two bytes (see PS 3.5-2001, section
1471          // 7.1.2 Data element structure with explicit vr p27) must be
1472          // skipped before proceeding on reading the length on 4 bytes.
1473          fseek(fp, 2L, SEEK_CUR);
1474          guint32 length32 = ReadInt32();
1475
1476          if ( (vr == "OB") && (length32 == 0xffffffff) ) 
1477          {
1478             Entry->SetLength(FindHeaderEntryLengthOB());
1479             return;
1480          }
1481          FixHeaderEntryFoundLength(Entry, length32); 
1482          return;
1483       }
1484
1485       // Length is encoded on 2 bytes.
1486       length16 = ReadInt16();
1487       
1488       // We can tell the current file is encoded in big endian (like
1489       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1490       // and it's value is the one of the encoding of a big endian file.
1491       // In order to deal with such big endian encoded files, we have
1492       // (at least) two strategies:
1493       // * when we load the "Transfer Syntax" tag with value of big endian
1494       //   encoding, we raise the proper flags. Then we wait for the end
1495       //   of the META group (0x0002) among which is "Transfer Syntax",
1496       //   before switching the swap code to big endian. We have to postpone
1497       //   the switching of the swap code since the META group is fully encoded
1498       //   in little endian, and big endian coding only starts at the next
1499       //   group. The corresponding code can be hard to analyse and adds
1500       //   many additional unnecessary tests for regular tags.
1501       // * the second strategy consists in waiting for trouble, that shall
1502       //   appear when we find the first group with big endian encoding. This
1503       //   is easy to detect since the length of a "Group Length" tag (the
1504       //   ones with zero as element number) has to be of 4 (0x0004). When we
1505       //   encounter 1024 (0x0400) chances are the encoding changed and we
1506       //   found a group with big endian encoding.
1507       // We shall use this second strategy. In order to make sure that we
1508       // can interpret the presence of an apparently big endian encoded
1509       // length of a "Group Length" without committing a big mistake, we
1510       // add an additional check: we look in the already parsed elements
1511       // for the presence of a "Transfer Syntax" whose value has to be "big
1512       // endian encoding". When this is the case, chances are we have got our
1513       // hands on a big endian encoded file: we switch the swap code to
1514       // big endian and proceed...
1515       if ( (element  == 0x0000) && (length16 == 0x0400) ) 
1516       {
1517          if ( ! IsExplicitVRBigEndianTransferSyntax() ) 
1518          {
1519             dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1520             errno = 1;
1521             return;
1522          }
1523          length16 = 4;
1524          SwitchSwapToBigEndian();
1525          // Restore the unproperly loaded values i.e. the group, the element
1526          // and the dictionary entry depending on them.
1527          guint16 CorrectGroup   = SwapShort(Entry->GetGroup());
1528          guint16 CorrectElem    = SwapShort(Entry->GetElement());
1529          gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1530                                                        CorrectElem);
1531          if (!NewTag) 
1532          {
1533             // This correct tag is not in the dictionary. Create a new one.
1534             NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1535          }
1536          // FIXME this can create a memory leaks on the old entry that be
1537          // left unreferenced.
1538          Entry->SetDictEntry(NewTag);
1539       }
1540        
1541       // Heuristic: well some files are really ill-formed.
1542       if ( length16 == 0xffff) 
1543       {
1544          length16 = 0;
1545          //dbg.Verbose(0, "gdcmParser::FindLength",
1546          //            "Erroneous element length fixed.");
1547          // Actually, length= 0xffff means that we deal with
1548          // Unknown Sequence Length 
1549       }
1550       FixHeaderEntryFoundLength(Entry, (guint32)length16);
1551       return;
1552    }
1553    else
1554    {
1555       // Either implicit VR or a non DICOM conformal (see note below) explicit
1556       // VR that ommited the VR of (at least) this element. Farts happen.
1557       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1558       // on Data elements "Implicit and Explicit VR Data Elements shall
1559       // not coexist in a Data Set and Data Sets nested within it".]
1560       // Length is on 4 bytes.
1561       
1562       FixHeaderEntryFoundLength(Entry, ReadInt32());
1563       return;
1564    }
1565 }
1566
1567 /**
1568  * \ingroup   gdcmParser
1569  * \brief     Find the Value Representation of the current Dicom Element.
1570  * @param     Entry
1571  */
1572 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry) 
1573 {
1574    if (filetype != ExplicitVR)
1575       return;
1576
1577    char VR[3];
1578
1579    long PositionOnEntry = ftell(fp);
1580    // Warning: we believe this is explicit VR (Value Representation) because
1581    // we used a heuristic that found "UL" in the first tag. Alas this
1582    // doesn't guarantee that all the tags will be in explicit VR. In some
1583    // cases (see e-film filtered files) one finds implicit VR tags mixed
1584    // within an explicit VR file. Hence we make sure the present tag
1585    // is in explicit VR and try to fix things if it happens not to be
1586    // the case.
1587    
1588    int lgrLue=fread (&VR, (size_t)2,(size_t)1, fp); // lgrLue not used
1589    VR[2]=0;
1590    if(!CheckHeaderEntryVR(Entry,VR))
1591    {
1592       fseek(fp, PositionOnEntry, SEEK_SET);
1593       // When this element is known in the dictionary we shall use, e.g. for
1594       // the semantics (see the usage of IsAnInteger), the VR proposed by the
1595       // dictionary entry. Still we have to flag the element as implicit since
1596       // we know now our assumption on expliciteness is not furfilled.
1597       // avoid  .
1598       if ( Entry->IsVRUnknown() )
1599          Entry->SetVR("Implicit");
1600       Entry->SetImplicitVR();
1601    }
1602 }
1603
1604 /**
1605  * \ingroup   gdcmParser
1606  * \brief     Check the correspondance between the VR of the header entry
1607  *            and the taken VR. If they are different, the header entry is 
1608  *            updated with the new VR.
1609  * @param     Entry Header Entry to check
1610  * @param     vr    Dicom Value Representation
1611  * @return    false if the VR is incorrect of if the VR isn't referenced
1612  *            otherwise, it returns true
1613 */
1614 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1615 {
1616    char msg[100]; // for sprintf
1617    bool RealExplicit = true;
1618
1619    // Assume we are reading a falsely explicit VR file i.e. we reached
1620    // a tag where we expect reading a VR but are in fact we read the
1621    // first to bytes of the length. Then we will interogate (through find)
1622    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1623    // both GCC and VC++ implementations of the STL map. Hence when the
1624    // expected VR read happens to be non-ascii characters we consider
1625    // we hit falsely explicit VR tag.
1626
1627    if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1628       RealExplicit = false;
1629
1630    // CLEANME searching the dicom_vr at each occurence is expensive.
1631    // PostPone this test in an optional integrity check at the end
1632    // of parsing or only in debug mode.
1633    if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1634       RealExplicit= false;
1635
1636    if ( !RealExplicit ) 
1637    {
1638       // We thought this was explicit VR, but we end up with an
1639       // implicit VR tag. Let's backtrack.   
1640       sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", 
1641                    Entry->GetGroup(),Entry->GetElement());
1642       dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1643       if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1644          gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1645                                    Entry->GetGroup(),Entry->GetElement(),
1646                                    "UL","FIXME","Group Length");
1647          Entry->SetDictEntry(NewEntry);     
1648       }
1649       return(false);
1650    }
1651
1652    if ( Entry->IsVRUnknown() ) 
1653    {
1654       // When not a dictionary entry, we can safely overwrite the VR.
1655       if (Entry->GetElement() == 0x0000) { // Group length is UL !
1656          Entry->SetVR("UL");
1657       } else {
1658          Entry->SetVR(vr);
1659       }
1660    }
1661    else if ( Entry->GetVR() != vr ) 
1662    {
1663       // The VR present in the file and the dictionary disagree. We assume
1664       // the file writer knew best and use the VR of the file. Since it would
1665       // be unwise to overwrite the VR of a dictionary (since it would
1666       // compromise it's next user), we need to clone the actual DictEntry
1667       // and change the VR for the read one.
1668       gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1669                                  Entry->GetGroup(),Entry->GetElement(),
1670                                  vr,"FIXME",Entry->GetName());
1671       Entry->SetDictEntry(NewEntry);
1672    }
1673    return(true); 
1674 }
1675
1676 /**
1677  * \ingroup gdcmParser
1678  * \brief   Get the transformed value of the header entry. The VR value 
1679  *          is used to define the transformation to operate on the value
1680  * \warning NOT end user intended method !
1681  * @param   Entry 
1682  * @return  Transformed entry value
1683  */
1684 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1685 {
1686    if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1687    {
1688       std::string val=Entry->GetValue();
1689       std::string vr=Entry->GetVR();
1690       guint32 length = Entry->GetLength();
1691       std::ostringstream s;
1692       int nbInt;
1693
1694       if (vr == "US" || vr == "SS")
1695       {
1696          guint16 NewInt16;
1697
1698          nbInt = length / 2;
1699          for (int i=0; i < nbInt; i++) 
1700          {
1701             if(i!=0)
1702                s << '\\';
1703             NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1704             NewInt16 = SwapShort(NewInt16);
1705             s << NewInt16;
1706          }
1707       }
1708
1709       else if (vr == "UL" || vr == "SL")
1710       {
1711          guint32 NewInt32;
1712
1713          nbInt = length / 4;
1714          for (int i=0; i < nbInt; i++) 
1715          {
1716             if(i!=0)
1717                s << '\\';
1718             NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1719                      ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1720             NewInt32=SwapLong(NewInt32);
1721             s << NewInt32;
1722          }
1723       }
1724 #ifdef GDCM_NO_ANSI_STRING_STREAM
1725       s << std::ends; // to avoid oddities on Solaris
1726 #endif //GDCM_NO_ANSI_STRING_STREAM
1727       return(s.str());
1728    }
1729
1730    return(Entry->GetValue());
1731 }
1732
1733 /**
1734  * \ingroup gdcmParser
1735  * \brief   Get the reverse transformed value of the header entry. The VR 
1736  *          value is used to define the reverse transformation to operate on
1737  *          the value
1738  * \warning NOT end user intended method !
1739  * @param   Entry 
1740  * @return  Reverse transformed entry value
1741  */
1742 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1743 {
1744    if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1745    {
1746       std::string vr=Entry->GetVR();
1747       std::ostringstream s;
1748       std::vector<std::string> tokens;
1749
1750       if (vr == "US" || vr == "SS") 
1751       {
1752          guint16 NewInt16;
1753
1754          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1755          Tokenize (Entry->GetValue(), tokens, "\\");
1756          for (unsigned int i=0; i<tokens.size();i++) 
1757          {
1758             NewInt16 = atoi(tokens[i].c_str());
1759             s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1760          }
1761          tokens.clear();
1762       }
1763       if (vr == "UL" || vr == "SL") 
1764       {
1765          guint32 NewInt32;
1766
1767          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1768          Tokenize (Entry->GetValue(), tokens, "\\");
1769          for (unsigned int i=0; i<tokens.size();i++) 
1770          {
1771             NewInt32 = atoi(tokens[i].c_str());
1772             s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1773                <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1774          }
1775          tokens.clear();
1776       }
1777
1778 #ifdef GDCM_NO_ANSI_STRING_STREAM
1779       s << std::ends; // to avoid oddities on Solaris
1780 #endif //GDCM_NO_ANSI_STRING_STREAM
1781       return(s.str());
1782    }
1783
1784    return(Entry->GetValue());
1785 }
1786
1787 /**
1788  * \ingroup gdcmParser
1789  * \brief   Skip a given Header Entry 
1790  * \warning NOT end user intended method !
1791  * @param   entry 
1792  */
1793 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry) 
1794 {
1795     SkipBytes(entry->GetLength());
1796 }
1797
1798 /**
1799  * \ingroup gdcmParser
1800  * \brief   When the length of an element value is obviously wrong (because
1801  *          the parser went Jabberwocky) one can hope improving things by
1802  *          applying this heuristic.
1803  */
1804 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength) 
1805 {
1806    Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1807      
1808    if ( FoundLength == 0xffffffff) {
1809       FoundLength = 0;
1810    }
1811    
1812    guint16 gr =Entry->GetGroup();
1813    guint16 el =Entry->GetElement(); 
1814      
1815    if (FoundLength%2) {
1816       std::ostringstream s;
1817       s << "Warning : Tag with uneven length " << FoundLength 
1818          <<  " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1819       dbg.Verbose(0,s.str().c_str());
1820    }
1821       
1822    // Sorry for the patch!  
1823    // XMedCom did the trick to read some nasty GE images ...
1824    if (FoundLength == 13) {
1825       // The following 'if' will be removed when there is no more
1826       // images on Creatis HDs with a 13 length for Manufacturer...
1827       if ( (Entry->GetGroup() != 0x0008) ||  
1828            ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1829       // end of remove area
1830          FoundLength =10;
1831          Entry->SetReadLength(10); // a bug is to be fixed
1832       }
1833    }
1834
1835    // to fix some garbage 'Leonardo' Siemens images
1836    // May be commented out to avoid overhead
1837    else if ( (Entry->GetGroup() == 0x0009) &&
1838        ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1839       FoundLength =4;
1840       Entry->SetReadLength(4); // a bug is to be fixed 
1841    } 
1842    // end of fix
1843  
1844    // to try to 'go inside' SeQuences (with length), and not to skip them        
1845    else if ( Entry->GetVR() == "SQ") 
1846    { 
1847       if (enableSequences)    // only if the user does want to !
1848          FoundLength =0;      // ReadLength is unchanged 
1849    } 
1850     
1851    // a SeQuence Element is beginning                                          
1852    // fffe|e000 is just a marker, its length *should be* zero                                               
1853    else if(Entry->GetGroup() == 0xfffe)
1854    { 
1855                                          // *normally, fffe|0000 doesn't exist ! 
1856      if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1857                                          // causes extra troubles :-(                                                        
1858          FoundLength =0;
1859    }         
1860    Entry->SetUsableLength(FoundLength);
1861 }
1862
1863 /**
1864  * \ingroup gdcmParser
1865  * \brief   Apply some heuristics to predict whether the considered 
1866  *          element value contains/represents an integer or not.
1867  * @param   Entry The element value on which to apply the predicate.
1868  * @return  The result of the heuristical predicate.
1869  */
1870 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1871    guint16 element = Entry->GetElement();
1872    guint16 group   = Entry->GetGroup();
1873    std::string  vr = Entry->GetVR();
1874    guint32 length  = Entry->GetLength();
1875    // When we have some semantics on the element we just read, and if we
1876    // a priori know we are dealing with an integer, then we shall be
1877    // able to swap it's element value properly.
1878    if ( element == 0 )  // This is the group length of the group
1879    {  
1880       if (length == 4)
1881          return true;
1882       else 
1883       {
1884          std::ostringstream s;
1885          int filePosition = ftell(fp);
1886          s << "Erroneous Group Length element length  on : (" \
1887            << std::hex << group << " , " << element 
1888            << ") -before- position x(" << filePosition << ")"
1889            << "lgt : " << length;
1890          // These 2 lines commented out : a *very dirty* patch
1891          // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1892          // have a glance at offset  x(8336) ...
1893          // For *regular* headers, the test is useless..
1894          // lets's print a warning message and go on, 
1895          // instead of giving up with an error message
1896
1897          //std::cout << s.str().c_str() << std::endl;
1898          // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1899          //           s.str().c_str());     
1900       }
1901    }
1902    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1903       return true;
1904    
1905    return false;
1906 }
1907 /**
1908  * \ingroup gdcmParser
1909  * \brief  Find the Length till the next sequence delimiter
1910  * \warning NOT end user intended method !
1911  * @return 
1912  */
1913
1914  guint32 gdcmParser::FindHeaderEntryLengthOB(void)  {
1915    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1916    guint16 g;
1917    guint16 n; 
1918    long PositionOnEntry = ftell(fp);
1919    bool FoundSequenceDelimiter = false;
1920    guint32 TotalLength = 0;
1921    guint32 ItemLength;
1922
1923    while ( ! FoundSequenceDelimiter) 
1924    {
1925       g = ReadInt16();
1926       n = ReadInt16();   
1927       if (errno == 1)
1928          return 0;
1929       TotalLength += 4;  // We even have to decount the group and element 
1930      
1931       if ( g != 0xfffe && g!=0xb00c ) //for bogus header  
1932       {
1933          char msg[100]; // for sprintf. Sorry
1934          sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1935          dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg); 
1936          errno = 1;
1937          return 0;
1938       }
1939       if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header 
1940          FoundSequenceDelimiter = true;
1941       else if ( n != 0xe000 )
1942       {
1943          char msg[100];  // for sprintf. Sorry
1944          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1945                       n, g,n);
1946          dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1947          errno = 1;
1948          return 0;
1949       }
1950       ItemLength = ReadInt32();
1951       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
1952                                       // the ItemLength with ReadInt32                                     
1953       SkipBytes(ItemLength);
1954    }
1955    fseek(fp, PositionOnEntry, SEEK_SET);
1956    return TotalLength;
1957 }
1958
1959 /**
1960  * \ingroup gdcmParser
1961  * \brief Reads a supposed to be 16 Bits integer
1962  *       (swaps it depending on processor endianity) 
1963  * @return read value
1964  */
1965 guint16 gdcmParser::ReadInt16(void) {
1966    guint16 g;
1967    size_t item_read;
1968    item_read = fread (&g, (size_t)2,(size_t)1, fp);
1969    if ( item_read != 1 ) {
1970       if(ferror(fp)) 
1971          dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1972       errno = 1;
1973       return 0;
1974    }
1975    errno = 0;
1976    g = SwapShort(g);   
1977    return g;
1978 }
1979
1980 /**
1981  * \ingroup gdcmParser
1982  * \brief  Reads a supposed to be 32 Bits integer
1983  *         (swaps it depending on processor endianity)  
1984  * @return read value
1985  */
1986 guint32 gdcmParser::ReadInt32(void) {
1987    guint32 g;
1988    size_t item_read;
1989    item_read = fread (&g, (size_t)4,(size_t)1, fp);
1990    if ( item_read != 1 ) { 
1991      if(ferror(fp)) 
1992          dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");   
1993       errno = 1;
1994       return 0;
1995    }
1996    errno = 0;   
1997    g = SwapLong(g);
1998    return g;
1999 }
2000
2001 /**
2002  * \ingroup gdcmParser
2003  * \brief skips bytes inside the source file 
2004  * \warning NOT end user intended method !
2005  * @return 
2006  */
2007 void gdcmParser::SkipBytes(guint32 NBytes) {
2008    //FIXME don't dump the returned value
2009    (void)fseek(fp, (long)NBytes, SEEK_CUR);
2010 }
2011
2012 /**
2013  * \ingroup gdcmParser
2014  * \brief Loads all the needed Dictionaries
2015  * \warning NOT end user intended method !   
2016  */
2017 void gdcmParser::Initialise(void) 
2018 {
2019    RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2020    RefShaDict = (gdcmDict*)0;
2021 }
2022
2023 /**
2024  * \ingroup gdcmParser
2025  * \brief   Discover what the swap code is (among little endian, big endian,
2026  *          bad little endian, bad big endian).
2027  *          sw is set
2028  * @return false when we are absolutely sure 
2029  *               it's neither ACR-NEMA nor DICOM
2030  *         true  when we hope ours assuptions are OK
2031  */
2032 bool gdcmParser::CheckSwap() {
2033
2034    // The only guaranted way of finding the swap code is to find a
2035    // group tag since we know it's length has to be of four bytes i.e.
2036    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2037    // occurs when we can't find such group...
2038    
2039    guint32  x=4;  // x : for ntohs
2040    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2041    guint32  s32;
2042    guint16  s16;
2043        
2044    int lgrLue;
2045    char *entCur;
2046    char deb[HEADER_LENGTH_TO_READ];
2047     
2048    // First, compare HostByteOrder and NetworkByteOrder in order to
2049    // determine if we shall need to swap bytes (i.e. the Endian type).
2050    if (x==ntohs(x))
2051       net2host = true;
2052    else
2053       net2host = false; 
2054          
2055    // The easiest case is the one of a DICOM header, since it possesses a
2056    // file preamble where it suffice to look for the string "DICM".
2057    lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2058    
2059    entCur = deb + 128;
2060    if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2061       dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2062       
2063       // Next, determine the value representation (VR). Let's skip to the
2064       // first element (0002, 0000) and check there if we find "UL" 
2065       // - or "OB" if the 1st one is (0002,0001) -,
2066       // in which case we (almost) know it is explicit VR.
2067       // WARNING: if it happens to be implicit VR then what we will read
2068       // is the length of the group. If this ascii representation of this
2069       // length happens to be "UL" then we shall believe it is explicit VR.
2070       // FIXME: in order to fix the above warning, we could read the next
2071       // element value (or a couple of elements values) in order to make
2072       // sure we are not commiting a big mistake.
2073       // We need to skip :
2074       // * the 128 bytes of File Preamble (often padded with zeroes),
2075       // * the 4 bytes of "DICM" string,
2076       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2077       // i.e. a total of  136 bytes.
2078       entCur = deb + 136;
2079      
2080       // FIXME : FIXME:
2081       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2082       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2083       // *Implicit* VR.  -and it is !- 
2084       
2085       if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2086           (memcmp(entCur, "OB", (size_t)2) == 0) ||
2087           (memcmp(entCur, "UI", (size_t)2) == 0) ||
2088           (memcmp(entCur, "CS", (size_t)2) == 0) )  // CS, to remove later
2089                                                     // when Write DCM *adds*
2090       // FIXME
2091       // Use gdcmParser::dicom_vr to test all the possibilities
2092       // instead of just checking for UL, OB and UI !? group 0000 
2093       {
2094          filetype = ExplicitVR;
2095          dbg.Verbose(1, "gdcmParser::CheckSwap:",
2096                      "explicit Value Representation");
2097       } 
2098       else 
2099       {
2100          filetype = ImplicitVR;
2101          dbg.Verbose(1, "gdcmParser::CheckSwap:",
2102                      "not an explicit Value Representation");
2103       }
2104       
2105       if (net2host) 
2106       {
2107          sw = 4321;
2108          dbg.Verbose(1, "gdcmParser::CheckSwap:",
2109                         "HostByteOrder != NetworkByteOrder");
2110       } 
2111       else 
2112       {
2113          sw = 0;
2114          dbg.Verbose(1, "gdcmParser::CheckSwap:",
2115                         "HostByteOrder = NetworkByteOrder");
2116       }
2117       
2118       // Position the file position indicator at first tag (i.e.
2119       // after the file preamble and the "DICM" string).
2120       rewind(fp);
2121       fseek (fp, 132L, SEEK_SET);
2122       return true;
2123    } // End of DicomV3
2124
2125    // Alas, this is not a DicomV3 file and whatever happens there is no file
2126    // preamble. We can reset the file position indicator to where the data
2127    // is (i.e. the beginning of the file).
2128    dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2129    rewind(fp);
2130
2131    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2132    // By clean we mean that the length of the first tag is written down.
2133    // If this is the case and since the length of the first group HAS to be
2134    // four (bytes), then determining the proper swap code is straightforward.
2135
2136    entCur = deb + 4;
2137    // We assume the array of char we are considering contains the binary
2138    // representation of a 32 bits integer. Hence the following dirty
2139    // trick :
2140    s32 = *((guint32 *)(entCur));
2141       
2142    switch (s32) {
2143       case 0x00040000 :
2144          sw = 3412;
2145          filetype = ACR;
2146          return true;
2147       case 0x04000000 :
2148          sw = 4321;
2149          filetype = ACR;
2150          return true;
2151       case 0x00000400 :
2152          sw = 2143;
2153          filetype = ACR;
2154          return true;
2155       case 0x00000004 :
2156          sw = 0;
2157          filetype = ACR;
2158          return true;
2159       default :
2160
2161       // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2162       // It is time for despaired wild guesses. 
2163       // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2164       //  i.e. the 'group length' element is not present :     
2165       
2166       //  check the supposed to be 'group number'
2167       //  0x0002 or 0x0004 or 0x0008
2168       //  to determine ' sw' value .
2169       //  Only 0 or 4321 will be possible 
2170       //  (no oportunity to check for the formerly well known
2171       //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2172       //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-) 
2173       //  the file IS NOT ACR-NEMA nor DICOM V3
2174       //  Find a trick to tell it the caller...
2175       
2176       s16 = *((guint16 *)(deb));
2177       
2178       switch (s16) {
2179       case 0x0002 :
2180       case 0x0004 :
2181       case 0x0008 :      
2182          sw = 0;
2183          filetype = ACR;
2184          return true;
2185       case 0x0200 :
2186       case 0x0400 :
2187       case 0x0800 : 
2188          sw = 4321;
2189          filetype = ACR;
2190          return true;
2191       default :
2192          dbg.Verbose(0, "gdcmParser::CheckSwap:",
2193                      "ACR/NEMA unfound swap info (Really hopeless !)"); 
2194          filetype = Unknown;     
2195          return false;
2196       }
2197       
2198       // Then the only info we have is the net2host one.
2199       //if (! net2host )
2200          //   sw = 0;
2201          //else
2202          //  sw = 4321;
2203          //return;
2204    }
2205 }
2206
2207 /**
2208  * \ingroup gdcmParser
2209  * \brief Restore the unproperly loaded values i.e. the group, the element
2210  *        and the dictionary entry depending on them. 
2211  */
2212 void gdcmParser::SwitchSwapToBigEndian(void) 
2213 {
2214    dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2215                   "Switching to BigEndian mode.");
2216    if ( sw == 0    ) 
2217    {
2218       sw = 4321;
2219       return;
2220    }
2221    if ( sw == 4321 ) 
2222    {
2223       sw = 0;
2224       return;
2225    }
2226    if ( sw == 3412 ) 
2227    {
2228       sw = 2143;
2229       return;
2230    }
2231    if ( sw == 2143 )
2232       sw = 3412;
2233 }
2234
2235 /**
2236  * \ingroup gdcmParser
2237  * \brief  during parsing, Header Elements too long are not loaded in memory 
2238  * @param NewSize
2239  */
2240 void gdcmParser::SetMaxSizeLoadEntry(long NewSize) 
2241 {
2242    if (NewSize < 0)
2243       return;
2244    if ((guint32)NewSize >= (guint32)0xffffffff) 
2245    {
2246       MaxSizeLoadEntry = 0xffffffff;
2247       return;
2248    }
2249    MaxSizeLoadEntry = NewSize;
2250 }
2251
2252
2253 /**
2254  * \ingroup gdcmParser
2255  * \brief Header Elements too long will not be printed
2256  * \warning 
2257  * \todo : not yet usable 
2258  *          (see MAX_SIZE_PRINT_ELEMENT_VALUE 
2259  *           in gdcmHeaderEntry gdcmLoadEntry)
2260  *             
2261  * @param NewSize
2262  */
2263 void gdcmParser::SetMaxSizePrintEntry(long NewSize) 
2264 {
2265    if (NewSize < 0)
2266       return;
2267    if ((guint32)NewSize >= (guint32)0xffffffff) 
2268    {
2269       MaxSizePrintEntry = 0xffffffff;
2270       return;
2271    }
2272    MaxSizePrintEntry = NewSize;
2273 }
2274
2275 /**
2276  * \ingroup gdcmParser
2277  * \brief   Searches both the public and the shadow dictionary (when they
2278  *          exist) for the presence of the DictEntry with given name.
2279  *          The public dictionary has precedence on the shadow one.
2280  * @param   Name name of the searched DictEntry
2281  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2282  */
2283 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name) 
2284 {
2285    gdcmDictEntry *found = (gdcmDictEntry *)0;
2286    if (!RefPubDict && !RefShaDict) 
2287    {
2288       dbg.Verbose(0, "gdcmParser::GetDictEntry",
2289                      "we SHOULD have a default dictionary");
2290    }
2291    if (RefPubDict) 
2292    {
2293       found = RefPubDict->GetDictEntryByName(Name);
2294       if (found)
2295          return found;
2296    }
2297    if (RefShaDict) 
2298    {
2299       found = RefShaDict->GetDictEntryByName(Name);
2300       if (found)
2301          return found;
2302    }
2303    return found;
2304 }
2305
2306 /**
2307  * \ingroup gdcmParser
2308  * \brief   Searches both the public and the shadow dictionary (when they
2309  *          exist) for the presence of the DictEntry with given
2310  *          group and element. The public dictionary has precedence on the
2311  *          shadow one.
2312  * @param   group   group of the searched DictEntry
2313  * @param   element element of the searched DictEntry
2314  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2315  */
2316 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element) 
2317 {
2318    gdcmDictEntry *found = (gdcmDictEntry *)0;
2319    if (!RefPubDict && !RefShaDict) 
2320    {
2321       dbg.Verbose(0, "gdcmParser::GetDictEntry",
2322                      "we SHOULD have a default dictionary");
2323    }
2324    if (RefPubDict) 
2325    {
2326       found = RefPubDict->GetDictEntryByNumber(group, element);
2327       if (found)
2328          return found;
2329    }
2330    if (RefShaDict) 
2331    {
2332       found = RefShaDict->GetDictEntryByNumber(group, element);
2333       if (found)
2334          return found;
2335    }
2336    return found;
2337 }
2338
2339 /**
2340  * \ingroup gdcmParser
2341  * \brief   Read the next tag but WITHOUT loading it's value
2342  * @return  On succes the newly created HeaderEntry, NULL on failure.      
2343  */
2344 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2345    guint16 g,n;
2346    gdcmHeaderEntry *NewEntry;
2347    g = ReadInt16();
2348    n = ReadInt16();
2349       
2350    if (errno == 1)
2351       // We reached the EOF (or an error occured) therefore 
2352       // header parsing has to be considered as finished.
2353       return (gdcmHeaderEntry *)0;
2354
2355 // Pb : how to propagate the element length (used in SkipHeaderEntry)
2356 //       direct call to SkipBytes ?
2357    
2358 //   if (ignoreShadow == 1 && g%2 ==1)
2359       // if user wants to skip shadow groups
2360       // and current element *is* a shadow element
2361       // we don't create anything
2362 //      return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2363   
2364    NewEntry = NewHeaderEntryByNumber(g, n);
2365    FindHeaderEntryVR(NewEntry);
2366    FindHeaderEntryLength(NewEntry);
2367
2368    if (errno == 1) {
2369       // Call it quits
2370       return NULL;
2371    }
2372    NewEntry->SetOffset(ftell(fp));  
2373    return NewEntry;
2374 }
2375
2376 /**
2377  * \ingroup gdcmParser
2378  * \brief   Build a new Element Value from all the low level arguments. 
2379  *          Check for existence of dictionary entry, and build
2380  *          a default one when absent.
2381  * @param   Name    Name of the underlying DictEntry
2382  */
2383 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name) 
2384 {
2385    gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2386    if (!NewTag)
2387       NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2388
2389    gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2390    if (!NewEntry) 
2391    {
2392       dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2393                   "failed to allocate gdcmHeaderEntry");
2394       return (gdcmHeaderEntry *)0;
2395    }
2396    return NewEntry;
2397 }  
2398
2399 /**
2400  * \ingroup gdcmParser
2401  * \brief   Request a new virtual dict entry to the dict set
2402  * @param   group  group   of the underlying DictEntry
2403  * @param   element  element of the underlying DictEntry
2404  * @param   vr     VR of the underlying DictEntry
2405  * @param   fourth owner group
2406  * @param   name   english name
2407  */
2408 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2409                                                std::string vr,
2410                                                std::string fourth,
2411                                                std::string name)
2412 {
2413    return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2414 }
2415
2416 /**
2417  * \ingroup gdcmParser
2418  * \brief   Build a new Element Value from all the low level arguments. 
2419  *          Check for existence of dictionary entry, and build
2420  *          a default one when absent.
2421  * @param   Group group   of the underlying DictEntry
2422  * @param   Elem  element of the underlying DictEntry
2423  */
2424 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem) 
2425 {
2426    // Find out if the tag we encountered is in the dictionaries:
2427    gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2428    if (!DictEntry)
2429       DictEntry = NewVirtualDictEntry(Group, Elem);
2430
2431    gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2432    if (!NewEntry) 
2433    {
2434       dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2435                   "failed to allocate gdcmHeaderEntry");
2436       return NULL;
2437    }
2438    return NewEntry;
2439 }
2440
2441 // Never used; commented out, waiting for removal.
2442 /**
2443  * \ingroup gdcmParser
2444  * \brief   Small utility function that creates a new manually crafted
2445  *          (as opposed as read from the file) gdcmHeaderEntry with user
2446  *          specified name and adds it to the public tag hash table.
2447  * \note    A fake TagKey is generated so the PubDict can keep it's coherence.
2448  * @param   NewTagName The name to be given to this new tag.
2449  * @param   VR The Value Representation to be given to this new tag.
2450  * @return  The newly hand crafted Element Value.
2451  */
2452 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName, 
2453 //                                                           std::string VR) 
2454 //{
2455 //   gdcmHeaderEntry *NewEntry = NULL;
2456 //   guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
2457 //   guint32 FreeElem = 0;
2458 //   gdcmDictEntry *DictEntry = NULL;
2459 //
2460 //   FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2461 //   if (FreeElem == UINT32_MAX) 
2462 //   {
2463 //      dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2464 //                     "Group 0xffff in Public Dict is full");
2465 //      return NULL;
2466 //   }
2467 //
2468 //   DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2469 //                                VR, "GDCM", NewTagName);
2470 //   NewEntry = new gdcmHeaderEntry(DictEntry);
2471 //   AddHeaderEntry(NewEntry);
2472 //   return NewEntry;
2473 //}
2474
2475 /**
2476  * \ingroup gdcmParser
2477  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2478  *          in the TagHt dictionary.
2479  * @param   group The generated tag must belong to this group.  
2480  * @return  The element of tag with given group which is fee.
2481  */
2482 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group) 
2483 {
2484    for (guint32 elem = 0; elem < UINT32_MAX; elem++) 
2485    {
2486       TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2487       if (tagHT.count(key) == 0)
2488          return elem;
2489    }
2490    return UINT32_MAX;
2491 }
2492
2493 //-----------------------------------------------------------------------------