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