]> 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                 
1446    gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1447    gdcmSQItem *itemSQ;
1448    bool dlm_mod;
1449    int lgr, l, lgth;
1450    int depth = set->GetDepthLevel();
1451    while (true) {
1452       
1453       NewDocEntry = ReadNextDocEntry();   
1454       if(delim_mode) {   
1455           if (NewDocEntry->isSequenceDelimitor()) {
1456           //add the Sequence Delimitor  // TODO : find the trick to put it properly !
1457              set->SetSequenceDelimitationItem(NewDocEntry);
1458              break;
1459           }          
1460       }      
1461       if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1462              break;
1463       }
1464       itemSQ = new gdcmSQItem(set->GetDepthLevel());
1465       itemSQ->AddEntry(NewDocEntry); // no value, no voidArea. Think of it while printing !
1466       l= NewDocEntry->GetReadLength();
1467       
1468       if (l ==0xffffffff)
1469          dlm_mod = true;
1470       else
1471          dlm_mod=false;
1472    
1473       lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1474       
1475       set->AddEntry(itemSQ,SQItemNumber);        
1476       SQItemNumber ++;
1477       if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1478          break;
1479       }       
1480    }
1481    lgth = ftell(fp) - offset;
1482    return(lgth);
1483 }
1484
1485 /**
1486  * \brief         Loads the element content if its length doesn't exceed
1487  *                the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1488  * @param         Entry Header Entry (Dicom Element) to be dealt with
1489  */
1490 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)  {
1491    size_t item_read;
1492    guint16 group  = Entry->GetGroup();
1493    std::string  vr= Entry->GetVR();
1494    guint32 length = Entry->GetLength();
1495
1496    fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1497
1498    // A SeQuence "contains" a set of Elements.  
1499    //          (fffe e000) tells us an Element is beginning
1500    //          (fffe e00d) tells us an Element just ended
1501    //          (fffe e0dd) tells us the current SeQuence just ended
1502    if( group == 0xfffe ) {
1503       // NO more value field for SQ !
1504       //Entry->SetValue("gdcm::Skipped");
1505       // appel recursif de Load Value
1506       // (meme pb que pour le parsing)
1507       return;
1508    }
1509
1510    // When the length is zero things are easy:
1511    if ( length == 0 ) {
1512       ((gdcmValEntry *)Entry)->SetValue("");
1513       return;
1514    }
1515
1516    // The elements whose length is bigger than the specified upper bound
1517    // are not loaded. Instead we leave a short notice of the offset of
1518    // the element content and it's length.
1519    if (length > MaxSizeLoadEntry) {
1520       if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1521       {
1522          std::ostringstream s;
1523          s << "gdcm::NotLoaded.";
1524          s << " Address:" << (long)Entry->GetOffset();
1525          s << " Length:"  << Entry->GetLength();
1526          s << " x(" << std::hex << Entry->GetLength() << ")";
1527          ValEntryPtr->SetValue(s.str());
1528       }
1529       // to be sure we are at the end of the value ...
1530       fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1531       
1532       return;
1533    }
1534     
1535    // Any compacter code suggested (?)
1536    if ( IsDocEntryAnInteger(Entry) ) {   
1537       guint32 NewInt;
1538       std::ostringstream s;
1539       int nbInt;
1540    // When short integer(s) are expected, read and convert the following 
1541    // n *two characters properly i.e. as short integers as opposed to strings.
1542    // Elements with Value Multiplicity > 1
1543    // contain a set of integers (not a single one)       
1544       if (vr == "US" || vr == "SS") {
1545          nbInt = length / 2;
1546          NewInt = ReadInt16();
1547          s << NewInt;
1548          if (nbInt > 1){
1549             for (int i=1; i < nbInt; i++) {
1550                s << '\\';
1551                NewInt = ReadInt16();
1552                s << NewInt;
1553             }
1554          }
1555       }
1556    // When integer(s) are expected, read and convert the following 
1557    // n * four characters properly i.e. as integers as opposed to strings.
1558    // Elements with Value Multiplicity > 1
1559    // contain a set of integers (not a single one)           
1560       else if (vr == "UL" || vr == "SL") {
1561          nbInt = length / 4;
1562          NewInt = ReadInt32();
1563          s << NewInt;
1564          if (nbInt > 1) {
1565             for (int i=1; i < nbInt; i++) {
1566                s << '\\';
1567                NewInt = ReadInt32();
1568                s << NewInt;
1569             }
1570          }
1571       }
1572 #ifdef GDCM_NO_ANSI_STRING_STREAM
1573       s << std::ends; // to avoid oddities on Solaris
1574 #endif //GDCM_NO_ANSI_STRING_STREAM
1575
1576       ((gdcmValEntry *)Entry)->SetValue(s.str());
1577       return;
1578    }
1579    
1580    // We need an additional byte for storing \0 that is not on disk
1581    std::string NewValue(length,0);
1582    item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1583    if ( item_read != 1 ) {
1584       dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1585       ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1586       return;
1587    }
1588
1589    if( (vr == "UI") ) // Because of correspondance with the VR dic
1590       ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1591    else
1592       ((gdcmValEntry *)Entry)->SetValue(NewValue);
1593 }
1594
1595
1596 /**
1597  * \brief  Find the value Length of the passed Header Entry
1598  * @param  Entry Header Entry whose length of the value shall be loaded. 
1599  */
1600  void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1601    guint16 element = Entry->GetElement();
1602    //guint16 group   = Entry->GetGroup(); //FIXME
1603    std::string  vr = Entry->GetVR();
1604    guint16 length16;
1605        
1606    
1607    if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) ) 
1608    {
1609       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) 
1610       {
1611          // The following reserved two bytes (see PS 3.5-2001, section
1612          // 7.1.2 Data element structure with explicit vr p27) must be
1613          // skipped before proceeding on reading the length on 4 bytes.
1614          fseek(fp, 2L, SEEK_CUR);
1615          guint32 length32 = ReadInt32();
1616
1617          if ( (vr == "OB") && (length32 == 0xffffffff) ) 
1618          {
1619             Entry->SetLength(FindDocEntryLengthOB());
1620             return;
1621          }
1622          FixDocEntryFoundLength(Entry, length32); 
1623          return;
1624       }
1625
1626       // Length is encoded on 2 bytes.
1627       length16 = ReadInt16();
1628       
1629       // We can tell the current file is encoded in big endian (like
1630       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1631       // and it's value is the one of the encoding of a big endian file.
1632       // In order to deal with such big endian encoded files, we have
1633       // (at least) two strategies:
1634       // * when we load the "Transfer Syntax" tag with value of big endian
1635       //   encoding, we raise the proper flags. Then we wait for the end
1636       //   of the META group (0x0002) among which is "Transfer Syntax",
1637       //   before switching the swap code to big endian. We have to postpone
1638       //   the switching of the swap code since the META group is fully encoded
1639       //   in little endian, and big endian coding only starts at the next
1640       //   group. The corresponding code can be hard to analyse and adds
1641       //   many additional unnecessary tests for regular tags.
1642       // * the second strategy consists in waiting for trouble, that shall
1643       //   appear when we find the first group with big endian encoding. This
1644       //   is easy to detect since the length of a "Group Length" tag (the
1645       //   ones with zero as element number) has to be of 4 (0x0004). When we
1646       //   encounter 1024 (0x0400) chances are the encoding changed and we
1647       //   found a group with big endian encoding.
1648       // We shall use this second strategy. In order to make sure that we
1649       // can interpret the presence of an apparently big endian encoded
1650       // length of a "Group Length" without committing a big mistake, we
1651       // add an additional check: we look in the already parsed elements
1652       // for the presence of a "Transfer Syntax" whose value has to be "big
1653       // endian encoding". When this is the case, chances are we have got our
1654       // hands on a big endian encoded file: we switch the swap code to
1655       // big endian and proceed...
1656       if ( (element  == 0x0000) && (length16 == 0x0400) ) 
1657       {
1658          if ( ! IsExplicitVRBigEndianTransferSyntax() ) 
1659          {
1660             dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1661             errno = 1;
1662             return;
1663          }
1664          length16 = 4;
1665          SwitchSwapToBigEndian();
1666          // Restore the unproperly loaded values i.e. the group, the element
1667          // and the dictionary entry depending on them.
1668          guint16 CorrectGroup   = SwapShort(Entry->GetGroup());
1669          guint16 CorrectElem    = SwapShort(Entry->GetElement());
1670          gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1671                                                        CorrectElem);
1672          if (!NewTag) 
1673          {
1674             // This correct tag is not in the dictionary. Create a new one.
1675             NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1676          }
1677          // FIXME this can create a memory leaks on the old entry that be
1678          // left unreferenced.
1679          Entry->SetDictEntry(NewTag);
1680       }
1681        
1682       // Heuristic: well some files are really ill-formed.
1683       if ( length16 == 0xffff) 
1684       {
1685          length16 = 0;
1686          //dbg.Verbose(0, "gdcmDocument::FindLength",
1687          //            "Erroneous element length fixed.");
1688          // Actually, length= 0xffff means that we deal with
1689          // Unknown Sequence Length 
1690       }
1691       FixDocEntryFoundLength(Entry, (guint32)length16);
1692       return;
1693    }
1694    else
1695    {
1696       // Either implicit VR or a non DICOM conformal (see note below) explicit
1697       // VR that ommited the VR of (at least) this element. Farts happen.
1698       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1699       // on Data elements "Implicit and Explicit VR Data Elements shall
1700       // not coexist in a Data Set and Data Sets nested within it".]
1701       // Length is on 4 bytes.
1702       
1703       FixDocEntryFoundLength(Entry, ReadInt32());
1704       return;
1705    }
1706 }
1707
1708 /**
1709  * \brief     Find the Value Representation of the current Dicom Element.
1710  * @param     Entry
1711  */
1712 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry) 
1713 {
1714    if (filetype != gdcmExplicitVR)
1715       return;
1716
1717    char VR[3];
1718
1719    long PositionOnEntry = ftell(fp);
1720    // Warning: we believe this is explicit VR (Value Representation) because
1721    // we used a heuristic that found "UL" in the first tag. Alas this
1722    // doesn't guarantee that all the tags will be in explicit VR. In some
1723    // cases (see e-film filtered files) one finds implicit VR tags mixed
1724    // within an explicit VR file. Hence we make sure the present tag
1725    // is in explicit VR and try to fix things if it happens not to be
1726    // the case.
1727    
1728    (void)fread (&VR, (size_t)2,(size_t)1, fp);
1729    VR[2]=0;
1730    if(!CheckDocEntryVR(Entry,VR))
1731    {
1732       fseek(fp, PositionOnEntry, SEEK_SET);
1733       // When this element is known in the dictionary we shall use, e.g. for
1734       // the semantics (see the usage of IsAnInteger), the VR proposed by the
1735       // dictionary entry. Still we have to flag the element as implicit since
1736       // we know now our assumption on expliciteness is not furfilled.
1737       // avoid  .
1738       if ( Entry->IsVRUnknown() )
1739          Entry->SetVR("Implicit");
1740       Entry->SetImplicitVR();
1741    }
1742 }
1743
1744 /**
1745  * \brief     Check the correspondance between the VR of the header entry
1746  *            and the taken VR. If they are different, the header entry is 
1747  *            updated with the new VR.
1748  * @param     Entry Header Entry to check
1749  * @param     vr    Dicom Value Representation
1750  * @return    false if the VR is incorrect of if the VR isn't referenced
1751  *            otherwise, it returns true
1752 */
1753 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1754 {
1755    char msg[100]; // for sprintf
1756    bool RealExplicit = true;
1757
1758    // Assume we are reading a falsely explicit VR file i.e. we reached
1759    // a tag where we expect reading a VR but are in fact we read the
1760    // first to bytes of the length. Then we will interogate (through find)
1761    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1762    // both GCC and VC++ implementations of the STL map. Hence when the
1763    // expected VR read happens to be non-ascii characters we consider
1764    // we hit falsely explicit VR tag.
1765
1766    if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1767       RealExplicit = false;
1768
1769    // CLEANME searching the dicom_vr at each occurence is expensive.
1770    // PostPone this test in an optional integrity check at the end
1771    // of parsing or only in debug mode.
1772    if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1773       RealExplicit= false;
1774
1775    if ( !RealExplicit ) 
1776    {
1777       // We thought this was explicit VR, but we end up with an
1778       // implicit VR tag. Let's backtrack.   
1779       sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", 
1780                    Entry->GetGroup(),Entry->GetElement());
1781       dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1782       if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1783          gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1784                                    Entry->GetGroup(),Entry->GetElement(),
1785                                    "UL","FIXME","Group Length");
1786          Entry->SetDictEntry(NewEntry);     
1787       }
1788       return(false);
1789    }
1790
1791    if ( Entry->IsVRUnknown() ) 
1792    {
1793       // When not a dictionary entry, we can safely overwrite the VR.
1794       if (Entry->GetElement() == 0x0000) { // Group length is UL !
1795          Entry->SetVR("UL");
1796       } else {
1797          Entry->SetVR(vr);
1798       }
1799    }
1800    else if ( Entry->GetVR() != vr ) 
1801    {
1802       // The VR present in the file and the dictionary disagree. We assume
1803       // the file writer knew best and use the VR of the file. Since it would
1804       // be unwise to overwrite the VR of a dictionary (since it would
1805       // compromise it's next user), we need to clone the actual DictEntry
1806       // and change the VR for the read one.
1807       gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1808                                  Entry->GetGroup(),Entry->GetElement(),
1809                                  vr,"FIXME",Entry->GetName());
1810       Entry->SetDictEntry(NewEntry);
1811    }
1812    return(true); 
1813 }
1814
1815 /**
1816  * \brief   Get the transformed value of the header entry. The VR value 
1817  *          is used to define the transformation to operate on the value
1818  * \warning NOT end user intended method !
1819  * @param   Entry 
1820  * @return  Transformed entry value
1821  */
1822 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1823 {
1824    if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1825    {
1826       std::string val=((gdcmValEntry *)Entry)->GetValue();
1827       std::string vr=Entry->GetVR();
1828       guint32 length = Entry->GetLength();
1829       std::ostringstream s;
1830       int nbInt;
1831
1832    // When short integer(s) are expected, read and convert the following 
1833    // n * 2 bytes properly i.e. as a multivaluated strings
1834    // (each single value is separated fromthe next one by '\'
1835    // as usual for standard multivaluated filels
1836    // Elements with Value Multiplicity > 1
1837    // contain a set of short integers (not a single one) 
1838    
1839       if (vr == "US" || vr == "SS")
1840       {
1841          guint16 NewInt16;
1842
1843          nbInt = length / 2;
1844          for (int i=0; i < nbInt; i++) 
1845          {
1846             if(i!=0)
1847                s << '\\';
1848             NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1849             NewInt16 = SwapShort(NewInt16);
1850             s << NewInt16;
1851          }
1852       }
1853
1854    // When integer(s) are expected, read and convert the following 
1855    // n * 4 bytes properly i.e. as a multivaluated strings
1856    // (each single value is separated fromthe next one by '\'
1857    // as usual for standard multivaluated filels
1858    // Elements with Value Multiplicity > 1
1859    // contain a set of integers (not a single one) 
1860       else if (vr == "UL" || vr == "SL")
1861       {
1862          guint32 NewInt32;
1863
1864          nbInt = length / 4;
1865          for (int i=0; i < nbInt; i++) 
1866          {
1867             if(i!=0)
1868                s << '\\';
1869             NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1870                      ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1871             NewInt32=SwapLong(NewInt32);
1872             s << NewInt32;
1873          }
1874       }
1875 #ifdef GDCM_NO_ANSI_STRING_STREAM
1876       s << std::ends; // to avoid oddities on Solaris
1877 #endif //GDCM_NO_ANSI_STRING_STREAM
1878       return(s.str());
1879    }
1880
1881    return(((gdcmValEntry *)Entry)->GetValue());
1882 }
1883
1884 /**
1885  * \brief   Get the reverse transformed value of the header entry. The VR 
1886  *          value is used to define the reverse transformation to operate on
1887  *          the value
1888  * \warning NOT end user intended method !
1889  * @param   Entry 
1890  * @return  Reverse transformed entry value
1891  */
1892 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1893 {
1894    if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1895    {
1896       std::string vr=Entry->GetVR();
1897       std::ostringstream s;
1898       std::vector<std::string> tokens;
1899
1900       if (vr == "US" || vr == "SS") 
1901       {
1902          guint16 NewInt16;
1903
1904          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1905          Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1906          for (unsigned int i=0; i<tokens.size();i++) 
1907          {
1908             NewInt16 = atoi(tokens[i].c_str());
1909             s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1910          }
1911          tokens.clear();
1912       }
1913       if (vr == "UL" || vr == "SL") 
1914       {
1915          guint32 NewInt32;
1916
1917          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1918          Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1919          for (unsigned int i=0; i<tokens.size();i++) 
1920          {
1921             NewInt32 = atoi(tokens[i].c_str());
1922             s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1923                <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1924          }
1925          tokens.clear();
1926       }
1927
1928 #ifdef GDCM_NO_ANSI_STRING_STREAM
1929       s << std::ends; // to avoid oddities on Solaris
1930 #endif //GDCM_NO_ANSI_STRING_STREAM
1931       return(s.str());
1932    }
1933
1934    return(((gdcmValEntry *)Entry)->GetValue());
1935 }
1936
1937 /**
1938  * \brief   Skip a given Header Entry 
1939  * \warning NOT end user intended method !
1940  * @param   entry 
1941  */
1942 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry) 
1943 {
1944    SkipBytes(entry->GetLength());
1945 }
1946
1947 /**
1948  * \brief   Skips to the begining of the next Header Entry 
1949  * \warning NOT end user intended method !
1950  * @param   entry 
1951  */
1952 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry) 
1953 {
1954    (void)fseek(fp, (long)(entry->GetOffset()),     SEEK_SET);
1955    (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1956 }
1957
1958 /**
1959  * \brief   Loads the value for a a given VLEntry 
1960  * \warning NOT end user intended method !
1961  * @param   entry 
1962  */
1963 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry) 
1964 {
1965     //SkipBytes(entry->GetLength());
1966     LoadDocEntry(entry);
1967 }
1968 /**
1969  * \brief   When the length of an element value is obviously wrong (because
1970  *          the parser went Jabberwocky) one can hope improving things by
1971  *          applying this heuristic.
1972  */
1973 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry, guint32 FoundLength) 
1974 {
1975    Entry->SetReadLength(FoundLength); // will be updated only if a bug is found        
1976    if ( FoundLength == 0xffffffff) {
1977       FoundLength = 0;
1978    }
1979    
1980    guint16 gr =Entry->GetGroup();
1981    guint16 el =Entry->GetElement(); 
1982      
1983    if (FoundLength%2) {
1984       std::ostringstream s;
1985       s << "Warning : Tag with uneven length " << FoundLength 
1986          <<  " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1987       dbg.Verbose(0,s.str().c_str());
1988    }
1989       
1990    // Sorry for the patch!  
1991    // XMedCom did the trick to read some naughty GE images ...
1992    if (FoundLength == 13) {
1993       // The following 'if' will be removed when there is no more
1994       // images on Creatis HDs with a 13 length for Manufacturer...
1995       if ( (Entry->GetGroup() != 0x0008) ||  
1996            ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1997       // end of remove area
1998          FoundLength =10;
1999          Entry->SetReadLength(10); // a bug is to be fixed
2000       }
2001    }
2002
2003    // to fix some garbage 'Leonardo' Siemens images
2004    // May be commented out to avoid overhead
2005    else if ( (Entry->GetGroup() == 0x0009) &&
2006        ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
2007       FoundLength =4;
2008       Entry->SetReadLength(4); // a bug is to be fixed 
2009    } 
2010    // end of fix
2011  
2012    // to try to 'go inside' SeQuences (with length), and not to skip them        
2013    else if ( Entry->GetVR() == "SQ") 
2014    { 
2015       if (enableSequences)    // only if the user does want to !
2016          FoundLength =0;      // ReadLength is unchanged 
2017    } 
2018     
2019    // we found a 'delimiter' element                                         
2020    // fffe|xxxx is just a marker, we don't take its length into account                                                   
2021    else if(Entry->GetGroup() == 0xfffe)
2022    {    
2023                                          // *normally, fffe|0000 doesn't exist ! 
2024      if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
2025                                          // causes extra troubles :-(                                                                   
2026         FoundLength =0;
2027    } 
2028            
2029    Entry->SetUsableLength(FoundLength);
2030 }
2031
2032 /**
2033  * \brief   Apply some heuristics to predict whether the considered 
2034  *          element value contains/represents an integer or not.
2035  * @param   Entry The element value on which to apply the predicate.
2036  * @return  The result of the heuristical predicate.
2037  */
2038 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2039    guint16 element = Entry->GetElement();
2040    guint16 group   = Entry->GetGroup();
2041    std::string  vr = Entry->GetVR();
2042    guint32 length  = Entry->GetLength();
2043    // When we have some semantics on the element we just read, and if we
2044    // a priori know we are dealing with an integer, then we shall be
2045    // able to swap it's element value properly.
2046    if ( element == 0 )  // This is the group length of the group
2047    {  
2048       if (length == 4)
2049          return true;
2050       else 
2051       {
2052          std::ostringstream s;
2053          int filePosition = ftell(fp);
2054          s << "Erroneous Group Length element length  on : (" \
2055            << std::hex << group << " , " << element 
2056            << ") -before- position x(" << filePosition << ")"
2057            << "lgt : " << length;
2058          // These 2 lines commented out : a *very dirty* patch
2059          // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
2060          // have a glance at offset  x(8336) ...
2061          // For *regular* headers, the test is useless..
2062          // lets's print a warning message and go on, 
2063          // instead of giving up with an error message
2064
2065          //std::cout << s.str().c_str() << std::endl;
2066          // dbg.Error("gdcmDocument::IsDocEntryAnInteger",
2067          //           s.str().c_str());     
2068       }
2069    }
2070    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2071       return true;
2072    
2073    return false;
2074 }
2075 /**
2076  * \brief  Find the Length till the next sequence delimiter
2077  * \warning NOT end user intended method !
2078  * @return 
2079  */
2080
2081  guint32 gdcmDocument::FindDocEntryLengthOB(void)  {
2082    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2083    guint16 g;
2084    guint16 n; 
2085    long PositionOnEntry = ftell(fp);
2086    bool FoundSequenceDelimiter = false;
2087    guint32 TotalLength = 0;
2088    guint32 ItemLength;
2089
2090    while ( ! FoundSequenceDelimiter) 
2091    {
2092       g = ReadInt16();
2093       n = ReadInt16();   
2094       if (errno == 1)
2095          return 0;
2096       TotalLength += 4;  // We even have to decount the group and element 
2097      
2098       if ( g != 0xfffe && g!=0xb00c ) //for bogus header  
2099       {
2100          char msg[100]; // for sprintf. Sorry
2101          sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2102          dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg); 
2103          errno = 1;
2104          return 0;
2105       }
2106       if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header 
2107          FoundSequenceDelimiter = true;
2108       else if ( n != 0xe000 )
2109       {
2110          char msg[100];  // for sprintf. Sorry
2111          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2112                       n, g,n);
2113          dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2114          errno = 1;
2115          return 0;
2116       }
2117       ItemLength = ReadInt32();
2118       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
2119                                       // the ItemLength with ReadInt32                                     
2120       SkipBytes(ItemLength);
2121    }
2122    fseek(fp, PositionOnEntry, SEEK_SET);
2123    return TotalLength;
2124 }
2125
2126 /**
2127  * \brief Reads a supposed to be 16 Bits integer
2128  *       (swaps it depending on processor endianity) 
2129  * @return read value
2130  */
2131 guint16 gdcmDocument::ReadInt16(void) {
2132    guint16 g;
2133    size_t item_read;
2134    item_read = fread (&g, (size_t)2,(size_t)1, fp);
2135    if ( item_read != 1 ) {
2136       if(ferror(fp)) 
2137          dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2138       errno = 1;
2139       return 0;
2140    }
2141    errno = 0;
2142    g = SwapShort(g);   
2143    return g;
2144 }
2145
2146 /**
2147  * \brief  Reads a supposed to be 32 Bits integer
2148  *         (swaps it depending on processor endianity)  
2149  * @return read value
2150  */
2151 guint32 gdcmDocument::ReadInt32(void) {
2152    guint32 g;
2153    size_t item_read;
2154    item_read = fread (&g, (size_t)4,(size_t)1, fp);
2155    if ( item_read != 1 ) { 
2156      if(ferror(fp)) 
2157          dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");   
2158       errno = 1;
2159       return 0;
2160    }
2161    errno = 0;   
2162    g = SwapLong(g);
2163    return g;
2164 }
2165
2166 /**
2167  * \brief skips bytes inside the source file 
2168  * \warning NOT end user intended method !
2169  * @return 
2170  */
2171 void gdcmDocument::SkipBytes(guint32 NBytes) {
2172    //FIXME don't dump the returned value
2173    (void)fseek(fp, (long)NBytes, SEEK_CUR);
2174 }
2175
2176 /**
2177  * \brief Loads all the needed Dictionaries
2178  * \warning NOT end user intended method !   
2179  */
2180 void gdcmDocument::Initialise(void) 
2181 {
2182    RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2183    RefShaDict = (gdcmDict*)0;
2184 }
2185
2186 /**
2187  * \brief   Discover what the swap code is (among little endian, big endian,
2188  *          bad little endian, bad big endian).
2189  *          sw is set
2190  * @return false when we are absolutely sure 
2191  *               it's neither ACR-NEMA nor DICOM
2192  *         true  when we hope ours assuptions are OK
2193  */
2194 bool gdcmDocument::CheckSwap() {
2195
2196    // The only guaranted way of finding the swap code is to find a
2197    // group tag since we know it's length has to be of four bytes i.e.
2198    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2199    // occurs when we can't find such group...
2200    
2201    guint32  x=4;  // x : for ntohs
2202    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2203    guint32  s32;
2204    guint16  s16;
2205        
2206    int lgrLue;
2207    char *entCur;
2208    char deb[HEADER_LENGTH_TO_READ];
2209     
2210    // First, compare HostByteOrder and NetworkByteOrder in order to
2211    // determine if we shall need to swap bytes (i.e. the Endian type).
2212    if (x==ntohs(x))
2213       net2host = true;
2214    else
2215       net2host = false; 
2216          
2217    // The easiest case is the one of a DICOM header, since it possesses a
2218    // file preamble where it suffice to look for the string "DICM".
2219    lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2220    
2221    entCur = deb + 128;
2222    if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2223       dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2224       
2225       // Next, determine the value representation (VR). Let's skip to the
2226       // first element (0002, 0000) and check there if we find "UL" 
2227       // - or "OB" if the 1st one is (0002,0001) -,
2228       // in which case we (almost) know it is explicit VR.
2229       // WARNING: if it happens to be implicit VR then what we will read
2230       // is the length of the group. If this ascii representation of this
2231       // length happens to be "UL" then we shall believe it is explicit VR.
2232       // FIXME: in order to fix the above warning, we could read the next
2233       // element value (or a couple of elements values) in order to make
2234       // sure we are not commiting a big mistake.
2235       // We need to skip :
2236       // * the 128 bytes of File Preamble (often padded with zeroes),
2237       // * the 4 bytes of "DICM" string,
2238       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2239       // i.e. a total of  136 bytes.
2240       entCur = deb + 136;
2241      
2242       // FIXME : FIXME:
2243       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2244       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2245       // *Implicit* VR.  -and it is !- 
2246       
2247       if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2248           (memcmp(entCur, "OB", (size_t)2) == 0) ||
2249           (memcmp(entCur, "UI", (size_t)2) == 0) ||
2250           (memcmp(entCur, "CS", (size_t)2) == 0) )  // CS, to remove later
2251                                                     // when Write DCM *adds*
2252       // FIXME
2253       // Use gdcmDocument::dicom_vr to test all the possibilities
2254       // instead of just checking for UL, OB and UI !? group 0000 
2255       {
2256          filetype = gdcmExplicitVR;
2257          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2258                      "explicit Value Representation");
2259       } 
2260       else 
2261       {
2262          filetype = gdcmImplicitVR;
2263          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2264                      "not an explicit Value Representation");
2265       }
2266       
2267       if (net2host) 
2268       {
2269          sw = 4321;
2270          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2271                         "HostByteOrder != NetworkByteOrder");
2272       } 
2273       else 
2274       {
2275          sw = 0;
2276          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2277                         "HostByteOrder = NetworkByteOrder");
2278       }
2279       
2280       // Position the file position indicator at first tag (i.e.
2281       // after the file preamble and the "DICM" string).
2282       rewind(fp);
2283       fseek (fp, 132L, SEEK_SET);
2284       return true;
2285    } // End of DicomV3
2286
2287    // Alas, this is not a DicomV3 file and whatever happens there is no file
2288    // preamble. We can reset the file position indicator to where the data
2289    // is (i.e. the beginning of the file).
2290    dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2291    rewind(fp);
2292
2293    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2294    // By clean we mean that the length of the first tag is written down.
2295    // If this is the case and since the length of the first group HAS to be
2296    // four (bytes), then determining the proper swap code is straightforward.
2297
2298    entCur = deb + 4;
2299    // We assume the array of char we are considering contains the binary
2300    // representation of a 32 bits integer. Hence the following dirty
2301    // trick :
2302    s32 = *((guint32 *)(entCur));
2303       
2304    switch (s32) {
2305       case 0x00040000 :
2306          sw = 3412;
2307          filetype = gdcmACR;
2308          return true;
2309       case 0x04000000 :
2310          sw = 4321;
2311          filetype = gdcmACR;
2312          return true;
2313       case 0x00000400 :
2314          sw = 2143;
2315          filetype = gdcmACR;
2316          return true;
2317       case 0x00000004 :
2318          sw = 0;
2319          filetype = gdcmACR;
2320          return true;
2321       default :
2322
2323       // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2324       // It is time for despaired wild guesses. 
2325       // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2326       //  i.e. the 'group length' element is not present :     
2327       
2328       //  check the supposed to be 'group number'
2329       //  0x0002 or 0x0004 or 0x0008
2330       //  to determine ' sw' value .
2331       //  Only 0 or 4321 will be possible 
2332       //  (no oportunity to check for the formerly well known
2333       //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2334       //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-) 
2335       //  the file IS NOT ACR-NEMA nor DICOM V3
2336       //  Find a trick to tell it the caller...
2337       
2338       s16 = *((guint16 *)(deb));
2339       
2340       switch (s16) {
2341       case 0x0002 :
2342       case 0x0004 :
2343       case 0x0008 :      
2344          sw = 0;
2345          filetype = gdcmACR;
2346          return true;
2347       case 0x0200 :
2348       case 0x0400 :
2349       case 0x0800 : 
2350          sw = 4321;
2351          filetype = gdcmACR;
2352          return true;
2353       default :
2354          dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2355                      "ACR/NEMA unfound swap info (Really hopeless !)"); 
2356          filetype = gdcmUnknown;     
2357          return false;
2358       }
2359       
2360       // Then the only info we have is the net2host one.
2361       //if (! net2host )
2362          //   sw = 0;
2363          //else
2364          //  sw = 4321;
2365          //return;
2366    }
2367 }
2368
2369 /**
2370  * \brief Restore the unproperly loaded values i.e. the group, the element
2371  *        and the dictionary entry depending on them. 
2372  */
2373 void gdcmDocument::SwitchSwapToBigEndian(void) 
2374 {
2375    dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2376                   "Switching to BigEndian mode.");
2377    if ( sw == 0    ) 
2378    {
2379       sw = 4321;
2380       return;
2381    }
2382    if ( sw == 4321 ) 
2383    {
2384       sw = 0;
2385       return;
2386    }
2387    if ( sw == 3412 ) 
2388    {
2389       sw = 2143;
2390       return;
2391    }
2392    if ( sw == 2143 )
2393       sw = 3412;
2394 }
2395
2396 /**
2397  * \brief  during parsing, Header Elements too long are not loaded in memory 
2398  * @param NewSize
2399  */
2400 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize) 
2401 {
2402    if (NewSize < 0)
2403       return;
2404    if ((guint32)NewSize >= (guint32)0xffffffff) 
2405    {
2406       MaxSizeLoadEntry = 0xffffffff;
2407       return;
2408    }
2409    MaxSizeLoadEntry = NewSize;
2410 }
2411
2412
2413 /**
2414  * \brief Header Elements too long will not be printed
2415  * \todo  See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE 
2416  * @param NewSize
2417  */
2418 void gdcmDocument::SetMaxSizePrintEntry(long NewSize) 
2419 {
2420    if (NewSize < 0)
2421       return;
2422    if ((guint32)NewSize >= (guint32)0xffffffff) 
2423    {
2424       MaxSizePrintEntry = 0xffffffff;
2425       return;
2426    }
2427    MaxSizePrintEntry = NewSize;
2428 }
2429
2430
2431
2432 /**
2433  * \brief   Read the next tag but WITHOUT loading it's value
2434  *          (read the 'Group Number', the 'Element Number',
2435  *           gets the Dict Entry
2436  *          gets the VR, gets the length, gets the offset value)
2437  * @return  On succes the newly created DocEntry, NULL on failure.      
2438  */
2439 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2440    guint16 g,n;
2441    gdcmDocEntry *NewEntry;
2442    g = ReadInt16();
2443    n = ReadInt16();
2444       
2445    if (errno == 1)
2446       // We reached the EOF (or an error occured) therefore 
2447       // header parsing has to be considered as finished.
2448       return (gdcmDocEntry *)0;
2449
2450 // Pb : how to propagate the element length (used in SkipDocEntry)
2451 //       direct call to SkipBytes ?
2452    
2453 //   if (ignoreShadow == 1 && g%2 ==1)
2454       // if user wants to skip shadow groups
2455       // and current element *is* a shadow element
2456       // we don't create anything
2457 //      return (gdcmDocEntry *)1; // to tell caller it's NOT finished
2458   
2459    NewEntry = NewDocEntryByNumber(g, n);
2460    FindDocEntryVR(NewEntry);
2461    FindDocEntryLength(NewEntry);
2462
2463    if (errno == 1) {
2464       // Call it quits
2465       delete NewEntry;
2466       return NULL;
2467    }
2468    NewEntry->SetOffset(ftell(fp));  
2469    return NewEntry;
2470 }
2471
2472 /**
2473  * \brief   Build a new Element Value from all the low level arguments. 
2474  *          Check for existence of dictionary entry, and build
2475  *          a default one when absent.
2476  * @param   Name    Name of the underlying DictEntry
2477  */
2478 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name) 
2479 {
2480    gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2481    if (!NewTag)
2482       NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2483
2484    gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2485    if (!NewEntry) 
2486    {
2487       dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2488                   "failed to allocate gdcmDocEntry");
2489       return (gdcmDocEntry *)0;
2490    }
2491    return NewEntry;
2492 }  
2493
2494 /**
2495  * \brief   Request a new virtual dict entry to the dict set
2496  * @param   group     group  number of the underlying DictEntry
2497  * @param   element  element number of the underlying DictEntry
2498  * @param   vr     VR of the underlying DictEntry
2499  * @param   fourth owner group
2500  * @param   name   english name
2501  */
2502 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2503                                                std::string vr,
2504                                                std::string fourth,
2505                                                std::string name)
2506 {
2507    return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2508 }
2509
2510 /**
2511  * \brief   Build a new Element Value from all the low level arguments. 
2512  *          Check for existence of dictionary entry, and build
2513  *          a default one when absent.
2514  * @param   Group group   number of the underlying DictEntry
2515  * @param   Elem  element number of the underlying DictEntry
2516  */
2517 gdcmDocEntry *gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem) 
2518 {
2519    // Find out if the tag we encountered is in the dictionaries:
2520    gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2521    if (!DictEntry)
2522       DictEntry = NewVirtualDictEntry(Group, Elem);
2523
2524    gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2525    if (!NewEntry) 
2526    {
2527       dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2528                   "failed to allocate gdcmDocEntry");
2529       return NULL;
2530    }
2531    return NewEntry;
2532 }
2533
2534
2535 /**
2536  * \brief   Build a new Element Value from all the low level arguments. 
2537  *          Check for existence of dictionary entry, and build
2538  *          a default one when absent.
2539  * @param   Group group   number of the underlying DictEntry
2540  * @param   Elem  element number of the underlying DictEntry
2541  */
2542 gdcmValEntry *gdcmDocument::NewValEntryByNumber(guint16 Group, guint16 Elem) 
2543 {
2544    // Find out if the tag we encountered is in the dictionaries:
2545    gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2546    if (!DictEntry)
2547       DictEntry = NewVirtualDictEntry(Group, Elem);
2548
2549    gdcmValEntry *NewEntry = new gdcmValEntry(DictEntry);
2550    if (!NewEntry) 
2551    {
2552       dbg.Verbose(1, "gdcmDocument::NewValEntryByNumber",
2553                   "failed to allocate gdcmValEntry");
2554       return NULL;
2555    }
2556    return NewEntry;
2557 }
2558
2559
2560 /**
2561  * \brief   Build a new Element Value from all the low level arguments. 
2562  *          Check for existence of dictionary entry, and build
2563  *          a default one when absent.
2564  * @param   Group group   number of the underlying DictEntry
2565  * @param   Elem  element number of the underlying DictEntry
2566  */
2567 gdcmBinEntry *gdcmDocument::NewBinEntryByNumber(guint16 Group, guint16 Elem) 
2568 {
2569    // Find out if the tag we encountered is in the dictionaries:
2570    gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2571    if (!DictEntry)
2572       DictEntry = NewVirtualDictEntry(Group, Elem);
2573
2574    gdcmBinEntry *NewEntry = new gdcmBinEntry(DictEntry);
2575    if (!NewEntry) 
2576    {
2577       dbg.Verbose(1, "gdcmDocument::NewBinEntryByNumber",
2578                   "failed to allocate gdcmBinEntry");
2579       return NULL;
2580    }
2581    return NewEntry;
2582 }
2583
2584 /**
2585  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2586  *          in the TagHt dictionary.
2587  * @param   group The generated tag must belong to this group.  
2588  * @return  The element of tag with given group which is fee.
2589  */
2590 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group) 
2591 {
2592    for (guint32 elem = 0; elem < UINT32_MAX; elem++) 
2593    {
2594       TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2595       if (tagHT.count(key) == 0)
2596          return elem;
2597    }
2598    return UINT32_MAX;
2599 }
2600
2601
2602 /**
2603  * \brief   Searches both the public and the shadow dictionary (when they
2604  *          exist) for the presence of the DictEntry with given name.
2605  *          The public dictionary has precedence on the shadow one.
2606  * @param   Name name of the searched DictEntry
2607  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2608  */
2609 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name) 
2610 {
2611    gdcmDictEntry *found = (gdcmDictEntry *)0;
2612    if (!RefPubDict && !RefShaDict) 
2613    {
2614       dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2615                      "we SHOULD have a default dictionary");
2616    }
2617    if (RefPubDict) 
2618    {
2619       found = RefPubDict->GetDictEntryByName(Name);
2620       if (found)
2621          return found;
2622    }
2623    if (RefShaDict) 
2624    {
2625       found = RefShaDict->GetDictEntryByName(Name);
2626       if (found)
2627          return found;
2628    }
2629    return found;
2630 }
2631
2632 /**
2633  * \brief   Searches both the public and the shadow dictionary (when they
2634  *          exist) for the presence of the DictEntry with given
2635  *          group and element. The public dictionary has precedence on the
2636  *          shadow one.
2637  * @param   group   group number of the searched DictEntry
2638  * @param   element element number of the searched DictEntry
2639  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2640  */
2641 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element) 
2642 {
2643    gdcmDictEntry *found = (gdcmDictEntry *)0;
2644    if (!RefPubDict && !RefShaDict) 
2645    {
2646       dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2647                      "we SHOULD have a default dictionary");
2648    }
2649    if (RefPubDict) 
2650    {
2651       found = RefPubDict->GetDictEntryByNumber(group, element);
2652       if (found)
2653          return found;
2654    }
2655    if (RefShaDict) 
2656    {
2657       found = RefShaDict->GetDictEntryByNumber(group, element);
2658       if (found)
2659          return found;
2660    }
2661    return found;
2662 }
2663
2664
2665 /**
2666  * \ingroup gdcmDocument
2667  * \brief   Parse pixel data from disk for multi-fragment Jpeg/Rle files
2668  * \        No other way so 'skip' the Data
2669  *
2670  */
2671 void gdcmDocument::Parse7FE0 (void) {
2672
2673    gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2674    if ( !Element )
2675       return;
2676       
2677    std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
2678    if (Transfer == UI1_2_840_10008_1_2 )
2679       return;  
2680    if ( Transfer == UI1_2_840_10008_1_2_1 )
2681       return;
2682    if ( Transfer == UI1_2_840_10008_1_2_2 )  //1.2.2 ??? A verifier !
2683       return;         
2684    if ( Transfer == UI1_2_840_10008_1_2_1_99 )
2685       return;
2686       
2687    int nb;
2688    std::string str_nb=GetEntryByNumber(0x0028,0x0100);
2689    if (str_nb == GDCM_UNFOUND ) {
2690       nb = 16;
2691    } else {
2692       nb = atoi(str_nb.c_str() );
2693       if (nb == 12) nb =16;
2694    }
2695       
2696    guint16 ItemTagGr,ItemTagEl; 
2697    int ln;
2698    long ftellRes;
2699
2700   // -------------------- for Parsing : Position on begining of Jpeg/RLE Pixels 
2701
2702    if ( Transfer != UI1_1_2_840_10008_1_2_5 ) { // !RLELossLessTransferSyntax 
2703       // JPEG Image
2704       ftellRes=ftell(fp);
2705       fread(&ItemTagGr,2,1,fp);  //Reading (fffe):Basic Offset Table Item Tag Gr
2706       fread(&ItemTagEl,2,1,fp);  //Reading (e000):Basic Offset Table Item Tag El
2707       if(GetSwapCode()) {
2708          ItemTagGr=SwapShort(ItemTagGr); 
2709          ItemTagEl=SwapShort(ItemTagEl);            
2710       }
2711       printf ("at %x : ItemTag (should be fffe,e000): %04x,%04x\n",
2712                 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2713       ftellRes=ftell(fp);
2714       fread(&ln,4,1,fp); 
2715       if(GetSwapCode()) 
2716          ln=SwapLong(ln);    // Basic Offset Table Item Length
2717       printf("at %x : Basic Offset Table Item Length (\?\?) %d x(%08x)\n",
2718             (unsigned)ftellRes,ln,ln);
2719       if (ln != 0) {
2720          // What is it used for ??
2721          char * BasicOffsetTableItemValue= new char[ln+1];
2722          fread(BasicOffsetTableItemValue,ln,1,fp); 
2723          guint32 a;
2724          for (int i=0;i<ln;i+=4){
2725             a=str2num(&BasicOffsetTableItemValue[i],guint32);
2726             printf("      x(%08x)  %d\n",a,a);
2727          }              
2728       }
2729       
2730       ftellRes=ftell(fp);
2731       fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
2732       fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
2733       if(GetSwapCode()) {
2734          ItemTagGr=SwapShort(ItemTagGr); 
2735          ItemTagEl=SwapShort(ItemTagEl);            
2736       }  
2737       printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2738             (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2739       
2740       while ( ( ItemTagGr==0xfffe) && (ItemTagEl!=0xe0dd) ) { // Parse fragments
2741       
2742          ftellRes=ftell(fp);
2743          fread(&ln,4,1,fp); 
2744          if(GetSwapCode()) 
2745             ln=SwapLong(ln);    // length
2746          printf("      at %x : fragment length %d x(%08x)\n",
2747                 (unsigned)ftellRes, ln,ln);
2748
2749          // ------------------------                                     
2750          fseek(fp,ln,SEEK_CUR); // skipping (not reading) fragment pixels    
2751          // ------------------------              
2752      
2753          ftellRes=ftell(fp);
2754          fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
2755          fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
2756          if(GetSwapCode()) {
2757             ItemTagGr=SwapShort(ItemTagGr); 
2758             ItemTagEl=SwapShort(ItemTagEl);            
2759          }
2760          printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2761                (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2762       } 
2763
2764    } else {
2765
2766       // RLE Image
2767       long RleSegmentLength[15],fragmentLength;
2768       guint32 nbRleSegments;
2769       guint32 RleSegmentOffsetTable[15];
2770       ftellRes=ftell(fp);
2771       // Basic Offset Table with Item Value
2772          // Item Tag
2773       fread(&ItemTagGr,2,1,fp);  //Reading (fffe):Basic Offset Table Item Tag Gr
2774       fread(&ItemTagEl,2,1,fp);  //Reading (e000):Basic Offset Table Item Tag El
2775       if(GetSwapCode()) {
2776          ItemTagGr=SwapShort(ItemTagGr); 
2777          ItemTagEl=SwapShort(ItemTagEl);            
2778       }
2779       printf ("at %x : ItemTag (should be fffe,e000): %04x,%04x\n",
2780                 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2781          // Item Length
2782       ftellRes=ftell(fp);
2783       fread(&ln,4,1,fp); 
2784       if(GetSwapCode()) 
2785          ln=SwapLong(ln);    // Basic Offset Table Item Length
2786       printf("at %x : Basic Offset Table Item Length (\?\?) %d x(%08x)\n",
2787             (unsigned)ftellRes,ln,ln);
2788       if (ln != 0) {
2789          // What is it used for ??
2790          char * BasicOffsetTableItemValue= new char[ln+1];
2791          fread(BasicOffsetTableItemValue,ln,1,fp); 
2792          guint32 a;
2793          for (int i=0;i<ln;i+=4){
2794             a=str2num(&BasicOffsetTableItemValue[i],guint32);
2795             printf("      x(%08x)  %d\n",a,a);
2796          }              
2797       }
2798
2799       ftellRes=ftell(fp);
2800       fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
2801       fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
2802       if(GetSwapCode()) {
2803          ItemTagGr=SwapShort(ItemTagGr); 
2804          ItemTagEl=SwapShort(ItemTagEl);            
2805       }  
2806       printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2807             (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2808
2809       // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2810       while (  ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) { 
2811       // Parse fragments of the current Fragment (Frame)    
2812          ftellRes=ftell(fp);
2813          fread(&fragmentLength,4,1,fp); 
2814          if(GetSwapCode()) 
2815             fragmentLength=SwapLong(fragmentLength);    // length
2816          printf("      at %x : 'fragment' length %d x(%08x)\n",
2817                 (unsigned)ftellRes, (unsigned)fragmentLength,(unsigned)fragmentLength);
2818                        
2819           //------------------ scanning (not reading) fragment pixels
2820  
2821          fread(&nbRleSegments,4,1,fp);  // Reading : Number of RLE Segments
2822          if(GetSwapCode()) 
2823             nbRleSegments=SwapLong(nbRleSegments);
2824             printf("   Nb of RLE Segments : %d\n",nbRleSegments);
2825  
2826          for(int k=1; k<=15; k++) { // Reading RLE Segments Offset Table
2827             ftellRes=ftell(fp);
2828             fread(&RleSegmentOffsetTable[k],4,1,fp);
2829             if(GetSwapCode())
2830                RleSegmentOffsetTable[k]=SwapLong(RleSegmentOffsetTable[k]);
2831             printf("        at : %x Offset Segment %d : %d (%x)\n",
2832                     (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2833                     RleSegmentOffsetTable[k]);
2834          }
2835
2836           if (nbRleSegments>1) { // skipping (not reading) RLE Segments
2837              for(unsigned int k=1; k<=nbRleSegments-1; k++) { 
2838                 RleSegmentLength[k]=   RleSegmentOffsetTable[k+1]
2839                                      - RleSegmentOffsetTable[k];
2840                 ftellRes=ftell(fp);
2841                 printf ("  Segment %d : Length = %d x(%x) Start at %x\n",
2842                            k,(unsigned)RleSegmentLength[k],(unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2843                 fseek(fp,RleSegmentLength[k],SEEK_CUR);    
2844              }
2845           }
2846           RleSegmentLength[nbRleSegments]= fragmentLength 
2847                                          - RleSegmentOffsetTable[nbRleSegments];
2848           ftellRes=ftell(fp);
2849           printf ("  Segment %d : Length = %d x(%x) Start at %x\n",
2850                            nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2851                            (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2852
2853           fseek(fp,RleSegmentLength[nbRleSegments],SEEK_CUR); 
2854             
2855          // ------------------ end of scanning fragment pixels        
2856       
2857          ftellRes=ftell(fp);
2858          fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
2859          fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
2860          if(GetSwapCode()) {
2861             ItemTagGr=SwapShort(ItemTagGr); 
2862             ItemTagEl=SwapShort(ItemTagEl);            
2863          }
2864          printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2865                (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2866       } 
2867    }
2868    return;            
2869 }
2870
2871 /**
2872  * \brief   Compares two documents, according to \ref gdcmDicomDir rules
2873  * \warning Does NOT work with ACR-NEMA files
2874  * \todo    Find a trick to solve the pb (use RET fields ?)
2875  * @param   document
2876  * @return  true if 'smaller'
2877  */
2878  bool gdcmDocument::operator<(gdcmDocument &document){
2879    std::string s1,s2;
2880                                                                                 
2881    // Patient Name
2882    s1=this->GetEntryByNumber(0x0010,0x0010);
2883    s2=document.GetEntryByNumber(0x0010,0x0010);
2884    if(s1 < s2)
2885       return(true);
2886    else if(s1 > s2)
2887       return(false);
2888    else
2889    {
2890       // Patient ID
2891       s1=this->GetEntryByNumber(0x0010,0x0020);
2892       s2=document.GetEntryByNumber(0x0010,0x0020);
2893       if (s1 < s2)
2894          return(true);
2895       else if (s1 > s2)
2896          return(1);
2897       else
2898       {
2899          // Study Instance UID
2900          s1=this->GetEntryByNumber(0x0020,0x000d);
2901          s2=document.GetEntryByNumber(0x0020,0x000d);
2902          if (s1 < s2)
2903             return(true);
2904          else if(s1 > s2)
2905             return(false);
2906          else
2907          {
2908             // Serie Instance UID
2909             s1=this->GetEntryByNumber(0x0020,0x000e);
2910             s2=document.GetEntryByNumber(0x0020,0x000e);
2911             if (s1 < s2)
2912                return(true);
2913             else if(s1 > s2)
2914                return(false);
2915          }
2916       }
2917    }
2918    return(false);
2919 }
2920
2921
2922 //-----------------------------------------------------------------------------