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