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