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