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