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