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