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