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