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