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