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