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