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