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