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