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