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