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