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