]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
Remove useless accesses to the Dicom Dictionnary std::map
[gdcm.git] / src / gdcmFile.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFile.cxx,v $
5   Language:  C++
6   Date:      $Date: 2006/04/11 16:03:26 $
7   Version:   $Revision: 1.318 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19 //
20 // --------------  Remember ! ----------------------------------
21 //
22 // Image Position (Patient)                            (0020,0032):
23 // If not found (ACR_NEMA) we try Image Position       (0020,0030)
24 // If not found (ACR-NEMA), we consider Slice Location (0020,1041)
25 //                                   or Location       (0020,0050) 
26 //                                   as the Z coordinate, 
27 // 0. for all the coordinates if nothing is found
28 //
29 // Image Position (Patient) (0020,0032) VM=3
30 // -->
31 //  The attribute Patient Orientation (0020,0020) from the General Image Module 
32 // is of type 2C and has the condition Required if image does not require 
33 // Image Orientation (0020,0037) and Image Position (0020,0032). 
34 // However, if the image does require the attributes 
35 // - Image Orientation (Patient) (0020,0037), VM=6
36 // - Image Position (Patient)    (0020,0032), VM=3
37 // then attribute Patient Orientation (0020,0020) should not be present
38 //  in the images.
39 //
40 // Remember also :
41 // Patient Position (0018,5100) values :
42
43 //  HFS   = Head First-Supine, where increasing (positive axis direction) :
44 //     X -> to the direction pointed to by the patient's oustretched left arm
45 //     Y -> to the anterior-to-posterior direction in the patient's body
46 //     Z -> to the feet-to-head direction in the patient's body
47
48 //  HFP   = Head First-Prone, where increasing (positive axis direction) :
49 //     X -> to the direction pointed to by the patient's oustretched left arm
50 //     Y -> to the anterior-to-posterior direction in the patient's body
51 //     Z -> to the feet-to-head direction in the patient's body
52
53 //  FFS  = Feet First-Supine, where increasing (positive axis direction) :
54 //     X -> to the direction pointed to by the patient's oustretched left arm
55 //     Y -> to the anterior-to-posterion direction in the patient's body
56 //     Z -> to the feet-to-head direction in the patient's body
57
58 //  FFP  = Feet First-Prone, where increasing (positive axis direction) :
59 //     X -> to the direction pointed to by the patient's oustretched left arm
60 //     Y -> to the posterior-to-anterior direction in the patient's body
61 //     Z -> to the feet-to-head direction in the patient's body
62
63 // HFDR = Head First-Decubitus Right
64 // HFDL = Head First-Decubitus Left
65 // FFDR = Feet First-Decubitus Right
66 // FFDL = Feet First-Decubitus Left
67
68 //  we can also find (non standard!)     
69
70 // SEMIERECT
71 // SUPINE
72
73 // CS 2 Patient Orientation (0020 0020)
74 //    When the coordinates of the image 
75 //    are always present, this field is almost never used.
76 //    Better we don't trust it too much ...
77 //    Found Values are :
78 //     L\P
79 //     L\FP
80 //     P\F
81 //     L\F
82 //     P\FR
83 //     R\F
84 //
85 // (0020|0037) [Image Orientation (Patient)] [1\0\0\0\1\0 ]
86
87                
88 // ---------------------------------------------------------------
89 //
90 #include "gdcmFile.h"
91 #include "gdcmGlobal.h"
92 #include "gdcmUtil.h"
93 #include "gdcmDebug.h"
94 #include "gdcmTS.h"
95 #include "gdcmSeqEntry.h"
96 #include "gdcmRLEFramesInfo.h"
97 #include "gdcmJPEGFragmentsInfo.h"
98 #include "gdcmDataEntry.h"
99
100 #include <vector>
101 #include <stdio.h>  //sscanf
102 #include <stdlib.h> // for atoi
103
104 namespace gdcm 
105 {
106
107 //-----------------------------------------------------------------------------
108 // Constructor / Destructor
109
110 /**
111  * \brief Constructor used when we want to generate dicom files from scratch
112  */
113 File::File():
114    Document()
115 {
116    RLEInfo  = new RLEFramesInfo;
117    JPEGInfo = new JPEGFragmentsInfo;
118    GrPixel  = 0x7fe0;  // to avoid further troubles
119    NumPixel = 0x0010;
120    BasicOffsetTableItemValue = 0;
121    FourthDimensionLocation = TagKey(0,0);
122 }
123
124
125 /**
126  * \brief   Canonical destructor.
127  */
128 File::~File()
129 {
130    if ( RLEInfo )
131       delete RLEInfo;
132    if ( JPEGInfo )
133       delete JPEGInfo;
134    delete[] BasicOffsetTableItemValue;
135 }
136
137 //-----------------------------------------------------------------------------
138 // Public
139 /**
140  * \brief   Loader  
141  * @return false if file cannot be open or no swap info was found,
142  *         or no tag was found.
143  */
144 bool File::Load( ) 
145 {
146    if ( ! this->Document::Load( ) )
147       return false;
148
149     return DoTheLoadingJob( );   
150 }
151
152 /**
153  * \brief   Does the Loading Job (internal use only)
154  * @return false if file cannot be open or no swap info was found,
155  *         or no tag was found.
156  */
157 bool File::DoTheLoadingJob( ) 
158 {
159    // for some ACR-NEMA images GrPixel, NumPixel is *not* 7fe0,0010
160    // We may encounter the 'RETired' (0x0028, 0x0200) tag
161    // (Image Location") . This entry contains the number of
162    // the group that contains the pixel data (hence the "Pixel Data"
163    // is found by indirection through the "Image Location").
164    // Inside the group pointed by "Image Location" the searched element
165    // is conventionally the element 0x0010 (when the norm is respected).
166    // When the "Image Location" is missing we default to group 0x7fe0.
167    // Note: this IS the right place for the code
168  
169    // Image Location
170    const std::string &imgLocation = GetEntryString(0x0028, 0x0200);
171    if ( imgLocation == GDCM_UNFOUND )
172    {
173       // default value
174       GrPixel = 0x7fe0;
175    }
176    else
177    {
178       GrPixel = (uint16_t) atoi( imgLocation.c_str() );
179    }   
180
181    // sometimes Image Location value doesn't follow
182    // the supposed processor endianness.
183    // see gdcmData/cr172241.dcm
184    if ( GrPixel == 0xe07f )
185    {
186       GrPixel = 0x7fe0;
187    }
188
189    if ( GrPixel != 0x7fe0 )
190    {
191       // This is a kludge for old dirty Philips imager.
192       NumPixel = 0x1010;
193    }
194    else
195    {
196       NumPixel = 0x0010;
197    }
198
199    // Now, we know GrPixel and NumPixel.
200    // Let's create a VirtualDictEntry to allow a further VR modification
201    // and force VR to match with BitsAllocated.
202    DocEntry *entry = GetDocEntry(GrPixel, NumPixel); 
203    if ( entry != 0 )
204    {
205       // Compute the RLE or JPEG info
206       OpenFile();
207       const std::string &ts = GetTransferSyntax();
208       Fp->seekg( entry->GetOffset(), std::ios::beg );
209       if ( Global::GetTS()->IsRLELossless(ts) ) 
210          ComputeRLEInfo();
211       else if ( Global::GetTS()->IsJPEG(ts) )
212          ComputeJPEGFragmentInfo();
213       CloseFile();
214
215       // Create a new DataEntry to change the DictEntry
216       // The changed DictEntry will have 
217       // - a correct PixelVR OB or OW)
218       // - the name to "Pixel Data"
219       
220        //==>Take it easy!
221        //==> Just change the VR !
222
223 /* 
224       DataEntry *oldEntry = dynamic_cast<DataEntry *>(entry);
225       if (oldEntry)
226       {
227          VRKey PixelVR;
228          // 8 bits allocated is a 'O Bytes' , as well as 24 (old ACR-NEMA RGB)
229          // more than 8 (i.e 12, 16) is a 'O Words'
230          if ( GetBitsAllocated() == 8 || GetBitsAllocated() == 24 ) 
231             PixelVR = "OB";
232          else
233             PixelVR = "OW";
234
235          // Change only made if usefull
236          if ( PixelVR != oldEntry->GetVR() )
237          {       
238             //DictEntry* newDict = DictEntry::New(GrPixel,NumPixel,
239             //                                    PixelVR,"1","Pixel Data");
240             //DataEntry *newEntry = DataEntry::New(newDict);
241             //newDict->Delete();
242             //newEntry->Copy(entry);
243             //newEntry->SetBinArea(oldEntry->GetBinArea(),oldEntry->IsSelfArea());
244             //oldEntry->SetSelfArea(false);
245
246             //RemoveEntry(oldEntry);
247             //AddEntry(newEntry);
248             //newEntry->Delete();
249   
250          }
251       }
252 */
253          VRKey PixelVR;
254          // 8 bits allocated is a 'O Bytes' , as well as 24 (old ACR-NEMA RGB)
255          // more than 8 (i.e 12, 16) is a 'O Words'
256          if ( GetBitsAllocated() == 8 || GetBitsAllocated() == 24 ) 
257             PixelVR = "OB";
258          else
259             PixelVR = "OW";
260          // Change only made if usefull
261          if ( PixelVR != entry->GetVR() )
262          { 
263             entry->SetVR(PixelVR);  
264          }         
265    }
266    return true;
267 }
268
269 /**
270  * \brief  This predicate, based on hopefully reasonable heuristics,
271  *         decides whether or not the current File was properly parsed
272  *         and contains the mandatory information for being considered as
273  *         a well formed and usable Dicom/Acr File.
274  * @return true when File is the one of a reasonable Dicom/Acr file,
275  *         false otherwise. 
276  */
277 bool File::IsReadable()
278 {
279    if ( !Document::IsReadable() )
280    {
281       return false;
282    }
283
284    const std::string &res = GetEntryString(0x0028, 0x0005);
285    if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
286    {
287       gdcmWarningMacro("Wrong Image Dimensions" << res);
288       return false; // Image Dimensions
289    }
290    bool b0028_0100 = true;
291    if ( !GetDocEntry(0x0028, 0x0100) )
292    {
293       gdcmWarningMacro("Bits Allocated (0028|0100) not found"); 
294       //return false; // "Bits Allocated"
295       b0028_0100 = false;
296    }
297    bool b0028_0101 = true;
298    if ( !GetDocEntry(0x0028, 0x0101) )
299    {
300       gdcmWarningMacro("Bits Stored (0028|0101) not found");
301       //return false; // "Bits Stored"
302       b0028_0101 = false;
303    }
304    bool b0028_0102 = true;
305    if ( !GetDocEntry(0x0028, 0x0102) )
306    {
307       gdcmWarningMacro("Hight Bit (0028|0102) not found"); 
308       //return false; // "High Bit"
309       b0028_0102 = false;
310    }
311    bool b0028_0103 = true;
312    if ( !GetDocEntry(0x0028, 0x0103) )
313    {
314       gdcmWarningMacro("Pixel Representation (0028|0103) not found");
315       //return false; // "Pixel Representation" i.e. 'Sign' ( 0 : unsigned, 1 : signed)
316       b0028_0103 = false;
317    }
318
319    if ( !b0028_0100 && !b0028_0101 && !b0028_0102 && !b0028_0103)
320    {
321       gdcmWarningMacro("Too much mandatory Tags missing !");
322       return false;
323    }
324
325    if ( !GetDocEntry(GrPixel, NumPixel) )
326    {
327       gdcmWarningMacro("Pixel Dicom Element " << std::hex <<
328                         GrPixel << "|" << NumPixel << "not found");
329       return false; // Pixel Dicom Element not found :-(
330    }
331    return true;
332 }
333
334 /**
335  * \brief gets the info from 0020,0013 : Image Number else 0.
336  * @return image number
337  */
338 int File::GetImageNumber()
339 {
340    //0020 0013 : Image Number
341    std::string strImNumber = GetEntryString(0x0020,0x0013);
342    if ( strImNumber != GDCM_UNFOUND )
343    {
344       return atoi( strImNumber.c_str() );
345    }
346    return 0;   //Hopeless
347 }
348
349 /**
350  * \brief gets the info from 0008,0060 : Modality
351  * @return Modality Type
352  */
353 ModalityType File::GetModality()
354 {
355    // 0008 0060 : Modality
356    std::string strModality = GetEntryString(0x0008,0x0060);
357    if ( strModality != GDCM_UNFOUND )
358    {
359            if ( strModality.find("AU")  < strModality.length()) return AU;
360       else if ( strModality.find("AS")  < strModality.length()) return AS;
361       else if ( strModality.find("BI")  < strModality.length()) return BI;
362       else if ( strModality.find("CF")  < strModality.length()) return CF;
363       else if ( strModality.find("CP")  < strModality.length()) return CP;
364       else if ( strModality.find("CR")  < strModality.length()) return CR;
365       else if ( strModality.find("CT")  < strModality.length()) return CT;
366       else if ( strModality.find("CS")  < strModality.length()) return CS;
367       else if ( strModality.find("DD")  < strModality.length()) return DD;
368       else if ( strModality.find("DF")  < strModality.length()) return DF;
369       else if ( strModality.find("DG")  < strModality.length()) return DG;
370       else if ( strModality.find("DM")  < strModality.length()) return DM;
371       else if ( strModality.find("DS")  < strModality.length()) return DS;
372       else if ( strModality.find("DX")  < strModality.length()) return DX;
373       else if ( strModality.find("ECG") < strModality.length()) return ECG;
374       else if ( strModality.find("EPS") < strModality.length()) return EPS;
375       else if ( strModality.find("FA")  < strModality.length()) return FA;
376       else if ( strModality.find("FS")  < strModality.length()) return FS;
377       else if ( strModality.find("HC")  < strModality.length()) return HC;
378       else if ( strModality.find("HD")  < strModality.length()) return HD;
379       else if ( strModality.find("LP")  < strModality.length()) return LP;
380       else if ( strModality.find("LS")  < strModality.length()) return LS;
381       else if ( strModality.find("MA")  < strModality.length()) return MA;
382       else if ( strModality.find("MR")  < strModality.length()) return MR;
383       else if ( strModality.find("NM")  < strModality.length()) return NM;
384       else if ( strModality.find("OT")  < strModality.length()) return OT;
385       else if ( strModality.find("PT")  < strModality.length()) return PT;
386       else if ( strModality.find("RF")  < strModality.length()) return RF;
387       else if ( strModality.find("RG")  < strModality.length()) return RG;
388       else if ( strModality.find("RTDOSE")   
389                                         < strModality.length()) return RTDOSE;
390       else if ( strModality.find("RTIMAGE")  
391                                         < strModality.length()) return RTIMAGE;
392       else if ( strModality.find("RTPLAN")
393                                         < strModality.length()) return RTPLAN;
394       else if ( strModality.find("RTSTRUCT") 
395                                         < strModality.length()) return RTSTRUCT;
396       else if ( strModality.find("SM")  < strModality.length()) return SM;
397       else if ( strModality.find("ST")  < strModality.length()) return ST;
398       else if ( strModality.find("TG")  < strModality.length()) return TG;
399       else if ( strModality.find("US")  < strModality.length()) return US;
400       else if ( strModality.find("VF")  < strModality.length()) return VF;
401       else if ( strModality.find("XA")  < strModality.length()) return XA;
402       else if ( strModality.find("XC")  < strModality.length()) return XC;
403
404       else
405       {
406          /// \todo throw error return value ???
407          /// specified <> unknown in our database
408          return Unknow;
409       }
410    }
411    return Unknow;
412 }
413
414 /**
415  * \brief   Retrieve the number of columns of image.
416  * @return  The encountered size when found, 0 by default.
417  *          0 means the file is NOT USABLE. The caller will have to check
418  */
419 int File::GetXSize()
420 {
421    DataEntry *entry = GetDataEntry(0x0028,0x0011);
422    if( entry )
423       return (int)entry->GetValue(0);
424    return 0;
425 }
426
427 /**
428  * \brief   Retrieve the number of lines of image.
429  * \warning The defaulted value is 1 as opposed to File::GetXSize()
430  * @return  The encountered size when found, 1 by default 
431  *          (The ACR-NEMA file contains a Signal, not an Image).
432  */
433 int File::GetYSize()
434 {
435    DataEntry *entry = GetDataEntry(0x0028,0x0010);
436    if( entry )
437       return (int)entry->GetValue(0);
438
439    if ( IsDicomV3() )
440    {
441       return 0;
442    }
443
444    // The Rows (0028,0010) entry was optional for ACR/NEMA.
445    // (at least some images didn't have it.)
446    // It might hence be a signal (1D image). So we default to 1:
447    return 1;
448 }
449
450 /**
451  * \brief   Retrieve the number of planes of volume or the number
452  *          of frames of a multiframe.
453  * \warning When present we consider the "Number of Frames" as the third
454  *          dimension. When missing we consider the third dimension as
455  *          being the ACR-NEMA "Planes" tag content.
456  * @return  The encountered size when found, 1 by default (single image).
457  */
458 int File::GetZSize()
459 {
460    // Both  DicomV3 and ACR/Nema consider the "Number of Frames"
461    // as the third dimension.
462    DataEntry *entry = GetDataEntry(0x0028,0x0008);
463    if( entry )
464       return (int)entry->GetValue(0);
465
466    // We then consider the "Planes" entry as the third dimension 
467    entry = GetDataEntry(0x0028,0x0012);
468    if( entry )
469       return (int)entry->GetValue(0);
470    return 1;
471 }
472
473 /**
474  * \brief   Retrieve the -unnormalized- number of 'times' of '4D image'.
475  *          User has to tell gdcm the location of this '4th Dimension component'
476  *          using SetFourthDimensionLocation() method before.
477  * \warning The defaulted value is 1.
478  * @return  The encountered size when found, 1 by default 
479  *          (The file doesn't contain a '4D image'.).
480  */
481 int File::GetTSize()
482 {
483    if (FourthDimensionLocation == TagKey(0,0) )// 4D location is not set : not a 4D object
484       return 1;
485       
486    DataEntry *entry = GetDataEntry(FourthDimensionLocation.GetGroup(),
487                                    FourthDimensionLocation.GetElement() );
488    if( !entry )   
489    {
490       gdcmWarningMacro( " FourthDimensionLocation not found at : " <<
491                     std::hex << FourthDimensionLocation.GetGroup()
492                   << "|" << FourthDimensionLocation.GetElement());
493       return 1;
494    }
495    else
496    {
497       return (int)entry->GetValue(0);
498    }      
499 }  
500
501 /**
502   * \brief gets the info from 0018,1164 : ImagerPixelSpacing
503   *                      then 0028,0030 : Pixel Spacing
504   *             else 1.0
505   * @return X dimension of a pixel
506   */
507 float File::GetXSpacing()
508 {
509    float xspacing = 1.0;
510    uint32_t nbValue;
511
512    // To follow David Clunie's advice, we first check ImagerPixelSpacing
513
514    DataEntry *entry = GetDataEntry(0x0018,0x1164);
515    if( entry )
516    {
517       nbValue = entry->GetValueCount();
518       // Can't use IsValueCountValid because of the complex heuristic.
519       if( nbValue !=2 )
520          gdcmWarningMacro("ImagerPixelSpacing (0x0018,0x1164) "
521          << "has a wrong number of values :" << nbValue);
522      
523       if( nbValue >= 3 )
524          xspacing = (float)entry->GetValue(2);
525       else if( nbValue >= 2 )
526          xspacing = (float)entry->GetValue(1);
527       else
528          xspacing = (float)entry->GetValue(0);
529
530       if ( xspacing == 0.0 )
531          xspacing = 1.0;
532       return xspacing;
533    }
534    else
535    {
536       gdcmWarningMacro( "Unfound Imager Pixel Spacing (0018,1164)" );
537    }
538
539    entry = GetDataEntry(0x0028,0x0030);
540    if( entry )
541    {
542       nbValue = entry->GetValueCount();
543       if( nbValue !=2 )
544          gdcmWarningMacro("PixelSpacing (0x0018,0x0030) "
545           << "has a wrong number of values :" << nbValue);      
546       
547       if( nbValue >= 3 )
548          xspacing = (float)entry->GetValue(2);
549       else if( nbValue >= 2 )
550          xspacing = (float)entry->GetValue(1);
551       else
552          xspacing = (float)entry->GetValue(0);
553
554       if ( xspacing == 0.0 )
555          xspacing = 1.0;
556       return xspacing;
557    }
558    else
559    {
560       gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
561    }
562    return xspacing;
563 }
564
565 /**
566   * \brief gets the info from 0018,1164 : ImagerPixelSpacing
567   *               then from   0028,0030 : Pixel Spacing                         
568   *             else 1.0
569   * @return Y dimension of a pixel
570   */
571 float File::GetYSpacing()
572 {
573    float yspacing = 1.0;
574    // To follow David Clunie's advice, we first check ImagerPixelSpacing
575
576    DataEntry *entry = GetDataEntry(0x0018,0x1164);
577    if( entry )
578    {
579       yspacing = (float)entry->GetValue(0);
580
581       if ( yspacing == 0.0 )
582          yspacing = 1.0;
583       return yspacing;
584    }
585    else
586    {
587       gdcmWarningMacro( "Unfound Imager Pixel Spacing (0018,1164)" );
588    }
589
590    entry = GetDataEntry(0x0028,0x0030);
591    if( entry )
592    {
593       yspacing = (float)entry->GetValue(0);
594
595       if ( yspacing == 0.0 )
596          yspacing = 1.0;
597       return yspacing;
598    }
599    else
600    {
601       gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
602    }
603
604    return yspacing;
605
606
607 /**
608  * \brief gets the info from 0018,0088 : Space Between Slices
609  *                 else from 0018,0050 : Slice Thickness
610  *                 else 1.0
611  *
612  * When an element is missing, we suppose slices join together
613  * (no overlapping, no interslice gap) but we have no way to check it !
614  * For *Dicom* images, ZSpacing *should be* calculated using 
615  * XOrigin, YOrigin, ZOrigin (of the top left image corner)
616  * of 2 consecutive images, and the Orientation
617  * Computing ZSpacing on a single image is not really meaningfull ! 
618  * @return Z dimension of a voxel-to be
619  */
620 float File::GetZSpacing()
621 {
622
623    float zspacing = 1.0f;
624
625    // Spacing Between Slices : distance between the middle of 2 slices
626    // Slices may be :
627    //   jointives     (Spacing between Slices = Slice Thickness)
628    //   overlapping   (Spacing between Slices < Slice Thickness)
629    //   disjointes    (Spacing between Slices > Slice Thickness)
630    // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
631    //   It only concerns the MRI guys, not people wanting to visualize volumes
632    //   If Spacing Between Slices is missing, 
633    //   we suppose slices joint together
634    DataEntry *entry = GetDataEntry(0x0018,0x0088);
635    if( entry )
636    {
637       zspacing = (float)entry->GetValue(0);
638
639       if ( zspacing == 0.0 )
640          zspacing = 1.0;
641       return zspacing;
642    }
643    else
644       gdcmWarningMacro("Unfound Spacing Between Slices (0018,0088)");
645
646    // if no 'Spacing Between Slices' is found, 
647    // we assume slices join together
648    // (no overlapping, no interslice gap)
649    entry = GetDataEntry(0x0018,0x0050);
650    if( entry )
651    {
652       zspacing = (float)entry->GetValue(0);
653
654       if ( zspacing == 0.0 )
655          zspacing = 1.0;
656       return zspacing;
657    }
658    else
659       gdcmWarningMacro("Unfound Slice Thickness (0018,0050)");
660
661    // if no 'Spacing Between Slices' is found, 
662    // we assume slices join together
663    // (no overlapping, no interslice gap)
664    entry = GetDataEntry(0x3004,0x000c);
665    if( entry )
666    {
667       float z1 = (float)entry->GetValue(0);
668       float z2 = (float)entry->GetValue(1);
669       zspacing = z2 - z1; // can be negative...
670
671       if ( zspacing == 0.0 )
672          zspacing = 1.0;
673       return zspacing;
674    }
675
676    return zspacing;
677 }
678
679 /**
680  * \brief gets the info from 0020,0032 : Image Position Patient
681  *                 else from 0020,0030 : Image Position (RET)
682  *                 else 0.
683  * @return up-left image corner X position
684  */
685 float File::GetXOrigin()
686 {
687    DataEntry *entry = GetDataEntry(0x0020,0x0032);
688    if( !entry )
689    {
690       gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
691       entry = GetDataEntry(0x0020,0x0030);
692       if( !entry )
693       {
694          gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
695          return 0.0f;
696       }
697    }
698
699    if( entry->GetValueCount() == 3 )
700    {
701       if (!entry->IsValueCountValid() )
702       {
703          gdcmErrorMacro( "Invalid Value Count" );
704       }
705       return (float)entry->GetValue(0);
706    }
707    return 0.0f;
708 }
709
710 /**
711  * \brief gets the info from 0020,0032 : Image Position Patient
712  *                 else from 0020,0030 : Image Position (RET)
713  *                 else 0.
714  * @return up-left image corner Y position
715  */
716 float File::GetYOrigin()
717 {
718    DataEntry *entry = GetDataEntry(0x0020,0x0032);
719    if( !entry )
720    {
721       gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
722       entry = GetDataEntry(0x0020,0x0030);
723       if( !entry )
724       {
725          gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
726          return 0.0f;
727       }
728    }
729
730    if( entry->GetValueCount() == 3 )
731    {
732       if (!entry->IsValueCountValid() )
733       {
734          gdcmErrorMacro( "Invalid Value Count" );
735       }
736       return (float)entry->GetValue(1);
737    }
738    return 0.0f;
739 }
740
741 /**
742  * \brief gets the info from 0020,0032 : Image Position Patient
743  *                 else from 0020,0030 : Image Position (RET)
744  *                 else from 0020,1041 : Slice Location
745  *                 else from 0020,0050 : Location
746  *                 else 0.
747  * @return up-left image corner Z position
748  */
749 float File::GetZOrigin()
750 {
751    DataEntry *entry = GetDataEntry(0x0020,0x0032);
752    if( entry )
753    {
754       if( entry->GetValueCount() == 3 )
755       {
756          if (!entry->IsValueCountValid() )
757          {
758             gdcmErrorMacro( "Invalid Value Count" );
759          }
760          return (float)entry->GetValue(2);
761       }
762       gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)");
763       return 0.0f;
764    }
765
766    entry = GetDataEntry(0x0020,0x0030);
767    if( entry )
768    {
769       if( entry->GetValueCount() == 3 )
770       {
771          if (!entry->IsValueCountValid() )
772          {
773             gdcmErrorMacro( "Invalid Value Count" );
774          }
775          return (float)entry->GetValue(2);
776       }
777       gdcmWarningMacro( "Wrong Image Position (RET) (0020,0030)");
778       return 0.0f;
779    }
780
781    // for *very* old ACR-NEMA images
782    entry = GetDataEntry(0x0020,0x1041);
783    if( entry )
784    {
785       if( entry->GetValueCount() == 1 )
786       {
787          if (!entry->IsValueCountValid() )
788          {
789             gdcmErrorMacro( "Invalid Value Count" );
790          }
791          return (float)entry->GetValue(0); // VM=1 !
792       }
793       gdcmWarningMacro( "Wrong Slice Location (0020,1041)");
794       return 0.0f;
795    }
796
797    entry = GetDataEntry(0x0020,0x0050);
798    if( entry )
799    {
800       if( entry->GetValueCount() == 1 )
801       {
802          if (!entry->IsValueCountValid() )
803          {
804             gdcmErrorMacro( "Invalid Value Count" );
805          }
806          return (float)entry->GetValue(0);
807       }
808       gdcmWarningMacro( "Wrong Location (0020,0050)");
809       return 0.0f;
810    }
811    return 0.; // Hopeless
812 }
813
814 /**
815   * \brief gets the info from 0020,0037 : Image Orientation Patient
816   *                   or from 0020 0035 : Image Orientation (RET)
817   *
818   * (needed to organize DICOM files based on their x,y,z position)
819   *
820   * @param iop adress of the (6)float array to receive values.
821   *        (defaulted as 1.,0.,0.,0.,1.,0. if nothing -or inconsistent stuff-
822   *        is found.
823   * @return true when one of the tag -with consistent values- is found
824   *         false when nothing or inconsistent stuff - is found
825   */
826 bool File::GetImageOrientationPatient( float iop[6] )
827 {
828    std::string strImOriPat;
829    //iop is supposed to be float[6]
830    iop[0] = iop[4] = 1.;
831    iop[1] = iop[2] = iop[3] = iop[5] = 0.;
832
833    // 0020 0037 DS REL Image Orientation (Patient)
834    if ( (strImOriPat = GetEntryString(0x0020,0x0037)) != GDCM_UNFOUND )
835    {
836       if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ", 
837           &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
838       {
839          gdcmWarningMacro( "Wrong Image Orientation Patient (0020,0037)."
840                         << " Less than 6 values were found." );
841          return false;
842       }
843       return true;
844    }
845    //For ACR-NEMA
846    // 0020 0035 DS REL Image Orientation (RET)
847    else if ( (strImOriPat = GetEntryString(0x0020,0x0035)) != GDCM_UNFOUND )
848    {
849       if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ", 
850           &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
851       {
852          gdcmWarningMacro( "wrong Image Orientation Patient (0020,0035). "
853                         << "Less than 6 values were found." );
854          return false;
855       }
856       return true;
857    }
858    return false;
859 }
860
861 /**
862  * \brief   Retrieve the number of Bits Stored (actually used)
863  *          (as opposed to number of Bits Allocated)
864  * @return  The encountered number of Bits Stored, 0 by default.
865  *          0 means the file is NOT USABLE. The caller has to check it !
866  */
867 int File::GetBitsStored()
868 {
869    DataEntry *entry = GetDataEntry(0x0028,0x0101);
870    if( !entry )
871    {
872       gdcmWarningMacro("BitsStored (0028,0101) is supposed to be mandatory");
873       return 0;
874    }
875    return (int)entry->GetValue(0);
876 }
877
878 /**
879  * \brief   Retrieve the number of Bits Allocated
880  *          (8, 12 -compacted ACR-NEMA files-, 16, 24 -old RGB ACR-NEMA files-,)
881  * @return  The encountered Number of Bits Allocated, 0 by default.
882  *          0 means the file is NOT USABLE. The caller has to check it !
883  */
884 int File::GetBitsAllocated()
885 {
886    DataEntry *entry = GetDataEntry(0x0028,0x0100);
887    if( !entry )
888    {
889       gdcmWarningMacro("BitsAllocated (0028,0100) is supposed to be mandatory");
890       return 0;
891    }
892    return (int)entry->GetValue(0);
893 }
894
895 /**
896  * \brief   Retrieve the high bit position.
897  * \warning The method defaults to 0 when information is missing.
898  *          The responsability of checking this value is left to the caller.
899  * @return  The high bit position when present. 0 when missing.
900  */
901 int File::GetHighBitPosition()
902 {
903    DataEntry *entry = GetDataEntry(0x0028,0x0102);
904    if( !entry )
905    {
906       gdcmWarningMacro("HighBitPosition (0028,0102) is supposed to be mandatory");
907       return 0;
908    }
909    return (int)entry->GetValue(0);
910 }
911
912 /**
913  * \brief   Retrieve the number of Samples Per Pixel
914  *          (1 : gray level, 3 : RGB/YBR -1 or 3 Planes-)
915  * @return  The encountered number of Samples Per Pixel, 1 by default.
916  *          (we assume Gray level Pixels)
917  */
918 int File::GetSamplesPerPixel()
919 {
920    DataEntry *entry = GetDataEntry(0x0028,0x0002);
921    if( !entry )
922    {
923       gdcmWarningMacro("SamplesPerPixel (0028,0002) is supposed to be mandatory");
924       return 1; // Well, it's supposed to be mandatory ...
925                 // but sometimes it's missing : *we* assume Gray pixels
926    }
927    return (int)entry->GetValue(0);
928 }
929
930 /**
931  * \brief   Retrieve the Planar Configuration for RGB images
932  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
933  * @return  The encountered Planar Configuration, 0 by default.
934  */
935 int File::GetPlanarConfiguration()
936 {
937    DataEntry *entry = GetDataEntry(0x0028,0x0006);
938    if( !entry )
939    {
940       return 0;
941    }
942    return (int)entry->GetValue(0);
943 }
944
945 /**
946  * \brief   Return the size (in bytes) of a single pixel of data.
947  * @return  The size in bytes of a single pixel of data; 0 by default
948  *          0 means the file is NOT USABLE; the caller will have to check
949  */
950 int File::GetPixelSize()
951 {
952    // 0028 0100 US IMG Bits Allocated
953    // (in order no to be messed up by old ACR-NEMA RGB images)
954    assert( !(GetEntryString(0x0028,0x0100) == "24") );
955
956    std::string pixelType = GetPixelType();
957    if ( pixelType ==  "8U" || pixelType == "8S" )
958    {
959       return 1;
960    }
961    if ( pixelType == "16U" || pixelType == "16S")
962    {
963       return 2;
964    }
965    if ( pixelType == "32U" || pixelType == "32S")
966    {
967       return 4;
968    }
969    if ( pixelType == "FD" )
970    {
971       return 8;
972    }
973    gdcmWarningMacro( "Unknown pixel type: " << pixelType);
974    return 0;
975 }
976
977 /**
978  * \brief   Build the Pixel Type of the image.
979  *          Possible values are:
980  *          - 8U  unsigned  8 bit,
981  *          - 8S    signed  8 bit,
982  *          - 16U unsigned 16 bit,
983  *          - 16S   signed 16 bit,
984  *          - 32U unsigned 32 bit,
985  *          - 32S   signed 32 bit,
986  *          - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
987  * \warning 12 bit images appear as 16 bit.
988  *          24 bit images appear as 8 bit + photochromatic interp ="RGB "
989  *                                        + Planar Configuration = 0
990  * @return  0S if nothing found. NOT USABLE file. The caller has to check
991  */
992 std::string File::GetPixelType()
993 {
994    std::string bitsAlloc = GetEntryString(0x0028, 0x0100); // Bits Allocated
995    if ( bitsAlloc == GDCM_UNFOUND )
996    {
997       gdcmWarningMacro( "Bits Allocated (0028,0100) supposed to be mandatory");
998       bitsAlloc = "16"; // default and arbitrary value, not to polute the output
999    }
1000
1001    if ( bitsAlloc == "64" )
1002    {
1003       return "FD";
1004    }
1005    else if ( bitsAlloc == "12" )
1006    {
1007       // It will be unpacked
1008       bitsAlloc = "16";
1009    }
1010    else if ( bitsAlloc == "24" )
1011    {
1012       // (in order no to be messed up by old RGB images)
1013       bitsAlloc = "8";
1014    }
1015
1016    std::string sign;
1017    if( IsSignedPixelData() )
1018    {
1019       sign = "S";
1020    }
1021    else
1022    {
1023       sign = "U";
1024    }
1025    return bitsAlloc + sign;
1026 }
1027
1028 /**
1029  * \brief   Check whether the pixels are signed (1) or UNsigned (0) data.
1030  * \warning The method defaults to false (UNsigned) when tag 0028|0103
1031  *          is missing.
1032  *          The responsability of checking this value is left to the caller
1033  *          (NO transformation is performed on the pixels to make then >0)
1034  * @return  True when signed, false when UNsigned
1035  */
1036 bool File::IsSignedPixelData()
1037 {
1038    DataEntry *entry = GetDataEntry(0x0028, 0x0103);//"Pixel Representation"
1039    if( !entry )
1040    {
1041       gdcmWarningMacro( "Pixel Representation (0028,0103) supposed to be "
1042                       << "mandatory");
1043       return false;
1044    }
1045    return entry->GetValue(0) != 0;
1046 }
1047
1048 /**
1049  * \brief   Check whether this a monochrome picture (gray levels) or not,
1050  *          using "Photometric Interpretation" tag (0x0028,0x0004).
1051  * @return  true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
1052  */
1053 bool File::IsMonochrome()
1054 {
1055    const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1056    if (  Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
1057       || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
1058    {
1059       return true;
1060    }
1061    if ( PhotometricInterp == GDCM_UNFOUND )
1062    {
1063       gdcmWarningMacro( "Photometric Interpretation (0028,0004) supposed to be "
1064                          << "mandatory");
1065    }
1066    return false;
1067 }
1068
1069 /**
1070  * \brief   Check whether this a MONOCHROME1 picture (high values = dark)
1071  *            or not using "Photometric Interpretation" tag (0x0028,0x0004).
1072  * @return  true when "MONOCHROME1" . False otherwise.
1073  */
1074 bool File::IsMonochrome1()
1075 {
1076    const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1077    if (  Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
1078    {
1079       return true;
1080    }
1081    if ( PhotometricInterp == GDCM_UNFOUND )
1082    {
1083       gdcmWarningMacro( "Photometric Interpretation (0028,0004) : supposed to"
1084       << " be mandatory! ");
1085    }
1086    return false;
1087 }
1088
1089 /**
1090  * \brief   Check whether this a "PALETTE COLOR" picture or not by accessing
1091  *          the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1092  * @return  true when "PALETTE COLOR". False otherwise.
1093  */
1094 bool File::IsPaletteColor()
1095 {
1096    std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1097    if (   PhotometricInterp == "PALETTE COLOR " )
1098    {
1099       return true;
1100    }
1101    if ( PhotometricInterp == GDCM_UNFOUND )
1102    {
1103       gdcmDebugMacro( "Not found : Palette color (0028,0004)");
1104    }
1105    return false;
1106 }
1107
1108 /**
1109  * \brief   Check whether this a "YBR_FULL" color picture or not by accessing
1110  *          the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1111  * @return  true when "YBR_FULL". False otherwise.
1112  */
1113 bool File::IsYBRFull()
1114 {
1115    std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1116    if (   PhotometricInterp == "YBR_FULL" )
1117    {
1118       return true;
1119    }
1120    if ( PhotometricInterp == GDCM_UNFOUND )
1121    {
1122       gdcmDebugMacro( "Not found : YBR Full (0028,0004)");
1123    }
1124    return false;
1125 }
1126
1127 /**
1128   * \brief tells us if LUT are used
1129   * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1130   *          are NOT considered as LUT, since nobody knows
1131   *          how to deal with them
1132   *          Please warn me if you know sbdy that *does* know ... jprx
1133   * @return true if LUT Descriptors and LUT Tables were found 
1134   */
1135 bool File::HasLUT()
1136 {
1137    // Check the presence of the LUT Descriptors, and LUT Tables    
1138    // LutDescriptorRed    
1139    if ( !GetDocEntry(0x0028,0x1101) )
1140    {
1141       return false;
1142    }
1143    // LutDescriptorGreen 
1144    if ( !GetDocEntry(0x0028,0x1102) )
1145    {
1146       return false;
1147    }
1148    // LutDescriptorBlue 
1149    if ( !GetDocEntry(0x0028,0x1103) )
1150    {
1151       return false;
1152    }
1153    // Red Palette Color Lookup Table Data
1154    if ( !GetDocEntry(0x0028,0x1201) )
1155    {
1156       return false;
1157    }
1158    // Green Palette Color Lookup Table Data       
1159    if ( !GetDocEntry(0x0028,0x1202) )
1160    {
1161       return false;
1162    }
1163    // Blue Palette Color Lookup Table Data      
1164    if ( !GetDocEntry(0x0028,0x1203) )
1165    {
1166       return false;
1167    }
1168
1169    // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1170    //         NOT taken into account, but we don't know how to use it ...   
1171    return true;
1172 }
1173
1174 /**
1175   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1176   *             else 0
1177   * @return Lookup Table number of Bits , 0 by default
1178   *          when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1179   * @ return bit number of each LUT item 
1180   */
1181 int File::GetLUTNbits()
1182 {
1183    std::vector<std::string> tokens;
1184    int lutNbits;
1185
1186    //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1187    //                                = Lookup Table Desc-Blue
1188    // Consistency already checked in GetLUTLength
1189    std::string lutDescription = GetEntryString(0x0028,0x1101);
1190    if ( lutDescription == GDCM_UNFOUND )
1191    {
1192       return 0;
1193    }
1194
1195    tokens.clear(); // clean any previous value
1196    Util::Tokenize ( lutDescription, tokens, "\\" );
1197    //LutLength=atoi(tokens[0].c_str());
1198    //LutDepth=atoi(tokens[1].c_str());
1199
1200    lutNbits = atoi( tokens[2].c_str() );
1201    tokens.clear();
1202
1203    return lutNbits;
1204 }
1205
1206 /**
1207  *\brief gets the info from 0028,1052 : Rescale Intercept
1208  * @return Rescale Intercept. defaulted to 0.0 is not found or empty
1209  */
1210 float File::GetRescaleIntercept()
1211 {
1212    // 0028 1052 DS IMG Rescale Intercept
1213    DataEntry *entry = GetDataEntry(0x0028, 0x1052);
1214    if( !entry )
1215    {
1216       gdcmWarningMacro( "Missing Rescale Intercept (0028,1052)");
1217       return 0.0f;
1218    }
1219    return (float)entry->GetValue(0);
1220
1221 }
1222
1223 /**
1224  *\brief   gets the info from 0028,1053 : Rescale Slope
1225  * @return Rescale Slope. defaulted to 1.0 is not found or empty
1226  */
1227 float File::GetRescaleSlope()
1228 {
1229    // 0028 1053 DS IMG Rescale Slope
1230    DataEntry *entry = GetDataEntry(0x0028, 0x1053);
1231    if( !entry )
1232    {
1233       gdcmDebugMacro( "Missing Rescale Slope (0028,1053)");
1234       return 1.0f;
1235    }
1236    return (float)entry->GetValue(0);
1237 }
1238
1239 /**
1240  * \brief This function is intended to user who doesn't want 
1241  *   to have to manage a LUT and expects to get an RBG Pixel image
1242  *   (or a monochrome one, if no LUT found ...) 
1243  * \warning to be used with GetImagePixels()
1244  * @return 1 if Gray level, 3 if Color (RGB, YBR, *or PALETTE COLOR*)
1245  */
1246 int File::GetNumberOfScalarComponents()
1247 {
1248    if ( GetSamplesPerPixel() == 3 )
1249    {
1250       return 3;
1251    }
1252
1253    // 0028 0100 US IMG Bits Allocated
1254    // (in order no to be messed up by old RGB images)
1255    if ( GetEntryString(0x0028,0x0100) == "24" )
1256    {
1257       return 3;
1258    }
1259
1260    std::string strPhotometricInterpretation = GetEntryString(0x0028,0x0004);
1261
1262    if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1263    {
1264       if ( HasLUT() )// PALETTE COLOR is NOT enough
1265       {
1266          return 3;
1267       }
1268       else
1269       {
1270          return 1;
1271       }
1272    }
1273
1274    // beware of trailing space at end of string      
1275    // DICOM tags are never of odd length
1276    if ( strPhotometricInterpretation == GDCM_UNFOUND   || 
1277         Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1278         Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1279    {
1280       return 1;
1281    }
1282    else
1283    {
1284       // we assume that *all* kinds of YBR are dealt with
1285       return 3;
1286    }
1287 }
1288
1289 /**
1290  * \brief This function is intended to user that DOESN'T want 
1291  *  to get RGB pixels image when it's stored as a PALETTE COLOR image
1292  *   - the (vtk) user is supposed to know how deal with LUTs - 
1293  * \warning to be used with GetImagePixelsRaw()
1294  * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1295  */
1296 int File::GetNumberOfScalarComponentsRaw()
1297 {
1298    // 0028 0100 US IMG Bits Allocated
1299    // (in order no to be messed up by old RGB images)
1300    if ( File::GetEntryString(0x0028,0x0100) == "24" )
1301    {
1302       return 3;
1303    }
1304
1305    // we assume that *all* kinds of YBR are dealt with
1306    return GetSamplesPerPixel();
1307 }
1308
1309 /**
1310  * \brief   Recover the offset (from the beginning of the file) 
1311  *          of *image* pixels (not *icone image* pixels, if any !)
1312  * @return Pixel Offset
1313  */
1314 size_t File::GetPixelOffset()
1315 {
1316    DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1317    if ( pxlElement )
1318    {
1319       return pxlElement->GetOffset();
1320    }
1321    else
1322    {
1323       gdcmWarningMacro( "Big trouble : Pixel Element ("
1324                       << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1325       return 0;
1326    }
1327 }
1328
1329 /**
1330  * \brief   Recover the pixel area length (in Bytes)
1331  * @return Pixel Element Length, as stored in the header
1332  *         (NOT the memory space necessary to hold the Pixels 
1333  *          -in case of embeded compressed image-)
1334  *         0 : NOT USABLE file. The caller has to check.
1335  */
1336 size_t File::GetPixelAreaLength()
1337 {
1338    DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1339    if ( pxlElement )
1340    {
1341       return pxlElement->GetLength();
1342    }
1343    else
1344    {
1345       gdcmWarningMacro( "Big trouble : Pixel Element ("
1346                       << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1347       return 0;
1348    }
1349 }
1350
1351 /**
1352  * \brief Adds the characteristics of a new element we want to anonymize
1353  * @param   group  Group number of the target tag.
1354  * @param   elem Element number of the target tag.
1355  * @param   value new value (string) to substitute with 
1356  */
1357 void File::AddAnonymizeElement (uint16_t group, uint16_t elem, 
1358                                 std::string const &value) 
1359
1360    DicomElement el;
1361    el.Group = group;
1362    el.Elem  = elem;
1363    el.Value = value;
1364    UserAnonymizeList.push_back(el); 
1365 }
1366
1367 /**
1368  * \brief Overwrites in the file the values of the DicomElements
1369  *       held in the list 
1370  */
1371 void File::AnonymizeNoLoad()
1372 {
1373    std::fstream *fp = new std::fstream(Filename.c_str(), 
1374                               std::ios::in | std::ios::out | std::ios::binary); 
1375    gdcm::DocEntry *d;
1376    uint32_t offset;
1377    uint32_t lgth;
1378    uint32_t valLgth = 0;
1379    std::string *spaces;
1380    for (ListElements::iterator it = UserAnonymizeList.begin();  
1381                                it != UserAnonymizeList.end();
1382                              ++it)
1383    { 
1384       d = GetDocEntry( (*it).Group, (*it).Elem);
1385
1386       if ( d == NULL)
1387          continue;
1388
1389       if ( dynamic_cast<SeqEntry *>(d) )
1390       {
1391          gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1392          continue;
1393       }
1394
1395       offset = d->GetOffset();
1396       lgth =   d->GetLength();
1397       if (valLgth < lgth)
1398       {
1399          spaces = new std::string( lgth-valLgth, ' ');
1400          (*it).Value = (*it).Value + *spaces;
1401          delete spaces;
1402       }
1403       fp->seekp( offset, std::ios::beg );
1404       fp->write( (*it).Value.c_str(), lgth );
1405      
1406    }
1407    fp->close();
1408    delete fp;
1409 }
1410
1411 /**
1412  * \brief anonymize a File (remove Patient's personal info passed with
1413  *        AddAnonymizeElement()
1414  * \note You cannot Anonymize a DataEntry (to be fixed)
1415  */
1416 bool File::AnonymizeFile()
1417 {
1418    // If Anonymisation list is empty, let's perform some basic anonymization
1419    if ( UserAnonymizeList.begin() == UserAnonymizeList.end() )
1420    {
1421       // If exist, replace by spaces
1422       SetEntryString("  ",0x0010, 0x2154); // Telephone   
1423       SetEntryString("  ",0x0010, 0x1040); // Adress
1424       SetEntryString("  ",0x0010, 0x0020); // Patient ID
1425
1426       DocEntry *patientNameHE = GetDocEntry (0x0010, 0x0010);
1427   
1428       if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1429       {
1430          std::string studyInstanceUID =  GetEntryString (0x0020, 0x000d);
1431          if ( studyInstanceUID != GDCM_UNFOUND )
1432          {
1433             SetEntryString(studyInstanceUID, 0x0010, 0x0010);
1434          }
1435          else
1436          {
1437             SetEntryString("anonymized", 0x0010, 0x0010);
1438          }
1439       }
1440    }
1441    else
1442    {
1443       gdcm::DocEntry *d;
1444       for (ListElements::iterator it = UserAnonymizeList.begin();  
1445                                   it != UserAnonymizeList.end();
1446                                 ++it)
1447       {  
1448          d = GetDocEntry( (*it).Group, (*it).Elem);
1449
1450          if ( d == NULL)
1451             continue;
1452
1453          if ( dynamic_cast<SeqEntry *>(d) )
1454          {
1455             gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1456             continue;
1457          }
1458
1459          if ( dynamic_cast<DataEntry *>(d) )
1460          {
1461             gdcmWarningMacro( "To 'Anonymize' a DataEntry, better use AnonymizeNoLoad (FIXME) ");
1462             continue;
1463          }
1464          else
1465             SetEntryString ((*it).Value, (*it).Group, (*it).Elem);
1466       }
1467 }
1468
1469   // In order to make definitively impossible any further identification
1470   // remove or replace all the stuff that contains a Date
1471
1472 //0008 0012 DA ID Instance Creation Date
1473 //0008 0020 DA ID Study Date
1474 //0008 0021 DA ID Series Date
1475 //0008 0022 DA ID Acquisition Date
1476 //0008 0023 DA ID Content Date
1477 //0008 0024 DA ID Overlay Date
1478 //0008 0025 DA ID Curve Date
1479 //0008 002a DT ID Acquisition Datetime
1480 //0018 9074 DT ACQ Frame Acquisition Datetime
1481 //0018 9151 DT ACQ Frame Reference Datetime
1482 //0018 a002 DT ACQ Contribution Date Time
1483 //0020 3403 SH REL Modified Image Date (RET)
1484 //0032 0032 DA SDY Study Verified Date
1485 //0032 0034 DA SDY Study Read Date
1486 //0032 1000 DA SDY Scheduled Study Start Date
1487 //0032 1010 DA SDY Scheduled Study Stop Date
1488 //0032 1040 DA SDY Study Arrival Date
1489 //0032 1050 DA SDY Study Completion Date
1490 //0038 001a DA VIS Scheduled Admission Date
1491 //0038 001c DA VIS Scheduled Discharge Date
1492 //0038 0020 DA VIS Admitting Date
1493 //0038 0030 DA VIS Discharge Date
1494 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1495 //0040 0004 DA PRC Scheduled Procedure Step End Date
1496 //0040 0244 DA PRC Performed Procedure Step Start Date
1497 //0040 0250 DA PRC Performed Procedure Step End Date
1498 //0040 2004 DA PRC Issue Date of Imaging Service Request
1499 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1500 //0040 4011 DT PRC Expected Completion Date and Time
1501 //0040 a030 DT PRC Verification Date Time
1502 //0040 a032 DT PRC Observation Date Time
1503 //0040 a120 DT PRC DateTime
1504 //0040 a121 DA PRC Date
1505 //0040 a13a DT PRC Referenced Datetime
1506 //0070 0082 DA ??? Presentation Creation Date
1507 //0100 0420 DT ??? SOP Autorization Date and Time
1508 //0400 0105 DT ??? Digital Signature DateTime
1509 //2100 0040 DA PJ Creation Date
1510 //3006 0008 DA SSET Structure Set Date
1511 //3008 0024 DA ??? Treatment Control Point Date
1512 //3008 0054 DA ??? First Treatment Date
1513 //3008 0056 DA ??? Most Recent Treatment Date
1514 //3008 0162 DA ??? Safe Position Exit Date
1515 //3008 0166 DA ??? Safe Position Return Date
1516 //3008 0250 DA ??? Treatment Date
1517 //300a 0006 DA RT RT Plan Date
1518 //300a 022c DA RT Air Kerma Rate Reference Date
1519 //300e 0004 DA RT Review Date
1520
1521    return true;
1522 }
1523
1524 /**
1525  * \brief Performs some consistency checking on various 'File related' 
1526  *       (as opposed to 'DicomDir related') entries 
1527  *       then writes in a file all the (Dicom Elements) included the Pixels 
1528  * @param fileName file name to write to
1529  * @param writetype type of the file to be written 
1530  *          (ACR, ExplicitVR, ImplicitVR)
1531  */
1532 bool File::Write(std::string fileName, FileType writetype)
1533 {
1534    std::ofstream *fp = new std::ofstream(fileName.c_str(), 
1535                                          std::ios::out | std::ios::binary);
1536    if (*fp == NULL)
1537    {
1538       gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1539       return false;
1540    }
1541
1542    // Entry : 0002|0000 = group length -> recalculated
1543    DataEntry *e0000 = GetDataEntry(0x0002,0x0000);
1544    if ( e0000 )
1545    {
1546       std::ostringstream sLen;
1547       sLen << ComputeGroup0002Length( );
1548       e0000->SetString(sLen.str());
1549    }
1550
1551    /// \todo FIXME : Derma?.dcm does not have it...let's remove it ?!? JPRx
1552    if( writetype != JPEG )
1553    {
1554       int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1555       if (i_lgPix != -2)
1556       {
1557          // no (GrPixel, NumPixel) element
1558          std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1559          s_lgPix = Util::DicomString( s_lgPix.c_str() );
1560          InsertEntryString(s_lgPix,GrPixel, 0x0000, "UL");   
1561       }
1562    }
1563    Document::WriteContent(fp, writetype);
1564
1565    fp->close();
1566    delete fp;
1567
1568    return true;
1569 }
1570
1571 //-----------------------------------------------------------------------------
1572 // Protected
1573
1574
1575 //-----------------------------------------------------------------------------
1576 // Private
1577 /**
1578  * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1579  *        Compute the RLE extra information and store it in \ref RLEInfo
1580  *        for later pixel retrieval usage.
1581  */
1582 void File::ComputeRLEInfo()
1583 {
1584    std::string ts = GetTransferSyntax();
1585    if ( !Global::GetTS()->IsRLELossless(ts) ) 
1586    {
1587       return;
1588    }
1589
1590    // Encoded pixel data: for the time being we are only concerned with
1591    // Jpeg or RLE Pixel data encodings.
1592    // As stated in PS 3.5-2003, section 8.2 p44:
1593    // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1594    //  value representation OB is used".
1595    // Hence we expect an OB value representation. Concerning OB VR,
1596    // the section PS 3.5-2003, section A.4.c p 58-59, states:
1597    // "For the Value Representations OB and OW, the encoding shall meet the
1598    //   following specifications depending on the Data element tag:"
1599    //   [...snip...]
1600    //    - the first item in the sequence of items before the encoded pixel
1601    //      data stream shall be basic offset table item. The basic offset table
1602    //      item value, however, is not required to be present"
1603    ReadEncapsulatedBasicOffsetTable();
1604
1605    // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1606    // Loop on the individual frame[s] and store the information
1607    // on the RLE fragments in a RLEFramesInfo.
1608    // Note: - when only a single frame is present, this is a
1609    //         classical image.
1610    //       - when more than one frame are present, then we are in 
1611    //         the case of a multi-frame image.
1612    long frameLength;
1613    int i=0;
1614    uint32_t sum = 0;
1615    while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1616    { 
1617       // Since we have read the basic offset table, let's check the value were correct
1618       // or else produce a warning:
1619       if ( BasicOffsetTableItemValue )
1620         {
1621         // If a BasicOffsetTableItemValue was read
1622         uint32_t individualLength = BasicOffsetTableItemValue[i];
1623         assert( individualLength == sum ); // REMOVE that if this is a problem
1624         if( individualLength != sum )
1625           {
1626           gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght" );
1627           }
1628         sum += frameLength + 8;
1629         i++;
1630         }
1631       // Parse the RLE Header and store the corresponding RLE Segment
1632       // Offset Table information on fragments of this current Frame.
1633       // Note that the fragment pixels themselves are not loaded
1634       // (but just skipped).
1635       long frameOffset = Fp->tellg(); // once per fragment
1636
1637       uint32_t nbRleSegments = ReadInt32();
1638       if ( nbRleSegments > 16 )
1639       {
1640          // There should be at most 15 segments (refer to RLEFrame class)
1641          gdcmWarningMacro( "Too many segments.");
1642       }
1643  
1644       uint32_t rleSegmentOffsetTable[16];
1645       for( int k = 1; k <= 15; k++ )
1646       {
1647          rleSegmentOffsetTable[k] = ReadInt32();
1648       }
1649
1650       // Deduce from both RLE Header and frameLength 
1651       // the fragment length, and again store this info
1652       // in a RLEFramesInfo.
1653       long rleSegmentLength[15];
1654       // skipping (not reading) RLE Segments
1655       if ( nbRleSegments > 1)
1656       {
1657          for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1658          {
1659              rleSegmentLength[k] =  rleSegmentOffsetTable[k+1]
1660                                   - rleSegmentOffsetTable[k];
1661              SkipBytes(rleSegmentLength[k]);
1662           }
1663        }
1664
1665        rleSegmentLength[nbRleSegments] = frameLength 
1666                                       - rleSegmentOffsetTable[nbRleSegments];
1667        SkipBytes(rleSegmentLength[nbRleSegments]);
1668
1669        // Store the collected info
1670        RLEFrame *newFrame = new RLEFrame;
1671        newFrame->SetNumberOfFragments(nbRleSegments);
1672        for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1673        {
1674           newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1675           newFrame->SetLength(uk,rleSegmentLength[uk]);
1676        }
1677        RLEInfo->AddFrame(newFrame);
1678    }
1679
1680    // Make sure that  we encounter a 'Sequence Delimiter Item'
1681    // at the end of the item :
1682    if ( !ReadTag(0xfffe, 0xe0dd) ) // once per RLE File
1683    {
1684       gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1685    }
1686 }
1687
1688 /**
1689  * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1690  *        Compute the jpeg extra information (fragment[s] offset[s] and
1691  *        length) and store it[them] in \ref JPEGInfo for later pixel
1692  *        retrieval usage.
1693  */
1694 void File::ComputeJPEGFragmentInfo()
1695 {
1696    // If you need to, look for comments of ComputeRLEInfo().
1697    std::string ts = GetTransferSyntax();
1698    if ( ! Global::GetTS()->IsJPEG(ts) )
1699    {
1700       return;
1701    }
1702
1703    ReadEncapsulatedBasicOffsetTable();
1704
1705    // Loop on the fragments[s] and store the parsed information in a
1706    // JPEGInfo.
1707    long fragmentLength;
1708    int i=0;
1709    uint32_t sum = 0;
1710    while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1711    { 
1712       // Since we have read the basic offset table, let's check the value were correct
1713       // or else produce a warning:
1714       // A.4 Transfer syntaxes for encapsulation of encoded pixel data:
1715       // When the Item Value is present, the Basic Offset Table Item Value shall contain
1716       // concatenated 32-bit unsigned integer values that are byte offsets to the first
1717       // byte of the Item Tag of the first fragment for each frame in the Sequence of
1718       // Items. These offsets are measured from the first byte of the first Item Tag
1719       // following the Basic Offset Table item (See Table A.4-2).
1720
1721       if ( BasicOffsetTableItemValue )
1722         {
1723         // If a BasicOffsetTableItemValue was read
1724         uint32_t individualLength = BasicOffsetTableItemValue[i];
1725         //assert( individualLength == sum ); // Seems like 00191113.dcm is off by one ??
1726         if( individualLength != sum )
1727           {
1728           gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght:" <<
1729               individualLength << " != " << sum );
1730           }
1731         sum += fragmentLength + 8;
1732         i++;
1733         }
1734
1735       long fragmentOffset = Fp->tellg(); // Once per fragment
1736       // Store the collected info
1737       JPEGFragment *newFragment = new JPEGFragment;
1738       newFragment->SetOffset(fragmentOffset);
1739       newFragment->SetLength(fragmentLength);
1740       JPEGInfo->AddFragment(newFragment);
1741
1742       SkipBytes(fragmentLength);
1743    }
1744
1745    // Make sure that  we encounter a 'Sequence Delimiter Item'
1746    // at the end of the item :
1747    if ( !ReadTag(0xfffe, 0xe0dd) )
1748    {
1749       gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1750    }
1751 }
1752
1753 /**
1754  * \brief   Assuming the internal file pointer \ref Document::Fp 
1755  *          is placed at the beginning of a tag, check whether this
1756  *          tag is (TestGroup, TestElem).
1757  * \warning On success the internal file pointer \ref Document::Fp
1758  *          is modified to point after the tag.
1759  *          On failure (i.e. when the tag wasn't the expected tag
1760  *          (TestGroup, TestElem) the internal file pointer
1761  *          \ref Document::Fp is restored to it's original position.
1762  * @param   testGroup The expected group   of the tag.
1763  * @param   testElem  The expected Element of the tag.
1764  * @return  True on success, false otherwise.
1765  */
1766 bool File::ReadTag(uint16_t testGroup, uint16_t testElem)
1767 {
1768    long positionOnEntry = Fp->tellg(); // Only when reading fragments
1769    //long currentPosition = positionOnEntry;      // On debugging purposes
1770
1771    // Read the Item Tag group and element, and make
1772    // sure they are what we expected:
1773    uint16_t itemTagGroup;
1774    uint16_t itemTagElem;
1775    try
1776    {
1777       itemTagGroup = ReadInt16();
1778       itemTagElem  = ReadInt16();
1779    }
1780    catch ( FormatError )
1781    {
1782       gdcmErrorMacro( "Can not read tag for "
1783        << "   We should have found tag ("
1784        << DictEntry::TranslateToKey(testGroup,testElem) << ")"
1785        ) ;
1786
1787       return false;
1788    }
1789    if ( itemTagGroup != testGroup || itemTagElem != testElem )
1790    {
1791        // in order not to pollute output we don't warn on 'delimitors'
1792       if (itemTagGroup != 0xfffe ||  testGroup != 0xfffe )
1793          gdcmWarningMacro( "Wrong Item Tag found:"
1794           << "   We should have found tag ("
1795           << DictEntry::TranslateToKey(testGroup,testElem) << ")" << std::endl
1796           << "   but instead we encountered tag ("
1797           << DictEntry::TranslateToKey(itemTagGroup,itemTagElem) << ")"
1798           << "  at address: " << "  0x(" << std::hex 
1799           << (unsigned int)positionOnEntry  << std::dec << ")" 
1800           ) ;
1801       Fp->seekg(positionOnEntry, std::ios::beg);
1802
1803       return false;
1804    }
1805    return true;
1806 }
1807
1808 /**
1809  * \brief   Assuming the internal file pointer \ref Document::Fp 
1810  *          is placed at the beginning of a tag (TestGroup, TestElement),
1811  *          read the length associated to the Tag.
1812  * \warning On success the internal file pointer \ref Document::Fp
1813  *          is modified to point after the tag and it's length.
1814  *          On failure (i.e. when the tag wasn't the expected tag
1815  *          (TestGroup, TestElement) the internal file pointer
1816  *          \ref Document::Fp is restored to it's original position.
1817  * @param   testGroup The expected Group   of the tag.
1818  * @param   testElem  The expected Element of the tag.
1819  * @return  On success returns the length associated to the tag. On failure
1820  *          returns 0.
1821  */
1822 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElem)
1823 {
1824
1825    if ( !ReadTag(testGroup, testElem) )
1826    {
1827       // Avoid polutting output
1828       if ( testGroup != 0xfffe ) 
1829          gdcmErrorMacro( "ReadTag did not succeed for ("
1830                     << DictEntry::TranslateToKey(testGroup,testElem) 
1831                     << ")..." );
1832       return 0;
1833    }
1834                                                                                 
1835    //// Then read the associated Item Length
1836    
1837    // long currentPosition = Fp->tellg(); // save time // JPRx
1838    uint32_t itemLength  = ReadInt32();
1839    gdcmDebugMacro( "Basic Item Length is: " << itemLength 
1840 //        << "  at address: " << std::hex << (unsigned int)currentPosition
1841    );
1842    return itemLength;
1843 }
1844
1845 /**
1846  * \brief When parsing the Pixel Data of an encapsulated file, read
1847  *        the basic offset table (when present, and BTW dump it).
1848  */
1849 void File::ReadEncapsulatedBasicOffsetTable()
1850 {
1851    //// Read the Basic Offset Table Item Tag length...
1852    uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
1853
1854    // When present, read the basic offset table itself.
1855    // Notes: - since the presence of this basic offset table is optional
1856    //          we can't rely on it for the implementation, and we will simply
1857    //          trash it's content (when present).
1858    //        - still, when present, we could add some further checks on the
1859    //          lengths, but we won't bother with such fuses for the time being.
1860    if ( itemLength != 0 )
1861    {
1862       char *charBasicOffsetTableItemValue = new char[itemLength];
1863       Fp->read(charBasicOffsetTableItemValue, itemLength);
1864       unsigned int nbEntries = itemLength/4;
1865       assert( nbEntries*4 == itemLength); // Make sure this is a multiple
1866       BasicOffsetTableItemValue = new uint32_t[nbEntries];
1867
1868       for (unsigned int i=0; i < nbEntries; i++ )
1869       {
1870          BasicOffsetTableItemValue[i] = *((uint32_t*)(&charBasicOffsetTableItemValue[4*i]));
1871 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
1872          uint32_t val = BasicOffsetTableItemValue[i];
1873          BasicOffsetTableItemValue[i] 
1874            = (  (val<<24)               | ((val<<8)  & 0x00ff0000) | 
1875               ( (val>>8)  & 0x0000ff00) |  (val>>24)               );
1876 #endif
1877          gdcmDebugMacro( "Read one length for: " << 
1878                           std::hex << BasicOffsetTableItemValue[i] );
1879       }
1880
1881       delete[] charBasicOffsetTableItemValue;
1882    }
1883 }
1884
1885 // These are the deprecated method that one day should be removed (after the next release)
1886
1887 #ifndef GDCM_LEGACY_REMOVE
1888 /*
1889  * \ brief   Loader. (DEPRECATED :  temporaryly kept not to break the API)
1890  * @ param   fileName file to be open for parsing
1891  * @ return false if file cannot be open or no swap info was found,
1892  *         or no tag was found.
1893  * @deprecated Use the Load() [ + SetLoadMode() ] + SetFileName() functions instead
1894  */
1895 bool File::Load( std::string const &fileName ) 
1896 {
1897    GDCM_LEGACY_REPLACED_BODY(File::Load(std::string), "1.2",
1898                              File::Load());
1899    SetFileName( fileName );
1900    if ( ! this->Document::Load( ) )
1901       return false;
1902
1903    return DoTheLoadingJob( );
1904 }
1905 #endif
1906
1907 //-----------------------------------------------------------------------------
1908 // Print
1909
1910 //-----------------------------------------------------------------------------
1911 } // end namespace gdcm