]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
add method
[gdcm.git] / src / gdcmFile.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFile.cxx,v $
5   Language:  C++
6   Date:      $Date: 2006/11/08 17:03:38 $
7   Version:   $Revision: 1.326 $
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 info from 0020,0032 : Image Position Patient
1004   *                   or from 0020 0030 : Image Position (RET)
1005   *
1006   * @param ipp adress of the (3)float array to receive values.
1007   *        (defaulted as 0.,0.,0. if nothing -or inconsistent stuff-
1008   *        is found.
1009   * @return true when one of the tag -with consistent values- is found
1010   *         false when nothing or inconsistent stuff - is found
1011   */
1012 bool File::GetImagePositionPatient( float ipp[3] )
1013 {
1014    std::string strImPosiPat;
1015    //iop is supposed to be float[3]
1016    ipp[0] = ipp[1] = ipp[2] = 0.;
1017
1018    // 0020 0032 DS REL Image Position (Patient)
1019    if ( (strImPosiPat = GetEntryString(0x0020,0x0032)) != GDCM_UNFOUND )
1020    {
1021       if ( sscanf( strImPosiPat.c_str(), "%f \\ %f \\%f", 
1022           &ipp[0], &ipp[1], &ipp[2]) != 3 )
1023       {
1024          gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)."
1025                         << " Less than 3 values were found." );
1026          return false;
1027       }
1028       return true;
1029    }
1030    //For ACR-NEMA
1031    // 0020 0030 DS REL Image Position (RET)
1032    else if ( (strImPosiPat = GetEntryString(0x0020,0x0030)) != GDCM_UNFOUND )
1033    {
1034       if ( sscanf( strImPosiPat.c_str(), "%f \\ %f \\%f ", 
1035           &ipp[0], &ipp[1], &ipp[2]) != 3 )
1036       {
1037          gdcmWarningMacro( "wrong Image Position Patient (0020,0035). "
1038                         << "Less than 3 values were found." );
1039          return false;
1040       }
1041       return true;
1042    }
1043    return false;
1044 }
1045
1046 /**
1047  * \brief   Retrieve the number of Bits Stored (actually used)
1048  *          (as opposed to number of Bits Allocated)
1049  * @return  The encountered number of Bits Stored, 0 by default.
1050  *          0 means the file is NOT USABLE. The caller has to check it !
1051  */
1052 int File::GetBitsStored()
1053 {
1054    DataEntry *entry = GetDataEntry(0x0028,0x0101);
1055    if( !entry )
1056    {
1057       gdcmWarningMacro("BitsStored (0028,0101) is supposed to be mandatory");
1058       return 0;
1059    }
1060    return (int)entry->GetValue(0);
1061 }
1062
1063 /**
1064  * \brief   Retrieve the number of Bits Allocated
1065  *          (8, 12 -compacted ACR-NEMA files-, 16, 24 -old RGB ACR-NEMA files-,)
1066  * @return  The encountered Number of Bits Allocated, 0 by default.
1067  *          0 means the file is NOT USABLE. The caller has to check it !
1068  */
1069 int File::GetBitsAllocated()
1070 {
1071    DataEntry *entry = GetDataEntry(0x0028,0x0100);
1072    if( !entry )
1073    {
1074       gdcmWarningMacro("BitsAllocated (0028,0100) is supposed to be mandatory");
1075       return 0;
1076    }
1077    return (int)entry->GetValue(0);
1078 }
1079
1080 /**
1081  * \brief   Retrieve the high bit position.
1082  * \warning The method defaults to 0 when information is missing.
1083  *          The responsability of checking this value is left to the caller.
1084  * @return  The high bit position when present. 0 when missing.
1085  */
1086 int File::GetHighBitPosition()
1087 {
1088    DataEntry *entry = GetDataEntry(0x0028,0x0102);
1089    if( !entry )
1090    {
1091       gdcmWarningMacro("HighBitPosition (0028,0102) is supposed to be mandatory");
1092       return 0;
1093    }
1094    return (int)entry->GetValue(0);
1095 }
1096
1097 /**
1098  * \brief   Retrieve the number of Samples Per Pixel
1099  *          (1 : gray level, 3 : RGB/YBR -1 or 3 Planes-)
1100  * @return  The encountered number of Samples Per Pixel, 1 by default.
1101  *          (we assume Gray level Pixels)
1102  */
1103 int File::GetSamplesPerPixel()
1104 {
1105    DataEntry *entry = GetDataEntry(0x0028,0x0002);
1106    if( !entry )
1107    {
1108       gdcmWarningMacro("SamplesPerPixel (0028,0002) is supposed to be mandatory");
1109       return 1; // Well, it's supposed to be mandatory ...
1110                 // but sometimes it's missing : *we* assume Gray pixels
1111    }
1112    return (int)entry->GetValue(0);
1113 }
1114
1115 /**
1116  * \brief   Retrieve the Planar Configuration for RGB images
1117  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1118  * @return  The encountered Planar Configuration, 0 by default.
1119  */
1120 int File::GetPlanarConfiguration()
1121 {
1122    DataEntry *entry = GetDataEntry(0x0028,0x0006);
1123    if( !entry )
1124    {
1125       return 0;
1126    }
1127    return (int)entry->GetValue(0);
1128 }
1129
1130 /**
1131  * \brief   Return the size (in bytes) of a single pixel of data.
1132  * @return  The size in bytes of a single pixel of data; 0 by default
1133  *          0 means the file is NOT USABLE; the caller will have to check
1134  */
1135 int File::GetPixelSize()
1136 {
1137    // 0028 0100 US IMG Bits Allocated
1138    // (in order no to be messed up by old ACR-NEMA RGB images)
1139    assert( !(GetEntryString(0x0028,0x0100) == "24") );
1140
1141    std::string pixelType = GetPixelType();
1142    if ( pixelType ==  "8U" || pixelType == "8S" )
1143    {
1144       return 1;
1145    }
1146    if ( pixelType == "16U" || pixelType == "16S")
1147    {
1148       return 2;
1149    }
1150    if ( pixelType == "32U" || pixelType == "32S")
1151    {
1152       return 4;
1153    }
1154    if ( pixelType == "FD" )
1155    {
1156       return 8;
1157    }
1158    gdcmWarningMacro( "Unknown pixel type: " << pixelType);
1159    return 0;
1160 }
1161
1162 /**
1163  * \brief   Build the Pixel Type of the image.
1164  *          Possible values are:
1165  *          - 8U  unsigned  8 bit,
1166  *          - 8S    signed  8 bit,
1167  *          - 16U unsigned 16 bit,
1168  *          - 16S   signed 16 bit,
1169  *          - 32U unsigned 32 bit,
1170  *          - 32S   signed 32 bit,
1171  *          - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
1172  * \warning 12 bit images appear as 16 bit.
1173  *          24 bit images appear as 8 bit + photochromatic interp ="RGB "
1174  *                                        + Planar Configuration = 0
1175  * @return  0S if nothing found. NOT USABLE file. The caller has to check
1176  */
1177 std::string File::GetPixelType()
1178 {
1179    std::string bitsAlloc = GetEntryString(0x0028, 0x0100); // Bits Allocated
1180    if ( bitsAlloc == GDCM_UNFOUND )
1181    {
1182       gdcmWarningMacro( "Bits Allocated (0028,0100) supposed to be mandatory");
1183       bitsAlloc = "16"; // default and arbitrary value, not to polute the output
1184    }
1185
1186    else if ( bitsAlloc == "64" )
1187    {
1188       return "FD";
1189    }
1190      // useless since we have to bypass a bug ( >8 && < 16)
1191    else if ( bitsAlloc == "12" )
1192    {
1193       // It will be unpacked
1194       bitsAlloc = "16";
1195    }
1196    
1197    else if ( bitsAlloc == "24" )
1198    {
1199       // (in order no to be messed up by old RGB images)
1200       bitsAlloc = "8";
1201    }
1202    
1203    int i= atoi(bitsAlloc.c_str());  // fix a bug in some headers
1204    if ( i > 8 &&  i < 16 )
1205    {
1206       bitsAlloc = "16";
1207    }
1208    
1209    std::string sign;
1210    if( IsSignedPixelData() )
1211    {
1212       sign = "S";
1213    }
1214    else
1215    {
1216       sign = "U";
1217    }
1218    return bitsAlloc + sign;
1219 }
1220
1221 /**
1222  * \brief   Check whether the pixels are signed (1) or UNsigned (0) data.
1223  * \warning The method defaults to false (UNsigned) when tag 0028|0103
1224  *          is missing.
1225  *          The responsability of checking this value is left to the caller
1226  *          (NO transformation is performed on the pixels to make then >0)
1227  * @return  True when signed, false when UNsigned
1228  */
1229 bool File::IsSignedPixelData()
1230 {
1231    DataEntry *entry = GetDataEntry(0x0028, 0x0103);//"Pixel Representation"
1232    if( !entry )
1233    {
1234       gdcmWarningMacro( "Pixel Representation (0028,0103) supposed to be "
1235                       << "mandatory");
1236       return false;
1237    }
1238    return entry->GetValue(0) != 0;
1239 }
1240
1241 /**
1242  * \brief   Check whether this a monochrome picture (gray levels) or not,
1243  *          using "Photometric Interpretation" tag (0x0028,0x0004).
1244  * @return  true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
1245  */
1246 bool File::IsMonochrome()
1247 {
1248    const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1249    if (  Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
1250       || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
1251    {
1252       return true;
1253    }
1254    if ( PhotometricInterp == GDCM_UNFOUND )
1255    {
1256       gdcmWarningMacro( "Photometric Interpretation (0028,0004) supposed to be "
1257                          << "mandatory");
1258    }
1259    return false;
1260 }
1261
1262 /**
1263  * \brief   Check whether this a MONOCHROME1 picture (high values = dark)
1264  *            or not using "Photometric Interpretation" tag (0x0028,0x0004).
1265  * @return  true when "MONOCHROME1" . False otherwise.
1266  */
1267 bool File::IsMonochrome1()
1268 {
1269    const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1270    if (  Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
1271    {
1272       return true;
1273    }
1274    if ( PhotometricInterp == GDCM_UNFOUND )
1275    {
1276       gdcmWarningMacro( "Photometric Interpretation (0028,0004) : supposed to"
1277       << " be mandatory! ");
1278    }
1279    return false;
1280 }
1281
1282 /**
1283  * \brief   Check whether this a "PALETTE COLOR" picture or not by accessing
1284  *          the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1285  * @return  true when "PALETTE COLOR". False otherwise.
1286  */
1287 bool File::IsPaletteColor()
1288 {
1289    std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1290    if (   PhotometricInterp == "PALETTE COLOR " )
1291    {
1292       return true;
1293    }
1294    if ( PhotometricInterp == GDCM_UNFOUND )
1295    {
1296       gdcmDebugMacro( "Not found : Palette color (0028,0004)");
1297    }
1298    return false;
1299 }
1300
1301 /**
1302  * \brief   Check whether this a "YBR_FULL" color picture or not by accessing
1303  *          the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1304  * @return  true when "YBR_FULL". False otherwise.
1305  */
1306 bool File::IsYBRFull()
1307 {
1308    std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1309    if (   PhotometricInterp == "YBR_FULL" )
1310    {
1311       return true;
1312    }
1313    if ( PhotometricInterp == GDCM_UNFOUND )
1314    {
1315       gdcmDebugMacro( "Not found : YBR Full (0028,0004)");
1316    }
1317    return false;
1318 }
1319
1320 /**
1321   * \brief tells us if LUT are used
1322   * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1323   *          are NOT considered as LUT, since nobody knows
1324   *          how to deal with them
1325   *          Please warn me if you know sbdy that *does* know ... jprx
1326   * @return true if LUT Descriptors and LUT Tables were found 
1327   */
1328 bool File::HasLUT()
1329 {
1330    // Check the presence of the LUT Descriptors, and LUT Tables    
1331    // LutDescriptorRed    
1332    if ( !GetDocEntry(0x0028,0x1101) )
1333    {
1334       return false;
1335    }
1336    // LutDescriptorGreen 
1337    if ( !GetDocEntry(0x0028,0x1102) )
1338    {
1339       return false;
1340    }
1341    // LutDescriptorBlue 
1342    if ( !GetDocEntry(0x0028,0x1103) )
1343    {
1344       return false;
1345    }
1346    // Red Palette Color Lookup Table Data
1347    if ( !GetDocEntry(0x0028,0x1201) )
1348    {
1349       return false;
1350    }
1351    // Green Palette Color Lookup Table Data       
1352    if ( !GetDocEntry(0x0028,0x1202) )
1353    {
1354       return false;
1355    }
1356    // Blue Palette Color Lookup Table Data      
1357    if ( !GetDocEntry(0x0028,0x1203) )
1358    {
1359       return false;
1360    }
1361
1362    // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1363    //         NOT taken into account, but we don't know how to use it ...   
1364    return true;
1365 }
1366
1367 /**
1368   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1369   *             else 0
1370   * @return Lookup Table number of Bits , 0 by default
1371   *          when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1372   * @ return bit number of each LUT item 
1373   */
1374 int File::GetLUTNbits()
1375 {
1376    std::vector<std::string> tokens;
1377    int lutNbits;
1378
1379    //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1380    //                                = Lookup Table Desc-Blue
1381    // Consistency already checked in GetLUTLength
1382    std::string lutDescription = GetEntryString(0x0028,0x1101);
1383    if ( lutDescription == GDCM_UNFOUND )
1384    {
1385       return 0;
1386    }
1387
1388    tokens.clear(); // clean any previous value
1389    Util::Tokenize ( lutDescription, tokens, "\\" );
1390    //LutLength=atoi(tokens[0].c_str());
1391    //LutDepth=atoi(tokens[1].c_str());
1392
1393    lutNbits = atoi( tokens[2].c_str() );
1394    tokens.clear();
1395
1396    return lutNbits;
1397 }
1398
1399 /**
1400  *\brief gets the info from 0028,1052 : Rescale Intercept
1401  * @return Rescale Intercept. defaulted to 0.0 is not found or empty
1402  */
1403 float File::GetRescaleIntercept()
1404 {
1405    // 0028 1052 DS IMG Rescale Intercept
1406    DataEntry *entry = GetDataEntry(0x0028, 0x1052);
1407    if( !entry )
1408    {
1409       gdcmWarningMacro( "Missing Rescale Intercept (0028,1052)");
1410       return 0.0f;
1411    }
1412    return (float)entry->GetValue(0);
1413
1414 }
1415
1416 /**
1417  *\brief   gets the info from 0028,1053 : Rescale Slope
1418  * @return Rescale Slope. defaulted to 1.0 is not found or empty
1419  */
1420 float File::GetRescaleSlope()
1421 {
1422    // 0028 1053 DS IMG Rescale Slope
1423    DataEntry *entry = GetDataEntry(0x0028, 0x1053);
1424    if( !entry )
1425    {
1426       gdcmDebugMacro( "Missing Rescale Slope (0028,1053)");
1427       return 1.0f;
1428    }
1429    return (float)entry->GetValue(0);
1430 }
1431
1432 /**
1433  * \brief This function is intended to user who doesn't want 
1434  *   to have to manage a LUT and expects to get an RBG Pixel image
1435  *   (or a monochrome one, if no LUT found ...) 
1436  * \warning to be used with GetImagePixels()
1437  * @return 1 if Gray level, 3 if Color (RGB, YBR, *or PALETTE COLOR*)
1438  */
1439 int File::GetNumberOfScalarComponents()
1440 {
1441    if ( GetSamplesPerPixel() == 3 )
1442    {
1443       return 3;
1444    }
1445
1446    // 0028 0100 US IMG Bits Allocated
1447    // (in order no to be messed up by old RGB images)
1448    if ( GetEntryString(0x0028,0x0100) == "24" )
1449    {
1450       return 3;
1451    }
1452
1453    std::string strPhotometricInterpretation = GetEntryString(0x0028,0x0004);
1454
1455    if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1456    {
1457       if ( HasLUT() )// PALETTE COLOR is NOT enough
1458       {
1459          return 3;
1460       }
1461       else
1462       {
1463          return 1;
1464       }
1465    }
1466
1467    // beware of trailing space at end of string      
1468    // DICOM tags are never of odd length
1469    if ( strPhotometricInterpretation == GDCM_UNFOUND   || 
1470         Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1471         Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1472    {
1473       return 1;
1474    }
1475    else
1476    {
1477       // we assume that *all* kinds of YBR are dealt with
1478       return 3;
1479    }
1480 }
1481
1482 /**
1483  * \brief This function is intended to user that DOESN'T want 
1484  *  to get RGB pixels image when it's stored as a PALETTE COLOR image
1485  *   - the (vtk) user is supposed to know how deal with LUTs - 
1486  * \warning to be used with GetImagePixelsRaw()
1487  * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1488  */
1489 int File::GetNumberOfScalarComponentsRaw()
1490 {
1491    // 0028 0100 US IMG Bits Allocated
1492    // (in order no to be messed up by old RGB images)
1493    if ( File::GetEntryString(0x0028,0x0100) == "24" )
1494    {
1495       return 3;
1496    }
1497
1498    // we assume that *all* kinds of YBR are dealt with
1499    return GetSamplesPerPixel();
1500 }
1501
1502 /**
1503  * \brief   Recover the offset (from the beginning of the file) 
1504  *          of *image* pixels (not *icone image* pixels, if any !)
1505  * @return Pixel Offset
1506  */
1507 size_t File::GetPixelOffset()
1508 {
1509    DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1510    if ( pxlElement )
1511    {
1512       return pxlElement->GetOffset();
1513    }
1514    else
1515    {
1516       gdcmWarningMacro( "Big trouble : Pixel Element ("
1517                       << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1518       return 0;
1519    }
1520 }
1521
1522 /**
1523  * \brief   Recover the pixel area length (in Bytes)
1524  * @return Pixel Element Length, as stored in the header
1525  *         (NOT the memory space necessary to hold the Pixels 
1526  *          -in case of embeded compressed image-)
1527  *         0 : NOT USABLE file. The caller has to check.
1528  */
1529 size_t File::GetPixelAreaLength()
1530 {
1531    DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1532    if ( pxlElement )
1533    {
1534       return pxlElement->GetLength();
1535    }
1536    else
1537    {
1538       gdcmWarningMacro( "Big trouble : Pixel Element ("
1539                       << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1540       return 0;
1541    }
1542 }
1543
1544 /**
1545  * \brief Adds the characteristics of a new element we want to anonymize
1546  * @param   group  Group number of the target tag.
1547  * @param   elem Element number of the target tag.
1548  * @param   value new value (string) to substitute with 
1549  */
1550 void File::AddAnonymizeElement (uint16_t group, uint16_t elem, 
1551                                 std::string const &value) 
1552
1553    DicomElement el;
1554    el.Group = group;
1555    el.Elem  = elem;
1556    el.Value = value;
1557    UserAnonymizeList.push_back(el); 
1558 }
1559
1560 /**
1561  * \brief Overwrites in the file the values of the DicomElements
1562  *       held in the list 
1563  */
1564 void File::AnonymizeNoLoad()
1565 {
1566    std::fstream *fp = new std::fstream(Filename.c_str(), 
1567                               std::ios::in | std::ios::out | std::ios::binary); 
1568    gdcm::DocEntry *d;
1569    uint32_t offset;
1570    uint32_t lgth;
1571    uint32_t valLgth = 0;
1572    std::string *spaces;
1573    for (ListElements::iterator it = UserAnonymizeList.begin();  
1574                                it != UserAnonymizeList.end();
1575                              ++it)
1576    { 
1577    
1578       //std::cout << "File::AnonymizeNoLoad -------" << std::hex <<(*it).Group <<"|"<< 
1579       //         (*it).Elem 
1580       //         << "[" << (*it).Value << "] "<< std::dec << std::endl; 
1581       d = GetDocEntry( (*it).Group, (*it).Elem);
1582
1583       if ( d == NULL)
1584          continue;
1585
1586       if ( dynamic_cast<SeqEntry *>(d) )
1587       {
1588          gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1589          continue;
1590       }
1591       
1592       valLgth = (*it).Value.size();
1593       if (valLgth == 0)
1594          continue;
1595
1596       offset = d->GetOffset();
1597       lgth =   d->GetLength();
1598       
1599       //std::cout << "lgth " << lgth << " valLgth " << valLgth << std::endl;
1600       if (valLgth < lgth)
1601       {
1602          spaces = new std::string( lgth-valLgth, ' ');
1603          (*it).Value = (*it).Value + *spaces;
1604          //std::cout << "[" << (*it).Value << "] " << lgth << std::endl;
1605          delete spaces;
1606       }
1607       fp->seekp( offset, std::ios::beg );
1608       fp->write( (*it).Value.c_str(), lgth );
1609      
1610    }
1611    fp->close();
1612    delete fp;
1613 }
1614
1615 /**
1616  * \brief anonymize a File (remove Patient's personal info passed with
1617  *        AddAnonymizeElement()
1618  * \note You cannot Anonymize a DataEntry (to be fixed)
1619  */
1620 bool File::AnonymizeFile()
1621 {
1622    // If Anonymisation list is empty, let's perform some basic anonymization
1623    if ( UserAnonymizeList.begin() == UserAnonymizeList.end() )
1624    {
1625       // If exist, replace by spaces
1626       SetEntryString("  ",0x0010, 0x2154); // Telephone   
1627       SetEntryString("  ",0x0010, 0x1040); // Adress
1628       SetEntryString("  ",0x0010, 0x0020); // Patient ID
1629
1630       DocEntry *patientNameHE = GetDocEntry (0x0010, 0x0010);
1631   
1632       if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1633       {
1634          std::string studyInstanceUID =  GetEntryString (0x0020, 0x000d);
1635          if ( studyInstanceUID != GDCM_UNFOUND )
1636          {
1637             SetEntryString(studyInstanceUID, 0x0010, 0x0010);
1638          }
1639          else
1640          {
1641             SetEntryString("anonymized", 0x0010, 0x0010);
1642          }
1643       }
1644    }
1645    else
1646    {
1647       gdcm::DocEntry *d;
1648       for (ListElements::iterator it = UserAnonymizeList.begin();  
1649                                   it != UserAnonymizeList.end();
1650                                 ++it)
1651       {  
1652          d = GetDocEntry( (*it).Group, (*it).Elem);
1653
1654          if ( d == NULL)
1655             continue;
1656
1657          if ( dynamic_cast<SeqEntry *>(d) )
1658          {
1659             gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1660             continue;
1661          }
1662
1663          if ( dynamic_cast<DataEntry *>(d) )
1664          {
1665             gdcmWarningMacro( "To 'Anonymize' a DataEntry, better use AnonymizeNoLoad (FIXME) ");
1666             continue;
1667          }
1668          else
1669             SetEntryString ((*it).Value, (*it).Group, (*it).Elem);
1670       }
1671 }
1672
1673   // In order to make definitively impossible any further identification
1674   // remove or replace all the stuff that contains a Date
1675
1676 //0008 0012 DA ID Instance Creation Date
1677 //0008 0020 DA ID Study Date
1678 //0008 0021 DA ID Series Date
1679 //0008 0022 DA ID Acquisition Date
1680 //0008 0023 DA ID Content Date
1681 //0008 0024 DA ID Overlay Date
1682 //0008 0025 DA ID Curve Date
1683 //0008 002a DT ID Acquisition Datetime
1684 //0018 9074 DT ACQ Frame Acquisition Datetime
1685 //0018 9151 DT ACQ Frame Reference Datetime
1686 //0018 a002 DT ACQ Contribution Date Time
1687 //0020 3403 SH REL Modified Image Date (RET)
1688 //0032 0032 DA SDY Study Verified Date
1689 //0032 0034 DA SDY Study Read Date
1690 //0032 1000 DA SDY Scheduled Study Start Date
1691 //0032 1010 DA SDY Scheduled Study Stop Date
1692 //0032 1040 DA SDY Study Arrival Date
1693 //0032 1050 DA SDY Study Completion Date
1694 //0038 001a DA VIS Scheduled Admission Date
1695 //0038 001c DA VIS Scheduled Discharge Date
1696 //0038 0020 DA VIS Admitting Date
1697 //0038 0030 DA VIS Discharge Date
1698 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1699 //0040 0004 DA PRC Scheduled Procedure Step End Date
1700 //0040 0244 DA PRC Performed Procedure Step Start Date
1701 //0040 0250 DA PRC Performed Procedure Step End Date
1702 //0040 2004 DA PRC Issue Date of Imaging Service Request
1703 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1704 //0040 4011 DT PRC Expected Completion Date and Time
1705 //0040 a030 DT PRC Verification Date Time
1706 //0040 a032 DT PRC Observation Date Time
1707 //0040 a120 DT PRC DateTime
1708 //0040 a121 DA PRC Date
1709 //0040 a13a DT PRC Referenced Datetime
1710 //0070 0082 DA ??? Presentation Creation Date
1711 //0100 0420 DT ??? SOP Autorization Date and Time
1712 //0400 0105 DT ??? Digital Signature DateTime
1713 //2100 0040 DA PJ Creation Date
1714 //3006 0008 DA SSET Structure Set Date
1715 //3008 0024 DA ??? Treatment Control Point Date
1716 //3008 0054 DA ??? First Treatment Date
1717 //3008 0056 DA ??? Most Recent Treatment Date
1718 //3008 0162 DA ??? Safe Position Exit Date
1719 //3008 0166 DA ??? Safe Position Return Date
1720 //3008 0250 DA ??? Treatment Date
1721 //300a 0006 DA RT RT Plan Date
1722 //300a 022c DA RT Air Kerma Rate Reference Date
1723 //300e 0004 DA RT Review Date
1724
1725    return true;
1726 }
1727
1728 /**
1729  * \brief Performs some consistency checking on various 'File related' 
1730  *       (as opposed to 'DicomDir related') entries 
1731  *       then writes in a file all the (Dicom Elements) included the Pixels 
1732  * @param fileName file name to write to
1733  * @param writetype type of the file to be written 
1734  *          (ACR, ExplicitVR, ImplicitVR)
1735  */
1736 bool File::Write(std::string fileName, FileType writetype)
1737 {
1738    std::ofstream *fp = new std::ofstream(fileName.c_str(), 
1739                                          std::ios::out | std::ios::binary);
1740    if (*fp == NULL)
1741    {
1742       gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1743       return false;
1744    }
1745
1746    // Entry : 0002|0000 = group length -> recalculated
1747    DataEntry *e0000 = GetDataEntry(0x0002,0x0000);
1748    if ( e0000 )
1749    {
1750       std::ostringstream sLen;
1751       sLen << ComputeGroup0002Length( );
1752       e0000->SetString(sLen.str());
1753    }
1754
1755    /// \todo FIXME : Derma?.dcm does not have it...let's remove it ?!? JPRx
1756    if( writetype != JPEG )
1757    {
1758       int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1759       if (i_lgPix != -2)
1760       {
1761          // no (GrPixel, NumPixel) element
1762          std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1763          s_lgPix = Util::DicomString( s_lgPix.c_str() );
1764          InsertEntryString(s_lgPix,GrPixel, 0x0000, "UL");   
1765       }
1766    }
1767    Document::WriteContent(fp, writetype);
1768
1769    fp->close();
1770    delete fp;
1771
1772    return true;
1773 }
1774
1775 //-----------------------------------------------------------------------------
1776 // Protected
1777
1778
1779 //-----------------------------------------------------------------------------
1780 // Private
1781 /**
1782  * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1783  *        Compute the RLE extra information and store it in \ref RLEInfo
1784  *        for later pixel retrieval usage.
1785  */
1786 void File::ComputeRLEInfo()
1787 {
1788    std::string ts = GetTransferSyntax();
1789    if ( !Global::GetTS()->IsRLELossless(ts) ) 
1790    {
1791       return;
1792    }
1793
1794    // Encoded pixel data: for the time being we are only concerned with
1795    // Jpeg or RLE Pixel data encodings.
1796    // As stated in PS 3.5-2003, section 8.2 p44:
1797    // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1798    //  value representation OB is used".
1799    // Hence we expect an OB value representation. Concerning OB VR,
1800    // the section PS 3.5-2003, section A.4.c p 58-59, states:
1801    // "For the Value Representations OB and OW, the encoding shall meet the
1802    //   following specifications depending on the Data element tag:"
1803    //   [...snip...]
1804    //    - the first item in the sequence of items before the encoded pixel
1805    //      data stream shall be basic offset table item. The basic offset table
1806    //      item value, however, is not required to be present"
1807    ReadEncapsulatedBasicOffsetTable();
1808
1809    // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1810    // Loop on the individual frame[s] and store the information
1811    // on the RLE fragments in a RLEFramesInfo.
1812    // Note: - when only a single frame is present, this is a
1813    //         classical image.
1814    //       - when more than one frame are present, then we are in 
1815    //         the case of a multi-frame image.
1816    long frameLength;
1817    int i=0;
1818    uint32_t sum = 0;
1819    while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1820    { 
1821       // Since we have read the basic offset table, let's check the value were correct
1822       // or else produce a warning:
1823       if ( BasicOffsetTableItemValue )
1824         {
1825         // If a BasicOffsetTableItemValue was read
1826         uint32_t individualLength = BasicOffsetTableItemValue[i];
1827         assert( individualLength == sum ); // REMOVE that if this is a problem
1828         if( individualLength != sum )
1829           {
1830           gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght" );
1831           }
1832         sum += frameLength + 8;
1833         i++;
1834         }
1835       // Parse the RLE Header and store the corresponding RLE Segment
1836       // Offset Table information on fragments of this current Frame.
1837       // Note that the fragment pixels themselves are not loaded
1838       // (but just skipped).
1839       long frameOffset = Fp->tellg(); // once per fragment
1840
1841       uint32_t nbRleSegments = ReadInt32();
1842       if ( nbRleSegments > 16 )
1843       {
1844          // There should be at most 15 segments (refer to RLEFrame class)
1845          gdcmWarningMacro( "Too many segments.");
1846       }
1847  
1848       uint32_t rleSegmentOffsetTable[16];
1849       for( int k = 1; k <= 15; k++ )
1850       {
1851          rleSegmentOffsetTable[k] = ReadInt32();
1852       }
1853
1854       // Deduce from both RLE Header and frameLength 
1855       // the fragment length, and again store this info
1856       // in a RLEFramesInfo.
1857       long rleSegmentLength[15];
1858       // skipping (not reading) RLE Segments
1859       if ( nbRleSegments > 1)
1860       {
1861          for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1862          {
1863              rleSegmentLength[k] =  rleSegmentOffsetTable[k+1]
1864                                   - rleSegmentOffsetTable[k];
1865              SkipBytes(rleSegmentLength[k]);
1866           }
1867        }
1868
1869        rleSegmentLength[nbRleSegments] = frameLength 
1870                                       - rleSegmentOffsetTable[nbRleSegments];
1871        SkipBytes(rleSegmentLength[nbRleSegments]);
1872
1873        // Store the collected info
1874        RLEFrame *newFrame = new RLEFrame;
1875        newFrame->SetNumberOfFragments(nbRleSegments);
1876        for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1877        {
1878           newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1879           newFrame->SetLength(uk,rleSegmentLength[uk]);
1880        }
1881        RLEInfo->AddFrame(newFrame);
1882    }
1883
1884    // Make sure that  we encounter a 'Sequence Delimiter Item'
1885    // at the end of the item :
1886    if ( !ReadTag(0xfffe, 0xe0dd) ) // once per RLE File
1887    {
1888       gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1889    }
1890 }
1891
1892 /**
1893  * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1894  *        Compute the jpeg extra information (fragment[s] offset[s] and
1895  *        length) and store it[them] in \ref JPEGInfo for later pixel
1896  *        retrieval usage.
1897  */
1898 void File::ComputeJPEGFragmentInfo()
1899 {
1900    // If you need to, look for comments of ComputeRLEInfo().
1901    std::string ts = GetTransferSyntax();
1902    if ( ! Global::GetTS()->IsJPEG(ts) )
1903    {
1904       return;
1905    }
1906
1907    ReadEncapsulatedBasicOffsetTable();
1908
1909    // Loop on the fragments[s] and store the parsed information in a
1910    // JPEGInfo.
1911    long fragmentLength;
1912    int i=0;
1913    uint32_t sum = 0;
1914    while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1915    { 
1916       // Since we have read the basic offset table, let's check the value were correct
1917       // or else produce a warning:
1918       // A.4 Transfer syntaxes for encapsulation of encoded pixel data:
1919       // When the Item Value is present, the Basic Offset Table Item Value shall contain
1920       // concatenated 32-bit unsigned integer values that are byte offsets to the first
1921       // byte of the Item Tag of the first fragment for each frame in the Sequence of
1922       // Items. These offsets are measured from the first byte of the first Item Tag
1923       // following the Basic Offset Table item (See Table A.4-2).
1924
1925       if ( BasicOffsetTableItemValue )
1926         {
1927         // If a BasicOffsetTableItemValue was read
1928         uint32_t individualLength = BasicOffsetTableItemValue[i];
1929         //assert( individualLength == sum ); // Seems like 00191113.dcm is off by one ??
1930         if( individualLength != sum )
1931           {
1932           gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght:" <<
1933               individualLength << " != " << sum );
1934           }
1935         sum += fragmentLength + 8;
1936         i++;
1937         }
1938
1939       long fragmentOffset = Fp->tellg(); // Once per fragment
1940       // Store the collected info
1941       JPEGFragment *newFragment = new JPEGFragment;
1942       newFragment->SetOffset(fragmentOffset);
1943       newFragment->SetLength(fragmentLength);
1944       JPEGInfo->AddFragment(newFragment);
1945
1946       SkipBytes(fragmentLength);
1947    }
1948
1949    // Make sure that  we encounter a 'Sequence Delimiter Item'
1950    // at the end of the item :
1951    if ( !ReadTag(0xfffe, 0xe0dd) )
1952    {
1953       gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1954    }
1955 }
1956
1957 /**
1958  * \brief   Assuming the internal file pointer \ref Document::Fp 
1959  *          is placed at the beginning of a tag, check whether this
1960  *          tag is (TestGroup, TestElem).
1961  * \warning On success the internal file pointer \ref Document::Fp
1962  *          is modified to point after the tag.
1963  *          On failure (i.e. when the tag wasn't the expected tag
1964  *          (TestGroup, TestElem) the internal file pointer
1965  *          \ref Document::Fp is restored to it's original position.
1966  * @param   testGroup The expected group   of the tag.
1967  * @param   testElem  The expected Element of the tag.
1968  * @return  True on success, false otherwise.
1969  */
1970 bool File::ReadTag(uint16_t testGroup, uint16_t testElem)
1971 {
1972    long positionOnEntry = Fp->tellg(); // Only when reading fragments
1973    //long currentPosition = positionOnEntry;      // On debugging purposes
1974
1975    // Read the Item Tag group and element, and make
1976    // sure they are what we expected:
1977    uint16_t itemTagGroup;
1978    uint16_t itemTagElem;
1979    try
1980    {
1981       itemTagGroup = ReadInt16();
1982       itemTagElem  = ReadInt16();
1983    }
1984    catch ( FormatError )
1985    {
1986       gdcmErrorMacro( "Can not read tag for "
1987        << "   We should have found tag ("
1988        << DictEntry::TranslateToKey(testGroup,testElem) << ")"
1989        ) ;
1990
1991       return false;
1992    }
1993    if ( itemTagGroup != testGroup || itemTagElem != testElem )
1994    {
1995        // in order not to pollute output we don't warn on 'delimitors'
1996       if (itemTagGroup != 0xfffe ||  testGroup != 0xfffe )
1997          gdcmWarningMacro( "Wrong Item Tag found:"
1998           << "   We should have found tag ("
1999           << DictEntry::TranslateToKey(testGroup,testElem) << ")" << std::endl
2000           << "   but instead we encountered tag ("
2001           << DictEntry::TranslateToKey(itemTagGroup,itemTagElem) << ")"
2002           << "  at address: " << "  0x(" << std::hex 
2003           << (unsigned int)positionOnEntry  << std::dec << ")" 
2004           ) ;
2005       Fp->seekg(positionOnEntry, std::ios::beg);
2006
2007       return false;
2008    }
2009    return true;
2010 }
2011
2012 /**
2013  * \brief   Assuming the internal file pointer \ref Document::Fp 
2014  *          is placed at the beginning of a tag (TestGroup, TestElement),
2015  *          read the length associated to the Tag.
2016  * \warning On success the internal file pointer \ref Document::Fp
2017  *          is modified to point after the tag and it's length.
2018  *          On failure (i.e. when the tag wasn't the expected tag
2019  *          (TestGroup, TestElement) the internal file pointer
2020  *          \ref Document::Fp is restored to it's original position.
2021  * @param   testGroup The expected Group   of the tag.
2022  * @param   testElem  The expected Element of the tag.
2023  * @return  On success returns the length associated to the tag. On failure
2024  *          returns 0.
2025  */
2026 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElem)
2027 {
2028
2029    if ( !ReadTag(testGroup, testElem) )
2030    {
2031       // Avoid polutting output
2032       if ( testGroup != 0xfffe ) 
2033          gdcmErrorMacro( "ReadTag did not succeed for ("
2034                     << DictEntry::TranslateToKey(testGroup,testElem) 
2035                     << ")..." );
2036       return 0;
2037    }
2038                                                                                 
2039    //// Then read the associated Item Length
2040    
2041    // long currentPosition = Fp->tellg(); // save time // JPRx
2042    uint32_t itemLength  = ReadInt32();
2043    gdcmDebugMacro( "Basic Item Length is: " << itemLength 
2044 //        << "  at address: " << std::hex << (unsigned int)currentPosition
2045    );
2046    return itemLength;
2047 }
2048
2049 /**
2050  * \brief When parsing the Pixel Data of an encapsulated file, read
2051  *        the basic offset table (when present, and BTW dump it).
2052  */
2053 void File::ReadEncapsulatedBasicOffsetTable()
2054 {
2055    //// Read the Basic Offset Table Item Tag length...
2056    uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2057
2058    // When present, read the basic offset table itself.
2059    // Notes: - since the presence of this basic offset table is optional
2060    //          we can't rely on it for the implementation, and we will simply
2061    //          trash it's content (when present).
2062    //        - still, when present, we could add some further checks on the
2063    //          lengths, but we won't bother with such fuses for the time being.
2064    if ( itemLength != 0 )
2065    {
2066       char *charBasicOffsetTableItemValue = new char[itemLength];
2067       Fp->read(charBasicOffsetTableItemValue, itemLength);
2068       unsigned int nbEntries = itemLength/4;
2069       assert( nbEntries*4 == itemLength); // Make sure this is a multiple
2070       BasicOffsetTableItemValue = new uint32_t[nbEntries];
2071
2072       for (unsigned int i=0; i < nbEntries; i++ )
2073       {
2074          BasicOffsetTableItemValue[i] = *((uint32_t*)(&charBasicOffsetTableItemValue[4*i]));
2075 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
2076          uint32_t val = BasicOffsetTableItemValue[i];
2077          BasicOffsetTableItemValue[i] 
2078            = (  (val<<24)               | ((val<<8)  & 0x00ff0000) | 
2079               ( (val>>8)  & 0x0000ff00) |  (val>>24)               );
2080 #endif
2081          gdcmDebugMacro( "Read one length for: " << 
2082                           std::hex << BasicOffsetTableItemValue[i] );
2083       }
2084
2085       delete[] charBasicOffsetTableItemValue;
2086    }
2087 }
2088
2089 // These are the deprecated method that one day should be removed (after the next release)
2090
2091 //#ifndef GDCM_LEGACY_REMOVE
2092 /*
2093  * \ brief   Loader. (DEPRECATED :  temporaryly kept not to break the API)
2094  * @ param   fileName file to be open for parsing
2095  * @ return false if file cannot be open or no swap info was found,
2096  *         or no tag was found.
2097  * @deprecated Use the Load() [ + SetLoadMode() ] + SetFileName() functions instead
2098  */
2099  /*
2100 bool File::Load( std::string const &fileName ) 
2101 {
2102    GDCM_LEGACY_REPLACED_BODY(File::Load(std::string), "1.2",
2103                              File::Load());
2104    SetFileName( fileName );
2105    if ( ! this->Document::Load( ) )
2106       return false;
2107
2108    return DoTheLoadingJob( );
2109 }
2110 #endif
2111 */
2112 //-----------------------------------------------------------------------------
2113 // Print
2114
2115 //-----------------------------------------------------------------------------
2116 } // end namespace gdcm