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