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