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