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