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