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