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