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