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