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