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