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