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