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