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