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