]> 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/06 15:32:13 $
7   Version:   $Revision: 1.267 $
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   * (needed to organize DICOM files based on their x,y,z position)
758   * @param iop adress of the (6)float array to receive values
759   * @return cosines of image orientation patient
760   */
761 bool File::GetImageOrientationPatient( float iop[6] )
762 {
763    std::string strImOriPat;
764    //iop is supposed to be float[6]
765    iop[0] = iop[1] = iop[2] = iop[3] = iop[4] = iop[5] = 0.;
766
767    // 0020 0037 DS REL Image Orientation (Patient)
768    if ( (strImOriPat = GetEntryValue(0x0020,0x0037)) != GDCM_UNFOUND )
769    {
770       if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ", 
771           &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
772       {
773          gdcmWarningMacro( "Wrong Image Orientation Patient (0020,0037). Less than 6 values were found." );
774          return false;
775       }
776    }
777    //For ACR-NEMA
778    // 0020 0035 DS REL Image Orientation (RET)
779    else if ( (strImOriPat = GetEntryValue(0x0020,0x0035)) != GDCM_UNFOUND )
780    {
781       if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ", 
782           &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
783       {
784          gdcmWarningMacro( "wrong Image Orientation Patient (0020,0035). Less than 6 values were found." );
785          return false;
786       }
787    }
788    return true;
789 }
790
791 /**
792  * \brief   Retrieve the number of Bits Stored (actually used)
793  *          (as opposed to number of Bits Allocated)
794  * @return  The encountered number of Bits Stored, 0 by default.
795  *          0 means the file is NOT USABLE. The caller has to check it !
796  */
797 int File::GetBitsStored()
798 {
799    std::string strSize = GetEntryValue( 0x0028, 0x0101 );
800    if ( strSize == GDCM_UNFOUND )
801    {
802       gdcmWarningMacro("(0028,0101) is supposed to be mandatory");
803       return 0;  // It's supposed to be mandatory
804                  // the caller will have to check
805    }
806    return atoi( strSize.c_str() );
807 }
808
809 /**
810  * \brief   Retrieve the number of Bits Allocated
811  *          (8, 12 -compacted ACR-NEMA files-, 16, 24 -old RGB ACR-NEMA files-,)
812  * @return  The encountered Number of Bits Allocated, 0 by default.
813  *          0 means the file is NOT USABLE. The caller has to check it !
814  */
815 int File::GetBitsAllocated()
816 {
817    std::string strSize = GetEntryValue(0x0028,0x0100);
818    if ( strSize == GDCM_UNFOUND  )
819    {
820       gdcmWarningMacro( "(0028,0100) is supposed to be mandatory");
821       return 0; // It's supposed to be mandatory
822                 // the caller will have to check
823    }
824    return atoi( strSize.c_str() );
825 }
826
827 /**
828  * \brief   Retrieve the high bit position.
829  * \warning The method defaults to 0 when information is missing.
830  *          The responsability of checking this value is left to the caller.
831  * @return  The high bit position when present. 0 when missing.
832  */
833 int File::GetHighBitPosition()
834 {
835    std::string strSize = GetEntryValue( 0x0028, 0x0102 );
836    if ( strSize == GDCM_UNFOUND )
837    {
838       gdcmWarningMacro( "(0028,0102) is supposed to be mandatory");
839       return 0;
840    }
841    return atoi( strSize.c_str() );
842 }
843
844 /**
845  * \brief   Retrieve the number of Samples Per Pixel
846  *          (1 : gray level, 3 : RGB/YBR -1 or 3 Planes-)
847  * @return  The encountered number of Samples Per Pixel, 1 by default.
848  *          (we assume Gray level Pixels)
849  */
850 int File::GetSamplesPerPixel()
851 {
852    const std::string &strSize = GetEntryValue(0x0028,0x0002);
853    if ( strSize == GDCM_UNFOUND )
854    {
855       gdcmWarningMacro( "(0028,0002) is supposed to be mandatory");
856       return 1; // Well, it's supposed to be mandatory ...
857                 // but sometimes it's missing : *we* assume Gray pixels
858    }
859    return atoi( strSize.c_str() );
860 }
861
862 /**
863  * \brief   Retrieve the Planar Configuration for RGB images
864  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
865  * @return  The encountered Planar Configuration, 0 by default.
866  */
867 int File::GetPlanarConfiguration()
868 {
869    std::string strSize = GetEntryValue(0x0028,0x0006);
870    if ( strSize == GDCM_UNFOUND )
871    {
872       gdcmWarningMacro( "Not found : Planar Configuration (0028,0006)");
873       return 0;
874    }
875    return atoi( strSize.c_str() );
876 }
877
878 /**
879  * \brief   Return the size (in bytes) of a single pixel of data.
880  * @return  The size in bytes of a single pixel of data; 0 by default
881  *          0 means the file is NOT USABLE; the caller will have to check
882  */
883 int File::GetPixelSize()
884 {
885    // 0028 0100 US IMG Bits Allocated
886    // (in order no to be messed up by old ACR-NEMA RGB images)
887    //   if (File::GetEntryValue(0x0028,0x0100) == "24")
888    //      return 3;
889
890    std::string pixelType = GetPixelType();
891    if ( pixelType ==  "8U" || pixelType == "8S" )
892    {
893       return 1;
894    }
895    if ( pixelType == "16U" || pixelType == "16S")
896    {
897       return 2;
898    }
899    if ( pixelType == "32U" || pixelType == "32S")
900    {
901       return 4;
902    }
903    if ( pixelType == "FD" )
904    {
905       return 8;
906    }
907    gdcmWarningMacro( "Unknown pixel type");
908    return 0;
909 }
910
911 /**
912  * \brief   Build the Pixel Type of the image.
913  *          Possible values are:
914  *          - 8U  unsigned  8 bit,
915  *          - 8S    signed  8 bit,
916  *          - 16U unsigned 16 bit,
917  *          - 16S   signed 16 bit,
918  *          - 32U unsigned 32 bit,
919  *          - 32S   signed 32 bit,
920  *          - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
921  * \warning 12 bit images appear as 16 bit.
922  *          24 bit images appear as 8 bit + photochromatic interp ="RGB "
923  *                                        + Planar Configuration = 0
924  * @return  0S if nothing found. NOT USABLE file. The caller has to check
925  */
926 std::string File::GetPixelType()
927 {
928    std::string bitsAlloc = GetEntryValue(0x0028, 0x0100); // Bits Allocated
929    if ( bitsAlloc == GDCM_UNFOUND )
930    {
931       gdcmWarningMacro( "Missing  Bits Allocated (0028,0100)");
932       bitsAlloc = "16"; // default and arbitrary value, not to polute the output
933    }
934
935    if ( bitsAlloc == "64" )
936    {
937       return "FD";
938    }
939    else if ( bitsAlloc == "12" )
940    {
941       // It will be unpacked
942       bitsAlloc = "16";
943    }
944    else if ( bitsAlloc == "24" )
945    {
946       // (in order no to be messed up by old RGB images)
947       bitsAlloc = "8";
948    }
949
950    std::string sign = GetEntryValue(0x0028, 0x0103);//"Pixel Representation"
951
952    if (sign == GDCM_UNFOUND )
953    {
954       gdcmWarningMacro( "Missing Pixel Representation (0028,0103)");
955       sign = "U"; // default and arbitrary value, not to polute the output
956    }
957    else if ( sign == "0" )
958    {
959       sign = "U";
960    }
961    else
962    {
963       sign = "S";
964    }
965    return bitsAlloc + sign;
966 }
967
968 /**
969  * \brief   Check whether the pixels are signed (1) or UNsigned (0) data.
970  * \warning The method defaults to false (UNsigned) when tag 0028|0103
971  *          is missing.
972  *          The responsability of checking this value is left to the caller
973  *          (NO transformation is performed on the pixels to make then >0)
974  * @return  True when signed, false when UNsigned
975  */
976 bool File::IsSignedPixelData()
977 {
978    std::string strSign = GetEntryValue( 0x0028, 0x0103 );
979    if ( strSign == GDCM_UNFOUND )
980    {
981       gdcmWarningMacro( "(0028,0103) is supposed to be mandatory");
982       return false;
983    }
984    int sign = atoi( strSign.c_str() );
985    if ( sign == 0 ) 
986    {
987       return false;
988    }
989    return true;
990 }
991
992 /**
993  * \brief   Check whether this a monochrome picture (gray levels) or not,
994  *          using "Photometric Interpretation" tag (0x0028,0x0004).
995  * @return  true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
996  */
997 bool File::IsMonochrome()
998 {
999    const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1000    if (  Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
1001       || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
1002    {
1003       return true;
1004    }
1005    if ( PhotometricInterp == GDCM_UNFOUND )
1006    {
1007       gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1008    }
1009    return false;
1010 }
1011
1012 /**
1013  * \brief   Check whether this a MONOCHROME1 picture (high values = dark)
1014  *            or not using "Photometric Interpretation" tag (0x0028,0x0004).
1015  * @return  true when "MONOCHROME1" . False otherwise.
1016  */
1017 bool File::IsMonochrome1()
1018 {
1019    const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1020    if (  Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
1021    {
1022       return true;
1023    }
1024    if ( PhotometricInterp == GDCM_UNFOUND )
1025    {
1026       gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1027    }
1028    return false;
1029 }
1030
1031 /**
1032  * \brief   Check whether this a "PALETTE COLOR" picture or not by accessing
1033  *          the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1034  * @return  true when "PALETTE COLOR". False otherwise.
1035  */
1036 bool File::IsPaletteColor()
1037 {
1038    std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1039    if (   PhotometricInterp == "PALETTE COLOR " )
1040    {
1041       return true;
1042    }
1043    if ( PhotometricInterp == GDCM_UNFOUND )
1044    {
1045       gdcmWarningMacro( "Not found : Palette color (0028,0004)");
1046    }
1047    return false;
1048 }
1049
1050 /**
1051  * \brief   Check whether this a "YBR_FULL" color picture or not by accessing
1052  *          the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1053  * @return  true when "YBR_FULL". False otherwise.
1054  */
1055 bool File::IsYBRFull()
1056 {
1057    std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1058    if (   PhotometricInterp == "YBR_FULL" )
1059    {
1060       return true;
1061    }
1062    if ( PhotometricInterp == GDCM_UNFOUND )
1063    {
1064       gdcmWarningMacro( "Not found : YBR Full (0028,0004)");
1065    }
1066    return false;
1067 }
1068
1069 /**
1070   * \brief tells us if LUT are used
1071   * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1072   *          are NOT considered as LUT, since nobody knows
1073   *          how to deal with them
1074   *          Please warn me if you know sbdy that *does* know ... jprx
1075   * @return true if LUT Descriptors and LUT Tables were found 
1076   */
1077 bool File::HasLUT()
1078 {
1079    // Check the presence of the LUT Descriptors, and LUT Tables    
1080    // LutDescriptorRed    
1081    if ( !GetDocEntry(0x0028,0x1101) )
1082    {
1083       return false;
1084    }
1085    // LutDescriptorGreen 
1086    if ( !GetDocEntry(0x0028,0x1102) )
1087    {
1088       return false;
1089    }
1090    // LutDescriptorBlue 
1091    if ( !GetDocEntry(0x0028,0x1103) )
1092    {
1093       return false;
1094    }
1095    // Red Palette Color Lookup Table Data
1096    if ( !GetDocEntry(0x0028,0x1201) )
1097    {
1098       return false;
1099    }
1100    // Green Palette Color Lookup Table Data       
1101    if ( !GetDocEntry(0x0028,0x1202) )
1102    {
1103       return false;
1104    }
1105    // Blue Palette Color Lookup Table Data      
1106    if ( !GetDocEntry(0x0028,0x1203) )
1107    {
1108       return false;
1109    }
1110
1111    // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1112    //         NOT taken into account, but we don't know how to use it ...   
1113    return true;
1114 }
1115
1116 /**
1117   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1118   *             else 0
1119   * @return Lookup Table number of Bits , 0 by default
1120   *          when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1121   * @ return bit number of each LUT item 
1122   */
1123 int File::GetLUTNbits()
1124 {
1125    std::vector<std::string> tokens;
1126    int lutNbits;
1127
1128    //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1129    //                                = Lookup Table Desc-Blue
1130    // Consistency already checked in GetLUTLength
1131    std::string lutDescription = GetEntryValue(0x0028,0x1101);
1132    if ( lutDescription == GDCM_UNFOUND )
1133    {
1134       return 0;
1135    }
1136
1137    tokens.clear(); // clean any previous value
1138    Util::Tokenize ( lutDescription, tokens, "\\" );
1139    //LutLength=atoi(tokens[0].c_str());
1140    //LutDepth=atoi(tokens[1].c_str());
1141
1142    lutNbits = atoi( tokens[2].c_str() );
1143    tokens.clear();
1144
1145    return lutNbits;
1146 }
1147
1148 /**
1149  *\brief gets the info from 0028,1052 : Rescale Intercept
1150  * @return Rescale Intercept
1151  */
1152 float File::GetRescaleIntercept()
1153 {
1154    float resInter = 0.;
1155    /// 0028 1052 DS IMG Rescale Intercept
1156    const std::string &strRescInter = GetEntryValue(0x0028,0x1052);
1157    if ( strRescInter != GDCM_UNFOUND )
1158    {
1159       if ( sscanf( strRescInter.c_str(), "%f ", &resInter) != 1 )
1160       {
1161          // bug in the element 0x0028,0x1052
1162          gdcmWarningMacro( "Rescale Intercept (0028,1052) is empty." );
1163       }
1164    }
1165
1166    return resInter;
1167 }
1168
1169 /**
1170  *\brief   gets the info from 0028,1053 : Rescale Slope
1171  * @return Rescale Slope
1172  */
1173 float File::GetRescaleSlope()
1174 {
1175    float resSlope = 1.;
1176    //0028 1053 DS IMG Rescale Slope
1177    std::string strRescSlope = GetEntryValue(0x0028,0x1053);
1178    if ( strRescSlope != GDCM_UNFOUND )
1179    {
1180       if ( sscanf( strRescSlope.c_str(), "%f ", &resSlope) != 1 )
1181       {
1182          // bug in the element 0x0028,0x1053
1183          gdcmWarningMacro( "Rescale Slope (0028,1053) is empty.");
1184       }
1185    }
1186
1187    return resSlope;
1188 }
1189
1190 /**
1191  * \brief This function is intended to user who doesn't want 
1192  *   to have to manage a LUT and expects to get an RBG Pixel image
1193  *   (or a monochrome one ...) 
1194  * \warning to be used with GetImagePixels()
1195  * @return 1 if Gray level, 3 if Color (RGB, YBR, *or PALETTE COLOR*)
1196  */
1197 int File::GetNumberOfScalarComponents()
1198 {
1199    if ( GetSamplesPerPixel() == 3 )
1200    {
1201       return 3;
1202    }
1203       
1204    // 0028 0100 US IMG Bits Allocated
1205    // (in order no to be messed up by old RGB images)
1206    if ( GetEntryValue(0x0028,0x0100) == "24" )
1207    {
1208       return 3;
1209    }
1210        
1211    std::string strPhotometricInterpretation = GetEntryValue(0x0028,0x0004);
1212
1213    if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1214    {
1215       if ( HasLUT() )// PALETTE COLOR is NOT enough
1216       {
1217          return 3;
1218       }
1219       else
1220       {
1221          return 1;
1222       }
1223    }
1224
1225    // beware of trailing space at end of string      
1226    // DICOM tags are never of odd length
1227    if ( strPhotometricInterpretation == GDCM_UNFOUND   || 
1228         Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1229         Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1230    {
1231       return 1;
1232    }
1233    else
1234    {
1235       // we assume that *all* kinds of YBR are dealt with
1236       return 3;
1237    }
1238 }
1239
1240 /**
1241  * \brief This function is intended to user that DOESN'T want 
1242  *  to get RGB pixels image when it's stored as a PALETTE COLOR image
1243  *   - the (vtk) user is supposed to know how deal with LUTs - 
1244  * \warning to be used with GetImagePixelsRaw()
1245  * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1246  */
1247 int File::GetNumberOfScalarComponentsRaw()
1248 {
1249    // 0028 0100 US IMG Bits Allocated
1250    // (in order no to be messed up by old RGB images)
1251    if ( File::GetEntryValue(0x0028,0x0100) == "24" )
1252    {
1253       return 3;
1254    }
1255
1256    // we assume that *all* kinds of YBR are dealt with
1257    return GetSamplesPerPixel();
1258 }
1259
1260 /**
1261  * \brief   Recover the offset (from the beginning of the file) 
1262  *          of *image* pixels (not *icone image* pixels, if any !)
1263  * @return Pixel Offset
1264  */
1265 size_t File::GetPixelOffset()
1266 {
1267    DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1268    if ( pxlElement )
1269    {
1270       return pxlElement->GetOffset();
1271    }
1272    else
1273    {
1274       gdcmDebugMacro( "Big trouble : Pixel Element ("
1275                       << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1276       return 0;
1277    }
1278 }
1279
1280 /**
1281  * \brief   Recover the pixel area length (in Bytes)
1282  * @return Pixel Element Length, as stored in the header
1283  *         (NOT the memory space necessary to hold the Pixels 
1284  *          -in case of embeded compressed image-)
1285  *         0 : NOT USABLE file. The caller has to check.
1286  */
1287 size_t File::GetPixelAreaLength()
1288 {
1289    DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1290    if ( pxlElement )
1291    {
1292       return pxlElement->GetLength();
1293    }
1294    else
1295    {
1296       gdcmDebugMacro( "Big trouble : Pixel Element ("
1297                       << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1298       return 0;
1299    }
1300 }
1301
1302 /**
1303  * \brief Adds the characteristics of a new element we want to anonymize
1304  * @param   group  Group number of the target tag.
1305  * @param   elem Element number of the target tag.
1306  * @param   value new value (string) to substitute with 
1307  */
1308 void File::AddAnonymizeElement (uint16_t group, uint16_t elem, 
1309                                 std::string const &value) 
1310
1311    Element el;
1312    el.Group = group;
1313    el.Elem  = elem;
1314    el.Value = value;
1315    UserAnonymizeList.push_back(el); 
1316 }
1317
1318 /**
1319  * \brief Overwrites in the file the values of the DicomElements
1320  *       held in the list 
1321  */
1322 void File::AnonymizeNoLoad()
1323 {
1324    std::fstream *fp = new std::fstream(Filename.c_str(), 
1325                               std::ios::in | std::ios::out | std::ios::binary); 
1326    gdcm::DocEntry *d;
1327    uint32_t offset;
1328    uint32_t lgth;
1329    uint32_t valLgth = 0;
1330    std::string *spaces;
1331    for (ListElements::iterator it = UserAnonymizeList.begin();  
1332                                it != UserAnonymizeList.end();
1333                              ++it)
1334    { 
1335       d = GetDocEntry( (*it).Group, (*it).Elem);
1336
1337       if ( d == NULL)
1338          continue;
1339
1340       if ( dynamic_cast<SeqEntry *>(d) )
1341       {
1342          gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1343          continue;
1344       }
1345
1346       offset = d->GetOffset();
1347       lgth =   d->GetLength();
1348       if (valLgth < lgth)
1349       {
1350          spaces = new std::string( lgth-valLgth, ' ');
1351          (*it).Value = (*it).Value + *spaces;
1352          delete spaces;
1353       }
1354       fp->seekp( offset, std::ios::beg );
1355       fp->write( (*it).Value.c_str(), lgth );
1356      
1357    }
1358    fp->close();
1359    delete fp;
1360 }
1361
1362 /**
1363  * \brief anonymize a File (remove Patient's personal info passed with
1364  *        AddAnonymizeElement()
1365  * \note You cannot Anonymize a BinEntry (to be fixed)
1366  */
1367 bool File::AnonymizeFile()
1368 {
1369    // If Anonymisation list is empty, let's perform some basic anonymization
1370    if ( UserAnonymizeList.begin() == UserAnonymizeList.end() )
1371    {
1372       // If exist, replace by spaces
1373       SetValEntry ("  ",0x0010, 0x2154); // Telephone   
1374       SetValEntry ("  ",0x0010, 0x1040); // Adress
1375       SetValEntry ("  ",0x0010, 0x0020); // Patient ID
1376
1377       DocEntry* patientNameHE = GetDocEntry (0x0010, 0x0010);
1378   
1379       if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1380       {
1381          std::string studyInstanceUID =  GetEntryValue (0x0020, 0x000d);
1382          if ( studyInstanceUID != GDCM_UNFOUND )
1383          {
1384             SetValEntry(studyInstanceUID, 0x0010, 0x0010);
1385          }
1386          else
1387          {
1388             SetValEntry("anonymized", 0x0010, 0x0010);
1389          }
1390       }
1391    }
1392    else
1393    {
1394       gdcm::DocEntry *d;
1395       for (ListElements::iterator it = UserAnonymizeList.begin();  
1396                                   it != UserAnonymizeList.end();
1397                                 ++it)
1398       {  
1399          d = GetDocEntry( (*it).Group, (*it).Elem);
1400
1401          if ( d == NULL)
1402             continue;
1403
1404          if ( dynamic_cast<SeqEntry *>(d) )
1405          {
1406             gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1407             continue;
1408          }
1409
1410          if ( dynamic_cast<BinEntry *>(d) )
1411          {
1412             gdcmWarningMacro( "To 'Anonymize' a BinEntry, better use AnonymizeNoLoad (FIXME) ");
1413             continue;
1414          }
1415          else
1416             SetValEntry ((*it).Value, (*it).Group, (*it).Elem);
1417       }
1418 }
1419
1420   // In order to make definitively impossible any further identification
1421   // remove or replace all the stuff that contains a Date
1422
1423 //0008 0012 DA ID Instance Creation Date
1424 //0008 0020 DA ID Study Date
1425 //0008 0021 DA ID Series Date
1426 //0008 0022 DA ID Acquisition Date
1427 //0008 0023 DA ID Content Date
1428 //0008 0024 DA ID Overlay Date
1429 //0008 0025 DA ID Curve Date
1430 //0008 002a DT ID Acquisition Datetime
1431 //0018 9074 DT ACQ Frame Acquisition Datetime
1432 //0018 9151 DT ACQ Frame Reference Datetime
1433 //0018 a002 DT ACQ Contribution Date Time
1434 //0020 3403 SH REL Modified Image Date (RET)
1435 //0032 0032 DA SDY Study Verified Date
1436 //0032 0034 DA SDY Study Read Date
1437 //0032 1000 DA SDY Scheduled Study Start Date
1438 //0032 1010 DA SDY Scheduled Study Stop Date
1439 //0032 1040 DA SDY Study Arrival Date
1440 //0032 1050 DA SDY Study Completion Date
1441 //0038 001a DA VIS Scheduled Admission Date
1442 //0038 001c DA VIS Scheduled Discharge Date
1443 //0038 0020 DA VIS Admitting Date
1444 //0038 0030 DA VIS Discharge Date
1445 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1446 //0040 0004 DA PRC Scheduled Procedure Step End Date
1447 //0040 0244 DA PRC Performed Procedure Step Start Date
1448 //0040 0250 DA PRC Performed Procedure Step End Date
1449 //0040 2004 DA PRC Issue Date of Imaging Service Request
1450 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1451 //0040 4011 DT PRC Expected Completion Date and Time
1452 //0040 a030 DT PRC Verification Date Time
1453 //0040 a032 DT PRC Observation Date Time
1454 //0040 a120 DT PRC DateTime
1455 //0040 a121 DA PRC Date
1456 //0040 a13a DT PRC Referenced Datetime
1457 //0070 0082 DA ??? Presentation Creation Date
1458 //0100 0420 DT ??? SOP Autorization Date and Time
1459 //0400 0105 DT ??? Digital Signature DateTime
1460 //2100 0040 DA PJ Creation Date
1461 //3006 0008 DA SSET Structure Set Date
1462 //3008 0024 DA ??? Treatment Control Point Date
1463 //3008 0054 DA ??? First Treatment Date
1464 //3008 0056 DA ??? Most Recent Treatment Date
1465 //3008 0162 DA ??? Safe Position Exit Date
1466 //3008 0166 DA ??? Safe Position Return Date
1467 //3008 0250 DA ??? Treatment Date
1468 //300a 0006 DA RT RT Plan Date
1469 //300a 022c DA RT Air Kerma Rate Reference Date
1470 //300e 0004 DA RT Review Date
1471
1472    return true;
1473 }
1474
1475 /**
1476  * \brief Performs some consistency checking on various 'File related' 
1477  *       (as opposed to 'DicomDir related') entries 
1478  *       then writes in a file all the (Dicom Elements) included the Pixels 
1479  * @param fileName file name to write to
1480  * @param writetype type of the file to be written 
1481  *          (ACR, ExplicitVR, ImplicitVR)
1482  */
1483 bool File::Write(std::string fileName, FileType writetype)
1484 {
1485    std::ofstream *fp = new std::ofstream(fileName.c_str(), 
1486                                          std::ios::out | std::ios::binary);
1487    if (*fp == NULL)
1488    {
1489       gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1490       return false;
1491    }
1492
1493    // Entry : 0002|0000 = group length -> recalculated
1494    ValEntry*e0000 = GetValEntry(0x0002,0x0000);
1495    if ( e0000 )
1496    {
1497       std::ostringstream sLen;
1498       sLen << ComputeGroup0002Length(writetype);
1499       e0000->SetValue(sLen.str());
1500    }
1501
1502    int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1503    if (i_lgPix != -2)
1504    {
1505       // no (GrPixel, NumPixel) element
1506       std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1507       s_lgPix = Util::DicomString( s_lgPix.c_str() );
1508       InsertValEntry(s_lgPix,GrPixel, 0x0000);
1509    }
1510
1511    Document::WriteContent(fp, writetype);
1512
1513    fp->close();
1514    delete fp;
1515
1516    return true;
1517 }
1518
1519 //-----------------------------------------------------------------------------
1520 // Protected
1521
1522
1523 //-----------------------------------------------------------------------------
1524 // Private
1525 /**
1526  * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1527  *        Compute the RLE extra information and store it in \ref RLEInfo
1528  *        for later pixel retrieval usage.
1529  */
1530 void File::ComputeRLEInfo()
1531 {
1532    std::string ts = GetTransferSyntax();
1533    if ( !Global::GetTS()->IsRLELossless(ts) ) 
1534    {
1535       return;
1536    }
1537
1538    // Encoded pixel data: for the time being we are only concerned with
1539    // Jpeg or RLE Pixel data encodings.
1540    // As stated in PS 3.5-2003, section 8.2 p44:
1541    // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1542    //  value representation OB is used".
1543    // Hence we expect an OB value representation. Concerning OB VR,
1544    // the section PS 3.5-2003, section A.4.c p 58-59, states:
1545    // "For the Value Representations OB and OW, the encoding shall meet the
1546    //   following specifications depending on the Data element tag:"
1547    //   [...snip...]
1548    //    - the first item in the sequence of items before the encoded pixel
1549    //      data stream shall be basic offset table item. The basic offset table
1550    //      item value, however, is not required to be present"
1551    ReadAndSkipEncapsulatedBasicOffsetTable();
1552
1553    // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1554    // Loop on the individual frame[s] and store the information
1555    // on the RLE fragments in a RLEFramesInfo.
1556    // Note: - when only a single frame is present, this is a
1557    //         classical image.
1558    //       - when more than one frame are present, then we are in 
1559    //         the case of a multi-frame image.
1560    long frameLength;
1561    while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1562    { 
1563       // Parse the RLE Header and store the corresponding RLE Segment
1564       // Offset Table information on fragments of this current Frame.
1565       // Note that the fragment pixels themselves are not loaded
1566       // (but just skipped).
1567       long frameOffset = Fp->tellg();
1568
1569       uint32_t nbRleSegments = ReadInt32();
1570       if ( nbRleSegments > 16 )
1571       {
1572          // There should be at most 15 segments (refer to RLEFrame class)
1573          gdcmWarningMacro( "Too many segments.");
1574       }
1575  
1576       uint32_t rleSegmentOffsetTable[16];
1577       for( int k = 1; k <= 15; k++ )
1578       {
1579          rleSegmentOffsetTable[k] = ReadInt32();
1580       }
1581
1582       // Deduce from both RLE Header and frameLength 
1583       // the fragment length, and again store this info
1584       // in a RLEFramesInfo.
1585       long rleSegmentLength[15];
1586       // skipping (not reading) RLE Segments
1587       if ( nbRleSegments > 1)
1588       {
1589          for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1590          {
1591              rleSegmentLength[k] =  rleSegmentOffsetTable[k+1]
1592                                   - rleSegmentOffsetTable[k];
1593              SkipBytes(rleSegmentLength[k]);
1594           }
1595        }
1596
1597        rleSegmentLength[nbRleSegments] = frameLength 
1598                                       - rleSegmentOffsetTable[nbRleSegments];
1599        SkipBytes(rleSegmentLength[nbRleSegments]);
1600
1601        // Store the collected info
1602        RLEFrame *newFrame = new RLEFrame;
1603        newFrame->SetNumberOfFragments(nbRleSegments);
1604        for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1605        {
1606           newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1607           newFrame->SetLength(uk,rleSegmentLength[uk]);
1608        }
1609        RLEInfo->AddFrame(newFrame);
1610    }
1611
1612    // Make sure that  we encounter a 'Sequence Delimiter Item'
1613    // at the end of the item :
1614    if ( !ReadTag(0xfffe, 0xe0dd) )
1615    {
1616       gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1617    }
1618 }
1619
1620 /**
1621  * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1622  *        Compute the jpeg extra information (fragment[s] offset[s] and
1623  *        length) and store it[them] in \ref JPEGInfo for later pixel
1624  *        retrieval usage.
1625  */
1626 void File::ComputeJPEGFragmentInfo()
1627 {
1628    // If you need to, look for comments of ComputeRLEInfo().
1629    std::string ts = GetTransferSyntax();
1630    if ( ! Global::GetTS()->IsJPEG(ts) )
1631    {
1632       return;
1633    }
1634
1635    ReadAndSkipEncapsulatedBasicOffsetTable();
1636
1637    // Loop on the fragments[s] and store the parsed information in a
1638    // JPEGInfo.
1639    long fragmentLength;
1640    while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1641    { 
1642       long fragmentOffset = Fp->tellg();
1643
1644        // Store the collected info
1645        JPEGFragment *newFragment = new JPEGFragment;
1646        newFragment->SetOffset(fragmentOffset);
1647        newFragment->SetLength(fragmentLength);
1648        JPEGInfo->AddFragment(newFragment);
1649
1650        SkipBytes(fragmentLength);
1651    }
1652
1653    // Make sure that  we encounter a 'Sequence Delimiter Item'
1654    // at the end of the item :
1655    if ( !ReadTag(0xfffe, 0xe0dd) )
1656    {
1657       gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1658    }
1659 }
1660
1661 /**
1662  * \brief   Assuming the internal file pointer \ref Document::Fp 
1663  *          is placed at the beginning of a tag check whether this
1664  *          tag is (TestGroup, TestElem).
1665  * \warning On success the internal file pointer \ref Document::Fp
1666  *          is modified to point after the tag.
1667  *          On failure (i.e. when the tag wasn't the expected tag
1668  *          (TestGroup, TestElem) the internal file pointer
1669  *          \ref Document::Fp is restored to it's original position.
1670  * @param   testGroup The expected group   of the tag.
1671  * @param   testElem  The expected Element of the tag.
1672  * @return  True on success, false otherwise.
1673  */
1674 bool File::ReadTag(uint16_t testGroup, uint16_t testElem)
1675 {
1676    long positionOnEntry = Fp->tellg();
1677    long currentPosition = Fp->tellg();          // On debugging purposes
1678
1679    // Read the Item Tag group and element, and make
1680    // sure they are what we expected:
1681    uint16_t itemTagGroup;
1682    uint16_t itemTagElem;
1683    try
1684    {
1685       itemTagGroup = ReadInt16();
1686       itemTagElem  = ReadInt16();
1687    }
1688    catch ( FormatError e )
1689    {
1690       //std::cerr << e << std::endl;
1691       return false;
1692    }
1693    if ( itemTagGroup != testGroup || itemTagElem != testElem )
1694    {
1695       gdcmWarningMacro( "Wrong Item Tag found:"
1696        << "   We should have found tag ("
1697        << std::hex << testGroup << "," << testElem << ")" << std::endl
1698        << "   but instead we encountered tag ("
1699        << std::hex << itemTagGroup << "," << itemTagElem << ")"
1700        << "  at address: " << "  0x(" << (unsigned int)currentPosition  << ")" 
1701        ) ;
1702       Fp->seekg(positionOnEntry, std::ios::beg);
1703
1704       return false;
1705    }
1706    return true;
1707 }
1708
1709 /**
1710  * \brief   Assuming the internal file pointer \ref Document::Fp 
1711  *          is placed at the beginning of a tag (TestGroup, TestElement),
1712  *          read the length associated to the Tag.
1713  * \warning On success the internal file pointer \ref Document::Fp
1714  *          is modified to point after the tag and it's length.
1715  *          On failure (i.e. when the tag wasn't the expected tag
1716  *          (TestGroup, TestElement) the internal file pointer
1717  *          \ref Document::Fp is restored to it's original position.
1718  * @param   testGroup The expected Group   of the tag.
1719  * @param   testElem  The expected Element of the tag.
1720  * @return  On success returns the length associated to the tag. On failure
1721  *          returns 0.
1722  */
1723 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElem)
1724 {
1725
1726    if ( !ReadTag(testGroup, testElem) )
1727    {
1728       return 0;
1729    }
1730                                                                                 
1731    //// Then read the associated Item Length
1732    long currentPosition = Fp->tellg();
1733    uint32_t itemLength  = ReadInt32();
1734    {
1735       gdcmWarningMacro( "Basic Item Length is: "
1736         << itemLength << std::endl
1737         << "  at address: " << std::hex << (unsigned int)currentPosition);
1738    }
1739    return itemLength;
1740 }
1741
1742 /**
1743  * \brief When parsing the Pixel Data of an encapsulated file, read
1744  *        the basic offset table (when present, and BTW dump it).
1745  */
1746 void File::ReadAndSkipEncapsulatedBasicOffsetTable()
1747 {
1748    //// Read the Basic Offset Table Item Tag length...
1749    uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
1750
1751    // When present, read the basic offset table itself.
1752    // Notes: - since the presence of this basic offset table is optional
1753    //          we can't rely on it for the implementation, and we will simply
1754    //          trash it's content (when present).
1755    //        - still, when present, we could add some further checks on the
1756    //          lengths, but we won't bother with such fuses for the time being.
1757    if ( itemLength != 0 )
1758    {
1759       char *basicOffsetTableItemValue = new char[itemLength + 1];
1760       Fp->read(basicOffsetTableItemValue, itemLength);
1761
1762 #ifdef GDCM_DEBUG
1763       for (unsigned int i=0; i < itemLength; i += 4 )
1764       {
1765          uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
1766                                               uint32_t);
1767          gdcmWarningMacro( "Read one length: " << 
1768                           std::hex << individualLength );
1769       }
1770 #endif //GDCM_DEBUG
1771
1772       delete[] basicOffsetTableItemValue;
1773    }
1774 }
1775
1776 // These are the deprecated method that one day should be removed (after the next release)
1777
1778 #ifndef GDCM_LEGACY_REMOVE
1779 /**
1780  * \brief  Constructor (DEPRECATED : temporaryly kept not to break the API)
1781  * @param  filename name of the file whose header we want to analyze
1782  * @deprecated do not use any longer
1783  */
1784 File::File( std::string const &filename )
1785      :Document( )
1786 {    
1787    RLEInfo  = new RLEFramesInfo;
1788    JPEGInfo = new JPEGFragmentsInfo;
1789
1790    SetFileName( filename );
1791    Load( ); // gdcm::Document is first Loaded, then the 'File part'
1792 }
1793
1794 /**
1795  * \brief   Loader. (DEPRECATED :  temporaryly kept not to break the API)
1796  * @param   fileName file to be open for parsing
1797  * @return false if file cannot be open or no swap info was found,
1798  *         or no tag was found.
1799  * @deprecated Use the Load() [ + SetLoadMode() ] + SetFileName() functions instead
1800  */
1801 bool File::Load( std::string const &fileName ) 
1802 {
1803    GDCM_LEGACY_REPLACED_BODY(File::Load(std::string), "1.2",
1804                              File::Load());
1805    SetFileName( fileName );
1806    if ( ! this->Document::Load( ) )
1807       return false;
1808
1809    return DoTheLoadingJob( );
1810 }
1811 #endif
1812
1813 //-----------------------------------------------------------------------------
1814 // Print
1815
1816 //-----------------------------------------------------------------------------
1817 } // end namespace gdcm