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