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