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