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