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