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