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