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