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