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