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