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