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