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