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