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