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