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