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