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