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