]> Creatis software - gdcm.git/blob - src/gdcmParser.cxx
6730a95a9b0812c6d6b217b8667409c1fb235f47
[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    if(filetype==Unknown)
223       return(false);
224
225    if(listEntries.size()<=0)
226       return(false);
227
228    return(true);
229 }
230
231 /**
232  * \ingroup gdcmParser
233  * \brief   Determines if the Transfer Syntax was already encountered
234  *          and if it corresponds to a ImplicitVRLittleEndian one.
235  *
236  * @return  True when ImplicitVRLittleEndian found. False in all other cases.
237  */
238 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
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 == UI1_2_840_10008_1_2 )
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 ExplicitVRLittleEndian one.
254  *
255  * @return  True when ExplicitVRLittleEndian found. False in all other cases.
256  */
257 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
258    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
259    if ( !Element )
260       return false;
261    LoadHeaderEntrySafe(Element);
262
263    std::string Transfer = Element->GetValue();
264    if ( Transfer == UI1_2_840_10008_1_2_1 )
265       return true;
266    return false;
267 }
268
269 /**
270  * \ingroup gdcmParser
271  * \brief   Determines if the Transfer Syntax was already encountered
272  *          and if it corresponds to a DeflatedExplicitVRLittleEndian one.
273  *
274  * @return  True when DeflatedExplicitVRLittleEndian found. False in all other cases.
275  */
276 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
277    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
278    if ( !Element )
279       return false;
280    LoadHeaderEntrySafe(Element);
281
282    std::string Transfer = Element->GetValue();
283    if ( Transfer == UI1_2_840_10008_1_2_1_99 )
284       return true;
285    return false;
286 }
287
288 /**
289  * \ingroup gdcmParser
290  * \brief   Determines if the Transfer Syntax was already encountered
291  *          and if it corresponds to a Explicit VR Big Endian one.
292  *
293  * @return  True when big endian found. False in all other cases.
294  */
295 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
296    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
297    if ( !Element )
298       return false;
299    LoadHeaderEntrySafe(Element);
300
301    std::string Transfer = Element->GetValue();
302    if ( Transfer == UI1_2_840_10008_1_2_2 )  //1.2.2 ??? A verifier !
303       return true;
304    return false;
305 }
306
307 /**
308  * \ingroup gdcmParser
309  * \brief  returns the File Type 
310  *         (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
311  * @return 
312  */
313 FileType gdcmParser::GetFileType(void) {
314    return(filetype);
315 }
316
317 /**
318  * \ingroup gdcmParser
319  * \brief   opens the file
320  * @param   exception_on_error
321  * @return  
322  */
323 FILE *gdcmParser::OpenFile(bool exception_on_error)
324   throw(gdcmFileError) 
325 {
326   fp=fopen(filename.c_str(),"rb");
327   if(exception_on_error) 
328   {
329     if(!fp)
330       throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
331   }
332
333   if ( fp ) 
334   {
335      guint16 zero;
336      fread(&zero,  (size_t)2, (size_t)1, fp);
337
338     //ACR -- or DICOM with no Preamble --
339     if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
340        return(fp);
341
342     //DICOM
343     fseek(fp, 126L, SEEK_CUR);
344     char dicm[4];
345     fread(dicm,  (size_t)4, (size_t)1, fp);
346     if( memcmp(dicm, "DICM", 4) == 0 )
347        return(fp);
348
349     fclose(fp);
350     dbg.Verbose(0, "gdcmParser::gdcmParser not DICOM/ACR", filename.c_str());
351   }
352   else {
353     dbg.Verbose(0, "gdcmParser::gdcmParser cannot open file", filename.c_str());
354   }
355   return(NULL);
356 }
357
358 /**
359  * \ingroup gdcmParser
360  * \brief closes the file  
361  * @return  TRUE if the close was successfull 
362  */
363 bool gdcmParser::CloseFile(void) {
364   int closed = fclose(fp);
365   fp = (FILE *)0;
366   if (! closed)
367      return false;
368   return true;
369 }
370
371 /**
372  * \ingroup gdcmParser
373  * \brief 
374  * @param fp file pointer on an already open file
375  * @param   type type of the File to be written 
376  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
377  * @return  always "True" ?!
378  */
379 bool gdcmParser::Write(FILE *fp, FileType type) {
380 // ==============
381 // TODO The stuff has been rewritten using the chained list instead 
382 //      of the H table
383 //      so we could remove the GroupHT from the gdcmParser
384 // To be checked
385 // =============
386
387    // TODO : move the following lines (and a lot of others, to be written)
388    // to a future function CheckAndCorrectHeader
389    
390         // Question :
391         // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
392         // (FileType est un champ de gdcmParser ...)
393         // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
394         // no way 
395         // a moins de se livrer a un tres complique ajout des champs manquants.
396         // faire un CheckAndCorrectHeader (?)  
397          
398
399    if (type == ImplicitVR) 
400    {
401       std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
402       ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
403       
404       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
405       //      values with a VR of UI shall be padded with a single trailing null
406       //      Dans le cas suivant on doit pader manuellement avec un 0
407       
408       SetEntryLengthByNumber(18, 0x0002, 0x0010);
409    } 
410
411    if (type == ExplicitVR) 
412    {
413       std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
414       ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
415       
416       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
417       //      values with a VR of UI shall be padded with a single trailing null
418       //      Dans le cas suivant on doit pader manuellement avec un 0
419       
420       SetEntryLengthByNumber(20, 0x0002, 0x0010);
421    }
422
423
424    if ( (type == ImplicitVR) || (type == ExplicitVR) )
425       UpdateGroupLength(false,type);
426    if ( type == ACR)
427       UpdateGroupLength(true,ACR);
428
429    WriteEntries(type, fp);
430    return(true);
431  }
432
433 /**
434  * \ingroup gdcmParser
435  * \brief   Modifies the value of a given Header Entry (Dicom Element)
436  *          if it exists; Creates it with the given value if it doesn't
437  * @param   Value passed as a std::string
438  * @param   Group
439  * @param   Elem
440  * \return  boolean
441  */
442 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value, 
443                                          guint16 Group, 
444                                          guint16 Elem ){
445    if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
446       gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
447       if (a == NULL) 
448          return false;
449       AddHeaderEntry(a);
450    }   
451    SetEntryByNumber(Value, Group, Elem);
452    return(true);
453 }   
454
455 /**
456  * \ingroup gdcmParser
457  * \brief   Modifies the value of a given Header Entry (Dicom Element)
458  *          if it exists; Creates it with the given value if it doesn't
459  * @param   Value passed as a char*
460  * @param   Group
461  * @param   Elem
462  * \return  boolean 
463  * 
464  */
465 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
466    gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
467
468    if(!nvHeaderEntry)
469       return(false);
470
471    AddHeaderEntry(nvHeaderEntry);
472
473    std::string v = Value;       
474    SetEntryByNumber(v, Group, Elem);
475    return(true);
476 }  
477
478 /**
479  * \ingroup gdcmParser
480  * \brief   Set a new value if the invoked element exists
481  *          Seems to be useless !!!
482  * @param   Value
483  * @param   Group
484  * @param   Elem
485  * \return  boolean 
486  */
487 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) 
488 {
489    std::string v = Value;       
490    SetEntryByNumber(v, Group, Elem);
491    return true;
492
493
494 //-----------------------------------------------------------------------------
495 // Protected
496 /**
497  * \ingroup gdcmParser
498  * \brief   Checks if a given Dicom Element exists
499  * \        within the H table
500  * @param   group Group   number of the searched Dicom Element 
501  * @param   element  Element number of the searched Dicom Element 
502  * @return  number of occurences
503  */
504 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
505         std::string key = gdcmDictEntry::TranslateToKey(group, element );
506         return (tagHT.count(key));
507 }
508
509 /**
510  * \ingroup gdcmParser
511  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
512  *          the public and private dictionaries 
513  *          for the element value of a given tag.
514  * \warning Don't use any longer : use GetPubEntryByName
515  * @param   tagName name of the searched element.
516  * @return  Corresponding element value when it exists,
517  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
518  */
519 std::string gdcmParser::GetEntryByName(std::string tagName) {
520    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
521    if( dictEntry == NULL)
522       return GDCM_UNFOUND;
523
524    return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));  
525 }
526
527 /**
528  * \ingroup gdcmParser
529  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
530  *          the public and private dictionaries 
531  *          for the element value representation of a given tag.
532  *
533  *          Obtaining the VR (Value Representation) might be needed by caller
534  *          to convert the string typed content to caller's native type 
535  *          (think of C++ vs Python). The VR is actually of a higher level
536  *          of semantics than just the native C++ type.
537  * @param   tagName name of the searched element.
538  * @return  Corresponding element value representation when it exists,
539  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
540  */
541 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
542    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
543    if( dictEntry == NULL)
544       return GDCM_UNFOUND;
545
546    gdcmHeaderEntry* elem =  GetHeaderEntryByNumber(dictEntry->GetGroup(),
547                                                    dictEntry->GetElement());                                    
548    return elem->GetVR();
549 }
550
551 /**
552  * \ingroup gdcmParser
553  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
554  *          the public and private dictionaries 
555  *          for the element value representation of a given tag.
556  * @param   group Group of the searched tag.
557  * @param   element Element of the searched tag.
558  * @return  Corresponding element value representation when it exists,
559  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
560  */
561 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
562    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
563    if ( ! tagHT.count(key))
564       return GDCM_UNFOUND;
565    return tagHT.find(key)->second->GetValue();
566 }
567
568 /**
569  * \ingroup gdcmParser
570  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
571  *          the public and private dictionaries 
572  *          for the element value representation of a given tag..
573  *
574  *          Obtaining the VR (Value Representation) might be needed by caller
575  *          to convert the string typed content to caller's native type 
576  *          (think of C++ vs Python). The VR is actually of a higher level
577  *          of semantics than just the native C++ type.
578  * @param   group Group of the searched tag.
579  * @param   element Element of the searched tag.
580  * @return  Corresponding element value representation when it exists,
581  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
582  */
583 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
584    gdcmHeaderEntry* elem =  GetHeaderEntryByNumber(group, element);
585    if ( !elem )
586       return GDCM_UNFOUND;
587    return elem->GetVR();
588 }
589
590 /**
591  * \ingroup gdcmParser
592  * \brief   Sets the value (string) of the Header Entry (Dicom Element)
593  * @param   content string value of the Dicom Element
594  * @param   tagName name of the searched Dicom Element.
595  * @return  true when found
596  */
597 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
598    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
599    if( dictEntry == NULL)
600       return false;                                 
601
602    return(SetEntryByNumber(content,dictEntry->GetGroup(),
603                                    dictEntry->GetElement()));
604 }
605
606 /**
607  * \ingroup gdcmParser
608  * \brief   Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
609  *          through it's (group, element) and modifies it's content with
610  *          the given value.
611  * \warning Don't use any longer : use SetPubEntryByNumber
612  * @param   content new value to substitute with
613  * @param   group   group of the Dicom Element to modify
614  * @param   element element of the Dicom Element to modify
615  */
616 bool gdcmParser::SetEntryByNumber(std::string content, 
617                                   guint16 group,
618                                   guint16 element) 
619 {
620    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
621    if ( ! tagHT.count(key))
622       return false;
623    int l = content.length();
624    if(l%2) // Odd length are padded with a space (020H).
625    {  
626       l++;
627       content = content + '\0';
628    }
629       
630    gdcmHeaderEntry * a;
631    IterHT p;
632    TagHeaderEntryHT::iterator p2;
633    // DO NOT remove the following lines : they explain the stuff   
634    //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
635    //p2=p.first;                // iterator on the first synonym 
636    //a=p2->second;              // H Table target column (2-nd col)
637     
638    // or, easier :
639    a = ((tagHT.equal_range(key)).first)->second; 
640        
641    a-> SetValue(content); 
642    
643    std::string vr = a->GetVR();
644    
645    guint32 lgr;
646    if( (vr == "US") || (vr == "SS") ) 
647       lgr = 2;
648    else if( (vr == "UL") || (vr == "SL") )
649       lgr = 4;
650    else
651       lgr = l;     
652
653    a->SetLength(lgr);   
654    return true;
655 }                                         
656
657 /**
658  * \ingroup gdcmParser
659  * \brief   Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
660  *          in the PubHeaderEntrySet of this instance
661  *          through it's (group, element) and modifies it's length with
662  *          the given value.
663  * \warning Use with extreme caution.
664  * @param   length new length to substitute with
665  * @param   group   group of the entry to modify
666  * @param   element element of the Entry to modify
667  * @return  1 on success, 0 otherwise.
668  */
669
670 bool gdcmParser::SetEntryLengthByNumber(guint32 length, 
671                                         guint16 group, 
672                                         guint16 element) 
673 {
674    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
675    if ( ! tagHT.count(key))
676       return false;
677    if (length%2) length++; // length must be even
678    ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);      
679          
680    return true ;                
681 }
682
683 /**
684  * \ingroup gdcmParser
685  * \brief   Gets (from Header) the offset  of a 'non string' element value 
686  * \        (LoadElementValues has already be executed)
687  * @param   Group
688  * @param   Elem
689  * @return File Offset of the Element Value 
690  */
691 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem) 
692 {
693    gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);         
694    if (!Entry) 
695    {
696       dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
697                       "failed to Locate gdcmHeaderEntry");
698       return (size_t)0;
699    }
700    return Entry->GetOffset();
701 }
702
703 /**
704  * \ingroup gdcmParser
705  * \brief   Gets (from Header) a 'non string' element value 
706  * \        (LoadElementValues has already be executed)  
707  * @param   Group
708  * @param   Elem
709  * @return Pointer to the 'non string' area
710  */
711 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem) 
712 {
713    gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);         
714    if (!Entry) 
715    {
716       dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
717                   "failed to Locate gdcmHeaderEntry");
718       return (NULL);
719    }
720    return Entry->GetVoidArea();
721 }
722
723 /**
724  * \ingroup       gdcmParser
725  * \brief         Loads (from disk) the element content 
726  *                when a string is not suitable
727  * @param   Group
728  * @param   Elem
729  */
730 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem) 
731 {
732    gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
733    if ( !Element )
734       return NULL;
735    size_t o =(size_t)Element->GetOffset();
736    fseek(fp, o, SEEK_SET);
737    int l=Element->GetLength();
738    void * a = malloc(l);
739    if(!a) 
740         return NULL;
741
742    SetEntryVoidAreaByNumber(a, Group, Elem);
743    // TODO check the result 
744    size_t l2 = fread(a, 1, l ,fp);
745    if(l != l2) 
746    {
747         free(a);
748         return NULL;
749    }
750    return a;  
751 }
752
753 /**
754  * \ingroup gdcmParser
755  * \brief   Sets a 'non string' value to a given Dicom Element
756  * @param   area
757  * @param   group Group number of the searched Dicom Element 
758  * @param   element Element number of the searched Dicom Element 
759  * @return  
760  */
761 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
762                                           guint16 group, 
763                                           guint16 element) 
764 {
765    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
766    if ( ! tagHT.count(key))
767       return false;
768    ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);      
769    return true;
770 }
771
772 /**
773  * \ingroup gdcmParser
774  * \brief   Update the entries with the shadow dictionary. Only odd entries are
775  *          analized
776  */
777 void gdcmParser::UpdateShaEntries(void) {
778    gdcmDictEntry *entry;
779    std::string vr;
780
781    for(ListTag::iterator it=listEntries.begin();
782        it!=listEntries.end();
783        ++it)
784    {
785       // Odd group => from public dictionary
786       if((*it)->GetGroup()%2==0)
787          continue;
788
789       // Peer group => search the corresponding dict entry
790       if(RefShaDict)
791          entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
792       else
793          entry=NULL;
794
795       if((*it)->IsImplicitVR())
796          vr="Implicit";
797       else
798          vr=(*it)->GetVR();
799
800       (*it)->SetValue(GetHeaderEntryUnvalue(*it));
801       if(entry){
802          // Set the new entry and the new value
803          (*it)->SetDictEntry(entry);
804          CheckHeaderEntryVR(*it,vr);
805
806          (*it)->SetValue(GetHeaderEntryValue(*it));
807       }
808       else
809       {
810          // Remove precedent value transformation
811          (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
812       }
813    }
814 }
815
816 /**
817  * \ingroup gdcmParser
818  * \brief   Searches within the Header Entries for a Dicom Element of
819  *          a given tag.
820  * @param   tagName name of the searched Dicom Element.
821  * @return  Corresponding Dicom Element when it exists, and NULL
822  *          otherwise.
823  */
824  gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
825    gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
826    if( dictEntry == NULL)
827       return NULL;
828
829   return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
830 }
831
832 /**
833  * \ingroup gdcmParser
834  * \brief  retrieves a Dicom Element (the first one) using (group, element)
835  * \ warning (group, element) IS NOT an identifier inside the Dicom Header
836  *           if you think it's NOT UNIQUE, check the count number
837  *           and use iterators to retrieve ALL the Dicoms Elements within
838  *           a given couple (group, element)
839  * @param   group Group number of the searched Dicom Element 
840  * @param   element Element number of the searched Dicom Element 
841  * @return  
842  */
843 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element) 
844 {
845    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
846    if ( ! tagHT.count(key))
847       return NULL;
848    return tagHT.find(key)->second;
849 }
850
851 /**
852  * \ingroup gdcmParser
853  * \brief   retrieves the Dicom Elements (all of them) using (group, element) 
854  * @param   group Group number of the searched Dicom Element.
855  * @param   element Element number of the searched Dicom Element.
856  * @return  a range (i.e.pair<,>) containing all elements whose key is group|element) 
857  */
858  
859 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
860    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
861    return (tagHT.equal_range(key));
862 }
863
864 /**
865  * \ingroup       gdcmParser
866  * \brief         Loads the element while preserving the current
867  *                underlying file position indicator as opposed to
868  *                to LoadHeaderEntry that modifies it.
869  * @param entry   Header Entry whose value shall be loaded. 
870  * @return  
871  */
872 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
873    long PositionOnEntry = ftell(fp);
874    LoadHeaderEntry(entry);
875    fseek(fp, PositionOnEntry, SEEK_SET);
876 }
877
878 /**
879  * \ingroup gdcmParser
880  * \brief   Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
881  * \warning : to be re-written using the chained list instead of the H table.
882  * \warning : DO NOT use (doesn't work any longer because of the multimap)
883  * \todo : to be re-written using the chained list instead of the H table
884  * @param   SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
885  * @param   type Type of the File (ExplicitVR,ImplicitVR, ACR, ...) 
886  */
887 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
888    guint16 gr, el;
889    std::string vr;
890    
891    gdcmHeaderEntry *elem;
892    char trash[10];
893    std::string str_trash;
894    
895    GroupKey key;
896    GroupHT groupHt;  // to hold the length of each group
897    TagKey tk;
898    // remember :
899    // typedef std::map<GroupKey, int> GroupHT;
900    
901    gdcmHeaderEntry *elemZ;
902   
903    // for each Tag in the DCM Header
904    
905    for (TagHeaderEntryHT::iterator tag2 = tagHT.begin(); 
906         tag2 != tagHT.end();
907         ++tag2)
908    {
909       elem  = tag2->second;
910       gr = elem->GetGroup();
911       el = elem->GetElement();
912       vr = elem->GetVR(); 
913                  
914       sprintf(trash, "%04x", gr);
915       key = trash;              // generate 'group tag'
916       
917       // if the caller decided not to take SEQUENCEs into account 
918       // e.g : he wants to write an ACR-NEMA File 
919                 
920       if (SkipSequence && vr == "SQ") 
921          continue;
922       
923       // Still unsolved problem :
924       // we cannot find the 'Sequence Delimitation Item'
925       // since it's at the end of the Hash Table
926       // (fffe,e0dd) 
927        
928       // pas SEQUENCE en ACR-NEMA
929       // WARNING : 
930       // --> la descente a l'interieur' des SQ 
931       // devrait etre faite avec une liste chainee, pas avec une HTable...
932             
933       if ( groupHt.count(key) == 0) // we just read the first elem of a given group
934       { 
935          if (el == 0x0000) // the first elem is 0x0000
936          {            
937             groupHt[key] = 0;         // initialize group length 
938          } 
939          else 
940          {
941             groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
942          } 
943       } 
944       else // any elem but the first
945       {   
946          if (type == ExplicitVR) 
947          {
948             if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) 
949             {
950                groupHt[key] +=  4; // explicit VR AND OB, OW, SQ : 4 more bytes
951             }
952          }
953          groupHt[key] += 2 + 2 + 4 + elem->GetLength(); 
954       } 
955    }
956
957    unsigned short int gr_bid;
958   
959    for (GroupHT::iterator g = groupHt.begin(); // for each group we found
960         g != groupHt.end();
961         ++g)
962    { 
963       // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
964       //        warning: unsigned int format, different type arg
965       sscanf(g->first.c_str(),"%x",&gr_bid);
966       tk = g->first + "|0000";                  // generate the element full tag
967                      
968       if ( tagHT.count(tk) == 0) // if element 0x0000 not found
969       {                 
970          gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");       
971          elemZ = new gdcmHeaderEntry(tagZ);
972          elemZ->SetLength(4);
973          AddHeaderEntry(elemZ);                         // create it
974       } 
975       else 
976       {
977          elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
978       }     
979       sprintf(trash ,"%d",g->second);
980       str_trash=trash;
981       elemZ->SetValue(str_trash);
982    }   
983 }
984
985 /**
986  * \ingroup gdcmParser
987  * \brief   writes on disc according to the requested format
988  * \        (ACR-NEMA, ExplicitVR, ImplicitVR) the image
989  * \ warning does NOT add the missing elements in the header :
990  * \         it's up to the user doing it !
991  * \         (function CheckHeaderCoherence to be written)
992  * @param   type type of the File to be written 
993  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
994  * @param   _fp already open file pointer
995  */
996 void gdcmParser::WriteEntries(FileType type, FILE * _fp) 
997 {
998    guint16 gr, el;
999    guint32 lgr;
1000    const char * val;
1001    std::string vr;
1002    guint32 val_uint32;
1003    guint16 val_uint16;
1004    
1005    std::vector<std::string> tokens;
1006    
1007    //  uses now listEntries to iterate, not TagHt!
1008    //
1009    //        pb : gdcmParser.Add does NOT update listEntries
1010    //       TODO : find a trick (in STL?) to do it, at low cost !
1011
1012    void *ptr;
1013
1014    // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1015
1016    for (ListTag::iterator tag2=listEntries.begin();
1017         tag2 != listEntries.end();
1018         ++tag2)
1019    {
1020       gr =  (*tag2)->GetGroup();
1021       el =  (*tag2)->GetElement();
1022       lgr = (*tag2)->GetLength();
1023       val = (*tag2)->GetValue().c_str();
1024       vr =  (*tag2)->GetVR();
1025       
1026       if ( type == ACR ) 
1027       { 
1028          if (gr < 0x0008)   continue; // ignore pure DICOM V3 groups
1029          if (gr %2)         continue; // ignore shadow groups
1030          if (vr == "SQ" )   continue; // ignore Sequences
1031                    // TODO : find a trick to *skip* the SeQuences !
1032                    // Not only ignore the SQ element
1033          if (gr == 0xfffe ) continue; // ignore delimiters
1034       } 
1035
1036       fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp);  //group
1037       fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp);  //element
1038
1039       if ( (type == ExplicitVR) && (gr <= 0x0002) ) 
1040       {
1041          // EXPLICIT VR
1042          guint16 z=0, shortLgr;
1043          fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1044
1045          if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) 
1046          {
1047             fwrite ( &z,  (size_t)2 ,(size_t)1 ,_fp);
1048             fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1049
1050          } 
1051          else 
1052          {
1053             shortLgr=lgr;
1054             fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1055          }
1056       } 
1057       else // IMPLICIT VR
1058       { 
1059          fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1060       }
1061
1062       if (vr == "US" || vr == "SS") 
1063       {
1064          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1065          Tokenize ((*tag2)->GetValue(), tokens, "\\");
1066          for (unsigned int i=0; i<tokens.size();i++) 
1067          {
1068             val_uint16 = atoi(tokens[i].c_str());
1069             ptr = &val_uint16;
1070             fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1071          }
1072          tokens.clear();
1073          continue;
1074       }
1075       if (vr == "UL" || vr == "SL") 
1076       {
1077          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1078          Tokenize ((*tag2)->GetValue(), tokens, "\\");
1079          for (unsigned int i=0; i<tokens.size();i++) 
1080          {
1081             val_uint32 = atoi(tokens[i].c_str());
1082             ptr = &val_uint32;
1083             fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1084          }
1085          tokens.clear();
1086          continue;
1087       }     
1088       // Pixels are never loaded in the element !
1089       if ((gr == 0x7fe0) && (el == 0x0010) ) 
1090          break;
1091
1092       fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1093    }
1094 }
1095
1096 /**
1097  * \ingroup gdcmParser
1098  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1099  *          processor order.
1100  * @return  The properly swaped 32 bits integer.
1101  */
1102 guint32 gdcmParser::SwapLong(guint32 a) {
1103    switch (sw) {
1104       case    0 :
1105          break;
1106       case 4321 :
1107          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
1108              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1109          break;
1110    
1111       case 3412 :
1112          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1113          break;
1114    
1115       case 2143 :
1116          a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1117          break;
1118       default :
1119          dbg.Error(" gdcmParser::SwapLong : unset swap code");
1120          a=0;
1121    }
1122    return(a);
1123 }
1124
1125 /**
1126  * \ingroup gdcmParser
1127  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
1128  *          processor order.
1129  * @return  The properly unswaped 32 bits integer.
1130  */
1131 guint32 gdcmParser::UnswapLong(guint32 a) {
1132    return (SwapLong(a));
1133 }
1134
1135 /**
1136  * \ingroup gdcmParser
1137  * \brief   Swaps the bytes so they agree with the processor order
1138  * @return  The properly swaped 16 bits integer.
1139  */
1140 guint16 gdcmParser::SwapShort(guint16 a) {
1141    if ( (sw==4321)  || (sw==2143) )
1142       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1143    return (a);
1144 }
1145
1146 /**
1147  * \ingroup gdcmParser
1148  * \brief   Unswaps the bytes so they agree with the processor order
1149  * @return  The properly unswaped 16 bits integer.
1150  */
1151 guint16 gdcmParser::UnswapShort(guint16 a) {
1152    return (SwapShort(a));
1153 }
1154
1155 //-----------------------------------------------------------------------------
1156 // Private
1157 /**
1158  * \ingroup gdcmParser
1159  * \brief   Parses the header of the file but WITHOUT loading element values.
1160  */
1161 void gdcmParser::Parse(bool exception_on_error) throw(gdcmFormatError) {
1162    gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1163    
1164    rewind(fp);
1165    CheckSwap();
1166    while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1167      SkipHeaderEntry(newHeaderEntry);
1168      if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) { //JPR
1169         AddHeaderEntry(newHeaderEntry); 
1170      }       
1171    }
1172 }
1173
1174 /**
1175  * \ingroup gdcmParser
1176  * \brief   Loads the element values of all the Header Entries pointed in the
1177  *          public Chained List.
1178  */
1179 void gdcmParser::LoadHeaderEntries(void) {
1180    rewind(fp);
1181    for (ListTag::iterator i = GetListEntry().begin();
1182       i != GetListEntry().end();
1183       ++i)
1184    {
1185       LoadHeaderEntry(*i);
1186    }
1187             
1188    rewind(fp);
1189
1190    // Load 'non string' values   
1191    std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);   
1192    if( PhotometricInterpretation == "PALETTE COLOR " ) {
1193       LoadEntryVoidArea(0x0028,0x1200);  // gray LUT   
1194       LoadEntryVoidArea(0x0028,0x1201);  // R    LUT
1195       LoadEntryVoidArea(0x0028,0x1202);  // G    LUT
1196       LoadEntryVoidArea(0x0028,0x1203);  // B    LUT
1197       
1198       LoadEntryVoidArea(0x0028,0x1221);  // Segmented Red   Palette Color LUT Data
1199       LoadEntryVoidArea(0x0028,0x1222);  // Segmented Green Palette Color LUT Data
1200       LoadEntryVoidArea(0x0028,0x1223);  // Segmented Blue  Palette Color LUT Data
1201    }
1202
1203    // --------------------------------------------------------------
1204    // Special Patch to allow gdcm to read ACR-LibIDO formated images
1205    //
1206    // if recognition code tells us we deal with a LibIDO image
1207    // we switch lineNumber and columnNumber
1208    //
1209    std::string RecCode; 
1210    RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1211    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1212        RecCode == "CANRME_AILIBOD1_1." ) 
1213    {
1214          filetype = ACR_LIBIDO; 
1215          std::string rows    = GetEntryByNumber(0x0028, 0x0010);
1216          std::string columns = GetEntryByNumber(0x0028, 0x0011);
1217          SetEntryByNumber(columns, 0x0028, 0x0010);
1218          SetEntryByNumber(rows   , 0x0028, 0x0011);
1219    }
1220    // ----------------- End of Special Patch ----------------
1221 }
1222
1223 /**
1224  * \ingroup       gdcmParser
1225  * \brief         Loads the element content if it's length is not bigger
1226  *                than the value specified with
1227  *                gdcmParser::SetMaxSizeLoadEntry()
1228  * @param         Entry Header Entry (Dicom Element) to be dealt with
1229  */
1230 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry)  {
1231    size_t item_read;
1232    guint16 group  = Entry->GetGroup();
1233    std::string  vr= Entry->GetVR();
1234    guint32 length = Entry->GetLength();
1235    bool SkipLoad  = false;
1236
1237    fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1238    
1239    // the test was commented out to 'go inside' the SeQuences
1240    // we don't any longer skip them !
1241     
1242    // if( vr == "SQ" )  //  (DO NOT remove this comment)
1243    //    SkipLoad = true;
1244
1245    // A SeQuence "contains" a set of Elements.  
1246    //          (fffe e000) tells us an Element is beginning
1247    //          (fffe e00d) tells us an Element just ended
1248    //          (fffe e0dd) tells us the current SeQuence just ended
1249    if( group == 0xfffe )
1250       SkipLoad = true;
1251
1252    if ( SkipLoad ) {
1253       Entry->SetLength(0);
1254       Entry->SetValue("gdcm::Skipped");
1255       return;
1256    }
1257
1258    // When the length is zero things are easy:
1259    if ( length == 0 ) {
1260       Entry->SetValue("");
1261       return;
1262    }
1263
1264    // The elements whose length is bigger than the specified upper bound
1265    // are not loaded. Instead we leave a short notice of the offset of
1266    // the element content and it's length.
1267    if (length > MaxSizeLoadEntry) {
1268       std::ostringstream s;
1269       s << "gdcm::NotLoaded.";
1270       s << " Address:" << (long)Entry->GetOffset();
1271       s << " Length:"  << Entry->GetLength();
1272       s << " x(" << std::hex << Entry->GetLength() << ")";
1273       Entry->SetValue(s.str());
1274       return;
1275    }
1276    
1277    // When integer(s) are expected, read and convert the following 
1278    // n *(two or four bytes)
1279    // properly i.e. as integers as opposed to a strings.        
1280    // Elements with Value Multiplicity > 1
1281    // contain a set of integers (not a single one) 
1282         
1283    // Any compacter code suggested (?)
1284    if ( IsHeaderEntryAnInteger(Entry) ) {   
1285       guint32 NewInt;
1286       std::ostringstream s;
1287       int nbInt;
1288       if (vr == "US" || vr == "SS") {
1289          nbInt = length / 2;
1290          NewInt = ReadInt16();
1291          s << NewInt;
1292          if (nbInt > 1){
1293             for (int i=1; i < nbInt; i++) {
1294                s << '\\';
1295                NewInt = ReadInt16();
1296                s << NewInt;
1297             }
1298          }                      
1299       }
1300       else if (vr == "UL" || vr == "SL") {
1301          nbInt = length / 4;
1302          NewInt = ReadInt32();
1303          s << NewInt;
1304          if (nbInt > 1) {
1305             for (int i=1; i < nbInt; i++) {
1306                s << '\\';
1307                NewInt = ReadInt32();
1308                s << NewInt;
1309             }
1310          }
1311       }
1312 #ifdef GDCM_NO_ANSI_STRING_STREAM
1313       s << std::ends; // to avoid oddities on Solaris
1314 #endif //GDCM_NO_ANSI_STRING_STREAM
1315
1316       Entry->SetValue(s.str());
1317       return;   
1318    }
1319    
1320    // We need an additional byte for storing \0 that is not on disk
1321    std::string NewValue(length,0);
1322    item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1323    if ( item_read != 1 ) {
1324       dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1325       Entry->SetValue("gdcm::UnRead");
1326       return;
1327    }
1328
1329    if( (vr == "UI") ) // Because of correspondance with the VR dic
1330       Entry->SetValue(NewValue.c_str());
1331    else
1332       Entry->SetValue(NewValue);
1333 }
1334
1335 /**
1336  * \ingroup gdcmParser
1337  * \brief   add a new Dicom Element pointer to 
1338  *          the H Table and to the chained List
1339  * \warning push_bash in listEntries ONLY during ParseHeader
1340  * \todo    something to allow further Elements addition,
1341  * \        when position to be taken care of     
1342  * @param   newHeaderEntry
1343  */
1344 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1345    tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1346    listEntries.push_back(newHeaderEntry); 
1347    wasUpdated = 1;
1348 }
1349
1350 /**
1351  * \ingroup gdcmParser
1352  * \brief   
1353  * @param   Entry Header Entry whose length of the value shall be loaded. 
1354
1355  * @return 
1356  */
1357  void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
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)+
1614                      ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1615             NewInt32=SwapLong(NewInt32);
1616             s << NewInt32;
1617          }
1618       }
1619
1620 #ifdef GDCM_NO_ANSI_STRING_STREAM
1621       s << std::ends; // to avoid oddities on Solaris
1622 #endif //GDCM_NO_ANSI_STRING_STREAM
1623       return(s.str());
1624    }
1625
1626    return(Entry->GetValue());
1627 }
1628
1629 /**
1630  * \ingroup gdcmParser
1631  * \brief   Get the reverse transformed value of the header entry. The VR 
1632  *          value is used to define the reverse transformation to operate on
1633  *          the value
1634  * \warning NOT end user intended method !
1635  * @param   Entry 
1636  * @return  Reverse transformed entry value
1637  */
1638 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1639 {
1640    if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1641    {
1642       std::string vr=Entry->GetVR();
1643       std::ostringstream s;
1644       std::vector<std::string> tokens;
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;      // ReadLength is unchanged         
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    guint16 element = Entry->GetElement();
1770    guint16 group   = Entry->GetGroup();
1771    std::string  vr = Entry->GetVR();
1772    guint32 length  = Entry->GetLength();
1773    // When we have some semantics on the element we just read, and if we
1774    // a priori know we are dealing with an integer, then we shall be
1775    // able to swap it's element value properly.
1776    if ( element == 0 )  // This is the group length of the group
1777    {  
1778       if (length == 4)
1779          return true;
1780       else 
1781       {
1782          std::ostringstream s;
1783          int filePosition = ftell(fp);
1784          s << "Erroneous Group Length element length  on : (" \
1785            << std::hex << group << " , " << element 
1786            << ") -before- position x(" << filePosition << ")"
1787            << "lgt : " << length;
1788         // These 2 lines commented out : a *very dirty* patch
1789         // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1790         // have a glance at offset  x(8336) ...
1791         // For *regular* headers, the test is useless..
1792         // lets's print a warning message and go on, 
1793         // instead of giving up with an error message
1794         std::cout << s.str().c_str() << std::endl;
1795         // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1796         //    s.str().c_str());     
1797       }
1798    }
1799    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1800       return true;
1801    
1802    return false;
1803 }
1804
1805 /**
1806  * \ingroup gdcmParser
1807  * \brief   
1808  *
1809  * @return 
1810  */
1811  guint32 gdcmParser::FindHeaderEntryLengthOB(void)  {
1812    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1813    guint16 g;
1814    guint16 n; 
1815    long PositionOnEntry = ftell(fp);
1816    bool FoundSequenceDelimiter = false;
1817    guint32 TotalLength = 0;
1818    guint32 ItemLength;
1819
1820    while ( ! FoundSequenceDelimiter) 
1821    {
1822       g = ReadInt16();
1823       n = ReadInt16();   
1824       if (errno == 1)
1825          return 0;
1826       TotalLength += 4;  // We even have to decount the group and element 
1827      
1828       if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ 
1829       {
1830          char msg[100]; // for sprintf. Sorry
1831          sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1832          dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg); 
1833          errno = 1;
1834          return 0;
1835       }
1836       if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header  */ 
1837          FoundSequenceDelimiter = true;
1838       else if ( n != 0xe000 )
1839       {
1840          char msg[100];  // for sprintf. Sorry
1841          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1842                       n, g,n);
1843          dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1844          errno = 1;
1845          return 0;
1846       }
1847       ItemLength = ReadInt32();
1848       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
1849                                       // the ItemLength with ReadInt32                                     
1850       SkipBytes(ItemLength);
1851    }
1852    fseek(fp, PositionOnEntry, SEEK_SET);
1853    return TotalLength;
1854 }
1855
1856 /**
1857  * \ingroup gdcmParser
1858  * \brief Reads a supposed to be 16 Bits integer
1859  * \     (swaps it depending on processor endianity) 
1860  *
1861  * @return read value
1862  */
1863 guint16 gdcmParser::ReadInt16(void) {
1864    guint16 g;
1865    size_t item_read;
1866    item_read = fread (&g, (size_t)2,(size_t)1, fp);
1867    if ( item_read != 1 ) {
1868       if(ferror(fp)) 
1869          dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1870       errno = 1;
1871       return 0;
1872    }
1873    errno = 0;
1874    g = SwapShort(g);   
1875    return g;
1876 }
1877
1878 /**
1879  * \ingroup gdcmParser
1880  * \brief  Reads a supposed to be 32 Bits integer
1881  * \       (swaps it depending on processor endianity)  
1882  *
1883  * @return read value
1884  */
1885 guint32 gdcmParser::ReadInt32(void) {
1886    guint32 g;
1887    size_t item_read;
1888    item_read = fread (&g, (size_t)4,(size_t)1, fp);
1889    if ( item_read != 1 ) { 
1890      if(ferror(fp)) 
1891          dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");   
1892       errno = 1;
1893       return 0;
1894    }
1895    errno = 0;   
1896    g = SwapLong(g);
1897    return g;
1898 }
1899
1900 /**
1901  * \ingroup gdcmParser
1902  * \brief   
1903  *
1904  * @return 
1905  */
1906 void gdcmParser::SkipBytes(guint32 NBytes) {
1907    //FIXME don't dump the returned value
1908    (void)fseek(fp, (long)NBytes, SEEK_CUR);
1909 }
1910
1911 /**
1912  * \ingroup gdcmParser
1913  * \brief   
1914  */
1915 void gdcmParser::Initialise(void) 
1916 {
1917    RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1918    RefShaDict = (gdcmDict*)0;
1919 }
1920
1921 /**
1922  * \ingroup gdcmParser
1923  * \brief   Discover what the swap code is (among little endian, big endian,
1924  *          bad little endian, bad big endian).
1925  *
1926  */
1927 void gdcmParser::CheckSwap() {
1928
1929    // The only guaranted way of finding the swap code is to find a
1930    // group tag since we know it's length has to be of four bytes i.e.
1931    // 0x00000004. Finding the swap code in then straigthforward. Trouble
1932    // occurs when we can't find such group...
1933    
1934    guint32  s;
1935    guint32  x=4;  // x : for ntohs
1936    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1937     
1938    int lgrLue;
1939    char *entCur;
1940    char deb[HEADER_LENGTH_TO_READ];
1941     
1942    // First, compare HostByteOrder and NetworkByteOrder in order to
1943    // determine if we shall need to swap bytes (i.e. the Endian type).
1944    if (x==ntohs(x))
1945       net2host = true;
1946    else
1947       net2host = false; 
1948          
1949    // The easiest case is the one of a DICOM header, since it possesses a
1950    // file preamble where it suffice to look for the string "DICM".
1951    lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1952    
1953    entCur = deb + 128;
1954    if(memcmp(entCur, "DICM", (size_t)4) == 0) {
1955       dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
1956       
1957       // Next, determine the value representation (VR). Let's skip to the
1958       // first element (0002, 0000) and check there if we find "UL" 
1959       // - or "OB" if the 1st one is (0002,0001) -,
1960       // in which case we (almost) know it is explicit VR.
1961       // WARNING: if it happens to be implicit VR then what we will read
1962       // is the length of the group. If this ascii representation of this
1963       // length happens to be "UL" then we shall believe it is explicit VR.
1964       // FIXME: in order to fix the above warning, we could read the next
1965       // element value (or a couple of elements values) in order to make
1966       // sure we are not commiting a big mistake.
1967       // We need to skip :
1968       // * the 128 bytes of File Preamble (often padded with zeroes),
1969       // * the 4 bytes of "DICM" string,
1970       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1971       // i.e. a total of  136 bytes.
1972       entCur = deb + 136;
1973       // FIXME
1974       // Use gdcmParser::dicom_vr to test all the possibilities
1975       // instead of just checking for UL, OB and UI !?
1976       if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
1977           (memcmp(entCur, "OB", (size_t)2) == 0) ||
1978           (memcmp(entCur, "UI", (size_t)2) == 0) )   
1979       {
1980          filetype = ExplicitVR;
1981          dbg.Verbose(1, "gdcmParser::CheckSwap:",
1982                      "explicit Value Representation");
1983       } 
1984       else 
1985       {
1986          filetype = ImplicitVR;
1987          dbg.Verbose(1, "gdcmParser::CheckSwap:",
1988                      "not an explicit Value Representation");
1989       }
1990       if (net2host) 
1991       {
1992          sw = 4321;
1993          dbg.Verbose(1, "gdcmParser::CheckSwap:",
1994                         "HostByteOrder != NetworkByteOrder");
1995       } 
1996       else 
1997       {
1998          sw = 0;
1999          dbg.Verbose(1, "gdcmParser::CheckSwap:",
2000                         "HostByteOrder = NetworkByteOrder");
2001       }
2002       
2003       // Position the file position indicator at first tag (i.e.
2004       // after the file preamble and the "DICM" string).
2005       rewind(fp);
2006       fseek (fp, 132L, SEEK_SET);
2007       return;
2008    } // End of DicomV3
2009
2010    // Alas, this is not a DicomV3 file and whatever happens there is no file
2011    // preamble. We can reset the file position indicator to where the data
2012    // is (i.e. the beginning of the file).
2013    dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2014    rewind(fp);
2015
2016    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2017    // By clean we mean that the length of the first tag is written down.
2018    // If this is the case and since the length of the first group HAS to be
2019    // four (bytes), then determining the proper swap code is straightforward.
2020
2021    entCur = deb + 4;
2022    // We assume the array of char we are considering contains the binary
2023    // representation of a 32 bits integer. Hence the following dirty
2024    // trick :
2025    s = *((guint32 *)(entCur));
2026       
2027    switch (s) {
2028       case 0x00040000 :
2029          sw = 3412;
2030          filetype = ACR;
2031          return;
2032       case 0x04000000 :
2033          sw = 4321;
2034          filetype = ACR;
2035          return;
2036       case 0x00000400 :
2037          sw = 2143;
2038          filetype = ACR;
2039          return;
2040       case 0x00000004 :
2041          sw = 0;
2042          filetype = ACR;
2043          return;
2044       default :
2045          dbg.Verbose(0, "gdcmParser::CheckSwap:",
2046                         "ACR/NEMA unfound swap info (time to raise bets)");
2047    }
2048
2049    // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2050    // It is time for despaired wild guesses. So, let's assume this file
2051    // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
2052    // not present. Then the only info we have is the net2host one.
2053    filetype = Unknown;
2054    if (! net2host )
2055       sw = 0;
2056    else
2057       sw = 4321;
2058    return;
2059 }
2060
2061 /**
2062  * \ingroup gdcmParser
2063  * \brief   
2064  */
2065 void gdcmParser::SwitchSwapToBigEndian(void) 
2066 {
2067    dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2068                   "Switching to BigEndian mode.");
2069    if ( sw == 0    ) 
2070    {
2071       sw = 4321;
2072       return;
2073    }
2074    if ( sw == 4321 ) 
2075    {
2076       sw = 0;
2077       return;
2078    }
2079    if ( sw == 3412 ) 
2080    {
2081       sw = 2143;
2082       return;
2083    }
2084    if ( sw == 2143 )
2085       sw = 3412;
2086 }
2087
2088 /**
2089  * \ingroup gdcmParser
2090  * \brief   
2091  * @param NewSize
2092  * @return 
2093  */
2094 void gdcmParser::SetMaxSizeLoadEntry(long NewSize) 
2095 {
2096    if (NewSize < 0)
2097       return;
2098    if ((guint32)NewSize >= (guint32)0xffffffff) 
2099    {
2100       MaxSizeLoadEntry = 0xffffffff;
2101       return;
2102    }
2103    MaxSizeLoadEntry = NewSize;
2104 }
2105
2106 /**
2107  * \ingroup gdcmParser
2108  * \brief   Searches both the public and the shadow dictionary (when they
2109  *          exist) for the presence of the DictEntry with given name.
2110  *          The public dictionary has precedence on the shadow one.
2111  * @param   Name name of the searched DictEntry
2112  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2113  */
2114 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name) 
2115 {
2116    gdcmDictEntry *found = (gdcmDictEntry *)0;
2117    if (!RefPubDict && !RefShaDict) 
2118    {
2119       dbg.Verbose(0, "gdcmParser::GetDictEntry",
2120                      "we SHOULD have a default dictionary");
2121    }
2122    if (RefPubDict) 
2123    {
2124       found = RefPubDict->GetDictEntryByName(Name);
2125       if (found)
2126          return found;
2127    }
2128    if (RefShaDict) 
2129    {
2130       found = RefShaDict->GetDictEntryByName(Name);
2131       if (found)
2132          return found;
2133    }
2134    return found;
2135 }
2136
2137 /**
2138  * \ingroup gdcmParser
2139  * \brief   Searches both the public and the shadow dictionary (when they
2140  *          exist) for the presence of the DictEntry with given
2141  *          group and element. The public dictionary has precedence on the
2142  *          shadow one.
2143  * @param   group   group of the searched DictEntry
2144  * @param   element element of the searched DictEntry
2145  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2146  */
2147 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element) 
2148 {
2149    gdcmDictEntry *found = (gdcmDictEntry *)0;
2150    if (!RefPubDict && !RefShaDict) 
2151    {
2152       dbg.Verbose(0, "gdcmParser::GetDictEntry",
2153                      "we SHOULD have a default dictionary");
2154    }
2155    if (RefPubDict) 
2156    {
2157       found = RefPubDict->GetDictEntryByNumber(group, element);
2158       if (found)
2159          return found;
2160    }
2161    if (RefShaDict) 
2162    {
2163       found = RefShaDict->GetDictEntryByNumber(group, element);
2164       if (found)
2165          return found;
2166    }
2167    return found;
2168 }
2169
2170 /**
2171  * \ingroup gdcmParser
2172  * \brief   Read the next tag but WITHOUT loading it's value
2173  * @return  On succes the newly created HeaderEntry, NULL on failure.      
2174  */
2175 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2176    guint16 g,n;
2177    gdcmHeaderEntry *NewEntry;
2178    
2179    g = ReadInt16();
2180    n = ReadInt16();
2181       
2182    if (errno == 1)
2183       // We reached the EOF (or an error occured) therefore 
2184       // header parsing has to be considered as finished.
2185       return (gdcmHeaderEntry *)0;
2186
2187 /*  Pb : how to propagate the element length (used in SkipHeaderEntry)
2188 //       direct call to SkipBytes ?
2189    
2190    if (ignoreShadow == 1 && g%2 ==1)  //JPR
2191       // if user wants to skip shadow groups
2192       // and current element *is* a shadow element
2193       // we don't create anything
2194       return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2195 */   
2196    NewEntry = NewHeaderEntryByNumber(g, n);
2197    FindHeaderEntryVR(NewEntry);
2198    FindHeaderEntryLength(NewEntry);
2199         
2200    if (errno == 1) {
2201       // Call it quits
2202       return NULL;
2203    }
2204    NewEntry->SetOffset(ftell(fp));  
2205    //if ( (g==0x7fe0) && (n==0x0010) ) 
2206    return NewEntry;
2207 }
2208
2209 /**
2210  * \ingroup gdcmParser
2211  * \brief   Build a new Element Value from all the low level arguments. 
2212  *          Check for existence of dictionary entry, and build
2213  *          a default one when absent.
2214  * @param   Name    Name of the underlying DictEntry
2215  */
2216 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name) 
2217 {
2218    gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2219    if (!NewTag)
2220       NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2221
2222    gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2223    if (!NewEntry) 
2224    {
2225       dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2226                   "failed to allocate gdcmHeaderEntry");
2227       return (gdcmHeaderEntry *)0;
2228    }
2229    return NewEntry;
2230 }  
2231
2232 /**
2233  * \ingroup gdcmParser
2234  * \brief   Request a new virtual dict entry to the dict set
2235  * @param   group  group   of the underlying DictEntry
2236  * @param   elem   element of the underlying DictEntry
2237  * @param   vr     VR of the underlying DictEntry
2238  * @param   fourth owner group
2239  * @param   name   english name
2240  */
2241 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2242                                                std::string vr,
2243                                                std::string fourth,
2244                                                std::string name)
2245 {
2246    return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2247 }
2248
2249 /**
2250  * \ingroup gdcmParser
2251  * \brief   Build a new Element Value from all the low level arguments. 
2252  *          Check for existence of dictionary entry, and build
2253  *          a default one when absent.
2254  * @param   Group group   of the underlying DictEntry
2255  * @param   Elem  element of the underlying DictEntry
2256  */
2257 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem) 
2258 {
2259    // Find out if the tag we encountered is in the dictionaries:
2260    gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2261    if (!DictEntry)
2262       DictEntry = NewVirtualDictEntry(Group, Elem);
2263
2264    gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2265    if (!NewEntry) 
2266    {
2267       dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2268                   "failed to allocate gdcmHeaderEntry");
2269       return NULL;
2270    }
2271    return NewEntry;
2272 }
2273
2274 /**
2275  * \ingroup gdcmParser
2276  * \brief   Small utility function that creates a new manually crafted
2277  *          (as opposed as read from the file) gdcmHeaderEntry with user
2278  *          specified name and adds it to the public tag hash table.
2279  * \note    A fake TagKey is generated so the PubDict can keep it's coherence.
2280  * @param   NewTagName The name to be given to this new tag.
2281  * @param   VR The Value Representation to be given to this new tag.
2282  * @return  The newly hand crafted Element Value.
2283  */
2284 gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName, 
2285                                                            std::string VR) 
2286 {
2287    gdcmHeaderEntry *NewEntry = NULL;
2288    guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
2289    guint32 FreeElem = 0;
2290    gdcmDictEntry *DictEntry = NULL;
2291
2292    FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2293    if (FreeElem == UINT32_MAX) 
2294    {
2295       dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2296                      "Group 0xffff in Public Dict is full");
2297       return NULL;
2298    }
2299
2300    DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2301                                 VR, "GDCM", NewTagName);
2302    NewEntry = new gdcmHeaderEntry(DictEntry);
2303    AddHeaderEntry(NewEntry);
2304    return NewEntry;
2305 }
2306
2307 /**
2308  * \ingroup gdcmParser
2309  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2310  *          in the TagHt dictionary.
2311  * @param   group The generated tag must belong to this group.  
2312  * @return  The element of tag with given group which is fee.
2313  */
2314 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group) 
2315 {
2316    for (guint32 elem = 0; elem < UINT32_MAX; elem++) 
2317    {
2318       TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2319       if (tagHT.count(key) == 0)
2320          return elem;
2321    }
2322    return UINT32_MAX;
2323 }
2324
2325 //-----------------------------------------------------------------------------