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