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