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