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