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