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