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