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