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