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