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