]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
ENH: Minor cleanup, mostly cosmetic
[gdcm.git] / src / gdcmHeader.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmHeader.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/10/28 03:10:58 $
7   Version:   $Revision: 1.196 $
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 "gdcmHeader.h"
20 #include "gdcmGlobal.h"
21 #include "gdcmUtil.h"
22 #include "gdcmDebug.h"
23 #include "gdcmTS.h"
24 #include "gdcmValEntry.h"
25
26 #include <vector>
27
28 namespace gdcm 
29 {
30 //-----------------------------------------------------------------------------
31 // Constructor / Destructor
32 /**
33  * \brief  Constructor 
34  * @param  filename name of the file whose header we want to analyze
35  */
36 Header::Header( std::string const & filename ):
37             Document( filename )
38 {    
39    // for some ACR-NEMA images GrPixel, NumPixel is *not* 7fe0,0010
40    // We may encounter the 'RETired' (0x0028, 0x0200) tag
41    // (Image Location") . This Element contains the number of
42    // the group that contains the pixel data (hence the "Pixel Data"
43    // is found by indirection through the "Image Location").
44    // Inside the group pointed by "Image Location" the searched element
45    // is conventionally the element 0x0010 (when the norm is respected).
46    // When the "Image Location" is absent we default to group 0x7fe0.
47    // Note: this IS the right place for the code
48  
49    // Image Location
50    std::string imgLocation = GetEntryByNumber(0x0028, 0x0200);
51    if ( imgLocation == GDCM_UNFOUND )
52    {
53       // default value
54       GrPixel = 0x7fe0;
55    }
56    else
57    {
58       GrPixel = (uint16_t) atoi( imgLocation.c_str() );
59    }   
60
61    // sometimes Image Location value doesn't follow 
62    // the supposed processor endianity. 
63    // see gdcmData/cr172241.dcm      
64    if ( GrPixel == 0xe07f )
65    {
66       GrPixel = 0x7fe0;
67    }
68
69    if ( GrPixel != 0x7fe0 )
70    {
71       // This is a kludge for old dirty Philips imager.
72       NumPixel = 0x1010;
73    }
74    else
75    {
76       NumPixel = 0x0010;
77    }
78 }
79
80 /**
81  * \brief Constructor  
82  */
83 Header::Header()
84            :Document()
85 {
86 }
87
88 /**
89  * \brief   Canonical destructor.
90  */
91 Header::~Header ()
92 {
93 }
94
95
96 /**
97  * \brief Performs some consistency checking on various 'File related' 
98  *       (as opposed to 'DicomDir related') entries 
99  *       then writes in a file all the (Dicom Elements) included the Pixels 
100  * @param fp file pointer on an already open file
101  * @param filetype Type of the File to be written 
102  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
103  */
104 void Header::Write(std::ofstream* fp,FileType filetype)
105 {
106    // Bits Allocated
107    if ( GetEntryByNumber(0x0028,0x0100) ==  "12")
108    {
109       SetEntryByNumber("16", 0x0028,0x0100);
110    }
111
112   /// \todo correct 'Pixel group' Length if necessary
113
114    int i_lgPix = GetEntryLengthByNumber(GrPixel, NumPixel);
115    if (i_lgPix != -2)
116    {
117       // no (GrPixel, NumPixel) element
118       std::string s_lgPix;
119       s_lgPix = Util::Format("%d", i_lgPix+12);
120       ReplaceOrCreateByNumber(s_lgPix,GrPixel, 0x0000);
121    }
122
123    // FIXME : should be nice if we could move it to File
124    //         (or in future gdcmPixelData class)
125
126    // Drop Palette Color, if necessary
127    
128    if ( GetEntryByNumber(0x0028,0x0002).c_str()[0] == '3' )
129    {
130       // if SamplesPerPixel = 3, sure we don't need any LUT !   
131       // Drop 0028|1101, 0028|1102, 0028|1103
132       // Drop 0028|1201, 0028|1202, 0028|1203
133
134       DocEntry* e = GetDocEntryByNumber(0x0028,0x01101);
135       if (e)
136       {
137          RemoveEntryNoDestroy(e);
138       }
139       e = GetDocEntryByNumber(0x0028,0x1102);
140       if (e)
141       {
142          RemoveEntryNoDestroy(e);
143       }
144       e = GetDocEntryByNumber(0x0028,0x1103);
145       if (e)
146       {
147          RemoveEntryNoDestroy(e);
148       }
149       e = GetDocEntryByNumber(0x0028,0x01201);
150       if (e)
151       {
152          RemoveEntryNoDestroy(e);
153       }
154       e = GetDocEntryByNumber(0x0028,0x1202);
155       if (e)
156       {
157          RemoveEntryNoDestroy(e);
158       }
159       e = GetDocEntryByNumber(0x0028,0x1203);
160       if (e)
161       {
162           RemoveEntryNoDestroy(e);
163       }
164    }
165    Document::Write(fp,filetype);
166 }
167
168 //-----------------------------------------------------------------------------
169 // Print
170
171
172 //-----------------------------------------------------------------------------
173 // Public
174
175 /**
176  * \brief  This predicate, based on hopefully reasonable heuristics,
177  *         decides whether or not the current Header was properly parsed
178  *         and contains the mandatory information for being considered as
179  *         a well formed and usable Dicom/Acr File.
180  * @return true when Header is the one of a reasonable Dicom/Acr file,
181  *         false otherwise. 
182  */
183 bool Header::IsReadable()
184 {
185    if( !Document::IsReadable() )
186    {
187       return false;
188    }
189
190    std::string res = GetEntryByNumber(0x0028, 0x0005);
191    if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
192    {
193       return false; // Image Dimensions
194    }
195    if ( !GetDocEntryByNumber(0x0028, 0x0100) )
196    {
197       return false; // "Bits Allocated"
198    }
199    if ( !GetDocEntryByNumber(0x0028, 0x0101) )
200    {
201       return false; // "Bits Stored"
202    }
203    if ( !GetDocEntryByNumber(0x0028, 0x0102) )
204    {
205       return false; // "High Bit"
206    }
207    if ( !GetDocEntryByNumber(0x0028, 0x0103) )
208    {
209       return false; // "Pixel Representation" i.e. 'Sign'
210    }
211
212    return true;
213 }
214
215 /**
216  * \brief   Retrieve the number of columns of image.
217  * @return  The encountered size when found, 0 by default.
218  *          0 means the file is NOT USABLE. The caller will have to check
219  */
220 int Header::GetXSize()
221 {
222    std::string strSize;
223    strSize = GetEntryByNumber(0x0028,0x0011);
224    if ( strSize == GDCM_UNFOUND )
225    {
226       return 0;
227    }
228
229    return atoi( strSize.c_str() );
230 }
231
232 /**
233  * \brief   Retrieve the number of lines of image.
234  * \warning The defaulted value is 1 as opposed to Header::GetXSize()
235  * @return  The encountered size when found, 1 by default 
236  *          (The ACR-NEMA file contains a Signal, not an Image).
237  */
238 int Header::GetYSize()
239 {
240    std::string strSize = GetEntryByNumber(0x0028,0x0010);
241    if ( strSize != GDCM_UNFOUND )
242    {
243       return atoi( strSize.c_str() );
244    }
245    if ( IsDicomV3() )
246    {
247       return 0;
248    }
249
250    // The Rows (0028,0010) entry was optional for ACR/NEMA. It might
251    // hence be a signal (1d image). So we default to 1:
252    return 1;
253 }
254
255 /**
256  * \brief   Retrieve the number of planes of volume or the number
257  *          of frames of a multiframe.
258  * \warning When present we consider the "Number of Frames" as the third
259  *          dimension. When absent we consider the third dimension as
260  *          being the ACR-NEMA "Planes" tag content.
261  * @return  The encountered size when found, 1 by default (single image).
262  */
263 int Header::GetZSize()
264 {
265    // Both  DicomV3 and ACR/Nema consider the "Number of Frames"
266    // as the third dimension.
267    std::string strSize = GetEntryByNumber(0x0028,0x0008);
268    if ( strSize != GDCM_UNFOUND )
269    {
270       return atoi( strSize.c_str() );
271    }
272
273    // We then consider the "Planes" entry as the third dimension 
274    strSize = GetEntryByNumber(0x0028,0x0012);
275    if ( strSize != GDCM_UNFOUND )
276    {
277       return atoi( strSize.c_str() );
278    }
279
280    return 1;
281 }
282
283 /**
284   * \brief gets the info from 0028,0030 : Pixel Spacing
285   *             else 1.0
286   * @return X dimension of a pixel
287   */
288 float Header::GetXSpacing()
289 {
290    float xspacing, yspacing;
291    std::string strSpacing = GetEntryByNumber(0x0028,0x0030);
292
293    if ( strSpacing == GDCM_UNFOUND )
294    {
295       dbg.Verbose(0, "Header::GetXSpacing: unfound Pixel Spacing (0028,0030)");
296       return 1.;
297    }
298
299    int nbValues;
300    if( ( nbValues = sscanf( strSpacing.c_str(), 
301          "%f\\%f", &yspacing, &xspacing)) != 2 )
302    {
303       // if single value is found, xspacing is defaulted to yspacing
304       if ( nbValues == 1 )
305       {
306          return yspacing;
307       }
308    }
309    if ( xspacing == 0.)
310    {
311       dbg.Verbose(0, "Header::GetYSpacing: gdcmData/CT-MONO2-8-abdo.dcm problem");
312       // seems to be a bug in the header ...
313       sscanf( strSpacing.c_str(), "%f\\0\\%f", &yspacing, &xspacing);
314    }
315
316    return xspacing;
317 }
318
319 /**
320   * \brief gets the info from 0028,0030 : Pixel Spacing
321   *             else 1.0
322   * @return Y dimension of a pixel
323   */
324 float Header::GetYSpacing()
325 {
326    float yspacing = 0;
327    std::string strSpacing = GetEntryByNumber(0x0028,0x0030);
328   
329    if ( strSpacing == GDCM_UNFOUND )
330    {
331       dbg.Verbose(0, "Header::GetYSpacing: unfound Pixel Spacing (0028,0030)");
332       return 1.;
333     }
334
335    // if sscanf cannot read any float value, it won't affect yspacing
336    sscanf( strSpacing.c_str(), "%f", &yspacing);
337
338    return yspacing;
339
340
341 /**
342  * \brief gets the info from 0018,0088 : Space Between Slices
343  *                else from 0018,0050 : Slice Thickness
344  *                else 1.0
345  * @return Z dimension of a voxel-to be
346  */
347 float Header::GetZSpacing()
348 {
349    // Spacing Between Slices : distance entre le milieu de chaque coupe
350    // Les coupes peuvent etre :
351    //   jointives     (Spacing between Slices = Slice Thickness)
352    //   chevauchantes (Spacing between Slices < Slice Thickness)
353    //   disjointes    (Spacing between Slices > Slice Thickness)
354    // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
355    //   ca interesse le physicien de l'IRM, pas le visualisateur de volumes ...
356    //   Si le Spacing Between Slices est absent, 
357    //   on suppose que les coupes sont jointives
358    
359    std::string strSpacingBSlices = GetEntryByNumber(0x0018,0x0088);
360
361    if ( strSpacingBSlices == GDCM_UNFOUND )
362    {
363       dbg.Verbose(0, "Header::GetZSpacing: unfound StrSpacingBSlices");
364       std::string strSliceThickness = GetEntryByNumber(0x0018,0x0050);       
365       if ( strSliceThickness == GDCM_UNFOUND )
366       {
367          return 1.;
368       }
369       else
370       {
371          // if no 'Spacing Between Slices' is found, 
372          // we assume slices join together
373          // (no overlapping, no interslice gap)
374          // if they don't, we're fucked up
375          return atof( strSliceThickness.c_str() );
376       }
377    }
378    else
379    {
380       return atof( strSpacingBSlices.c_str() );
381    }
382 }
383
384 /**
385  *\brief gets the info from 0028,1052 : Rescale Intercept
386  * @return Rescale Intercept
387  */
388 float Header::GetRescaleIntercept()
389 {
390    float resInter = 0.;
391    /// 0028 1052 DS IMG Rescale Intercept
392    std::string strRescInter = GetEntryByNumber(0x0028,0x1052);
393    if ( strRescInter != GDCM_UNFOUND )
394    {
395       if( sscanf( strRescInter.c_str(), "%f", &resInter) != 1 )
396       {
397          // bug in the element 0x0028,0x1052
398          dbg.Verbose(0, "Header::GetRescaleIntercept: Rescale Slope "
399                         "is empty");
400       }
401    }
402
403    return resInter;
404 }
405
406 /**
407  *\brief   gets the info from 0028,1053 : Rescale Slope
408  * @return Rescale Slope
409  */
410 float Header::GetRescaleSlope()
411 {
412    float resSlope = 1.;
413    //0028 1053 DS IMG Rescale Slope
414    std::string strRescSlope = GetEntryByNumber(0x0028,0x1053);
415    if ( strRescSlope != GDCM_UNFOUND )
416    {
417       if( sscanf( strRescSlope.c_str(), "%f", &resSlope) != 1)
418       {
419          // bug in the element 0x0028,0x1053
420          dbg.Verbose(0, "Header::GetRescaleSlope: Rescale Slope is empty");
421       }
422    }
423
424    return resSlope;
425 }
426
427 /**
428  * \brief This function is intended to user who doesn't want 
429  *   to have to manage a LUT and expects to get an RBG Pixel image
430  *   (or a monochrome one ...) 
431  * \warning to be used with GetImagePixels()
432  * @return 1 if Gray level, 3 if Color (RGB, YBR or PALETTE COLOR)
433  */
434 int Header::GetNumberOfScalarComponents()
435 {
436    if ( GetSamplesPerPixel() == 3 )
437    {
438       return 3;
439    }
440       
441    // 0028 0100 US IMG Bits Allocated
442    // (in order no to be messed up by old RGB images)
443    if ( GetEntryByNumber(0x0028,0x0100) == "24" )
444    {
445       return 3;
446    }
447        
448    std::string strPhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
449
450    if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
451    {
452       if ( HasLUT() )// PALETTE COLOR is NOT enough
453       {
454          return 3;
455       }
456       else
457       {
458          return 1;
459       }
460    }
461
462    // beware of trailing space at end of string      
463    // DICOM tags are never of odd length
464    if ( strPhotometricInterpretation == GDCM_UNFOUND   || 
465         strPhotometricInterpretation == "MONOCHROME1 " || 
466         strPhotometricInterpretation == "MONOCHROME2 " )
467    {
468       return 1;
469    }
470    else
471    {
472       // we assume that *all* kinds of YBR are dealt with
473       return 3;
474    }
475 }
476
477 /**
478  * \brief This function is intended to user that DOESN'T want 
479  *  to get RGB pixels image when it's stored as a PALETTE COLOR image
480  *   - the (vtk) user is supposed to know how deal with LUTs - 
481  * \warning to be used with GetImagePixelsRaw()
482  * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
483  */
484 int Header::GetNumberOfScalarComponentsRaw()
485 {
486    // 0028 0100 US IMG Bits Allocated
487    // (in order no to be messed up by old RGB images)
488    if ( Header::GetEntryByNumber(0x0028,0x0100) == "24" )
489    {
490       return 3;
491    }
492
493    // we assume that *all* kinds of YBR are dealt with
494    return GetSamplesPerPixel();
495 }
496
497 //
498 // --------------  Remember ! ----------------------------------
499 //
500 // Image Position Patient                              (0020,0032):
501 // If not found (ACR_NEMA) we try Image Position       (0020,0030)
502 // If not found (ACR-NEMA), we consider Slice Location (0020,1041)
503 //                                   or Location       (0020,0050) 
504 // as the Z coordinate, 
505 // 0. for all the coordinates if nothing is found
506
507 // \todo find a way to inform the caller nothing was found
508 // \todo How to tell the caller a wrong number of values was found?
509 //
510 // ---------------------------------------------------------------
511 //
512
513 /**
514  * \brief gets the info from 0020,0032 : Image Position Patient
515  *                 else from 0020,0030 : Image Position (RET)
516  *                 else 0.
517  * @return up-left image corner X position
518  */
519 float Header::GetXOrigin()
520 {
521    float xImPos, yImPos, zImPos;  
522    std::string strImPos = GetEntryByNumber(0x0020,0x0032);
523
524    if ( strImPos == GDCM_UNFOUND )
525    {
526       dbg.Verbose(0, "Header::GetXImagePosition: unfound Image "
527                      "Position Patient (0020,0032)");
528       strImPos = GetEntryByNumber(0x0020,0x0030); // For ACR-NEMA images
529       if ( strImPos == GDCM_UNFOUND )
530       {
531          dbg.Verbose(0, "Header::GetXImagePosition: unfound Image "
532                         "Position (RET) (0020,0030)");
533          /// \todo How to tell the caller nothing was found ?
534          return 0.;
535       }
536    }
537
538    if( sscanf( strImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3 )
539    {
540       return 0.;
541    }
542
543    return xImPos;
544 }
545
546 /**
547  * \brief gets the info from 0020,0032 : Image Position Patient
548  *                 else from 0020,0030 : Image Position (RET)
549  *                 else 0.
550  * @return up-left image corner Y position
551  */
552 float Header::GetYOrigin()
553 {
554    float xImPos, yImPos, zImPos;
555    std::string strImPos = GetEntryByNumber(0x0020,0x0032);
556
557    if ( strImPos == GDCM_UNFOUND)
558    {
559       dbg.Verbose(0, "Header::GetYImagePosition: unfound Image "
560                      "Position Patient (0020,0032)");
561       strImPos = GetEntryByNumber(0x0020,0x0030); // For ACR-NEMA images
562       if ( strImPos == GDCM_UNFOUND )
563       {
564          dbg.Verbose(0, "Header::GetYImagePosition: unfound Image "
565                         "Position (RET) (0020,0030)");
566          /// \todo How to tell the caller nothing was found ?
567          return 0.;
568       }  
569    }
570
571    if( sscanf( strImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3 )
572    {
573       return 0.;
574    }
575
576    return yImPos;
577 }
578
579 /**
580  * \brief gets the info from 0020,0032 : Image Position Patient
581  *                 else from 0020,0030 : Image Position (RET)
582  *                 else from 0020,1041 : Slice Location
583  *                 else from 0020,0050 : Location
584  *                 else 0.
585  * @return up-left image corner Z position
586  */
587 float Header::GetZOrigin()
588 {
589    float xImPos, yImPos, zImPos; 
590    std::string strImPos = GetEntryByNumber(0x0020,0x0032);
591
592    if ( strImPos != GDCM_UNFOUND )
593    {
594       if( sscanf( strImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3)
595       {
596          dbg.Verbose(0, "Header::GetZImagePosition: wrong Image "
597                         "Position Patient (0020,0032)");
598          return 0.;  // bug in the element 0x0020,0x0032
599       }
600       else
601       {
602          return zImPos;
603       }
604    }
605
606    strImPos = GetEntryByNumber(0x0020,0x0030); // For ACR-NEMA images
607    if ( strImPos != GDCM_UNFOUND )
608    {
609       if( sscanf( strImPos.c_str(), 
610           "%f\\%f\\%f", &xImPos, &yImPos, &zImPos ) != 3 )
611       {
612          dbg.Verbose(0, "Header::GetZImagePosition: wrong Image Position (RET) (0020,0030)");
613          return 0.;  // bug in the element 0x0020,0x0032
614       }
615       else
616       {
617          return zImPos;
618       }
619    }
620
621    std::string strSliceLocation = GetEntryByNumber(0x0020,0x1041); // for *very* old ACR-NEMA images
622    if ( strSliceLocation != GDCM_UNFOUND )
623    {
624       if( sscanf( strSliceLocation.c_str(), "%f", &zImPos) != 1)
625       {
626          dbg.Verbose(0, "Header::GetZImagePosition: wrong Slice Location (0020,1041)");
627          return 0.;  // bug in the element 0x0020,0x1041
628       }
629       else
630       {
631          return zImPos;
632       }
633    }
634    dbg.Verbose(0, "Header::GetZImagePosition: unfound Slice Location (0020,1041)");
635
636    std::string strLocation = GetEntryByNumber(0x0020,0x0050);
637    if ( strLocation != GDCM_UNFOUND )
638    {
639       if( sscanf( strLocation.c_str(), "%f", &zImPos) != 1)
640       {
641          dbg.Verbose(0, "Header::GetZImagePosition: wrong Location (0020,0050)");
642          return 0.;  // bug in the element 0x0020,0x0050
643       }
644       else
645       {
646          return zImPos;
647       }
648    }
649    dbg.Verbose(0, "Header::GetYImagePosition: unfound Location (0020,0050)");  
650
651    return 0.; // Hopeless
652 }
653
654 /**
655  * \brief gets the info from 0020,0013 : Image Number else 0.
656  * @return image number
657  */
658 int Header::GetImageNumber()
659 {
660    // The function i atoi() takes the address of an area of memory as
661    // parameter and converts the string stored at that location to an integer
662    // using the external decimal to internal binary conversion rules. This may
663    // be preferable to sscanf() since atoi() is a much smaller, simpler and
664    // faster function. sscanf() can do all possible conversions whereas
665    // atoi() can only do single decimal integer conversions.
666    //0020 0013 IS REL Image Number
667    std::string strImNumber = GetEntryByNumber(0x0020,0x0013);
668    if ( strImNumber != GDCM_UNFOUND )
669    {
670       return atoi( strImNumber.c_str() );
671    }
672    return 0;   //Hopeless
673 }
674
675 /**
676  * \brief gets the info from 0008,0060 : Modality
677  * @return Modality Type
678  */
679 ModalityType Header::GetModality()
680 {
681    // 0008 0060 CS ID Modality
682    std::string strModality = GetEntryByNumber(0x0008,0x0060);
683    if ( strModality != GDCM_UNFOUND )
684    {
685            if ( strModality.find("AU") < strModality.length()) return AU;
686       else if ( strModality.find("AS") < strModality.length()) return AS;
687       else if ( strModality.find("BI") < strModality.length()) return BI;
688       else if ( strModality.find("CF") < strModality.length()) return CF;
689       else if ( strModality.find("CP") < strModality.length()) return CP;
690       else if ( strModality.find("CR") < strModality.length()) return CR;
691       else if ( strModality.find("CT") < strModality.length()) return CT;
692       else if ( strModality.find("CS") < strModality.length()) return CS;
693       else if ( strModality.find("DD") < strModality.length()) return DD;
694       else if ( strModality.find("DF") < strModality.length()) return DF;
695       else if ( strModality.find("DG") < strModality.length()) return DG;
696       else if ( strModality.find("DM") < strModality.length()) return DM;
697       else if ( strModality.find("DS") < strModality.length()) return DS;
698       else if ( strModality.find("DX") < strModality.length()) return DX;
699       else if ( strModality.find("ECG") < strModality.length()) return ECG;
700       else if ( strModality.find("EPS") < strModality.length()) return EPS;
701       else if ( strModality.find("FA") < strModality.length()) return FA;
702       else if ( strModality.find("FS") < strModality.length()) return FS;
703       else if ( strModality.find("HC") < strModality.length()) return HC;
704       else if ( strModality.find("HD") < strModality.length()) return HD;
705       else if ( strModality.find("LP") < strModality.length()) return LP;
706       else if ( strModality.find("LS") < strModality.length()) return LS;
707       else if ( strModality.find("MA") < strModality.length()) return MA;
708       else if ( strModality.find("MR") < strModality.length()) return MR;
709       else if ( strModality.find("NM") < strModality.length()) return NM;
710       else if ( strModality.find("OT") < strModality.length()) return OT;
711       else if ( strModality.find("PT") < strModality.length()) return PT;
712       else if ( strModality.find("RF") < strModality.length()) return RF;
713       else if ( strModality.find("RG") < strModality.length()) return RG;
714       else if ( strModality.find("RTDOSE")   < strModality.length()) return RTDOSE;
715       else if ( strModality.find("RTIMAGE")  < strModality.length()) return RTIMAGE;
716       else if ( strModality.find("RTPLAN")   < strModality.length()) return RTPLAN;
717       else if ( strModality.find("RTSTRUCT") < strModality.length()) return RTSTRUCT;
718       else if ( strModality.find("SM") < strModality.length()) return SM;
719       else if ( strModality.find("ST") < strModality.length()) return ST;
720       else if ( strModality.find("TG") < strModality.length()) return TG;
721       else if ( strModality.find("US") < strModality.length()) return US;
722       else if ( strModality.find("VF") < strModality.length()) return VF;
723       else if ( strModality.find("XA") < strModality.length()) return XA;
724       else if ( strModality.find("XC") < strModality.length()) return XC;
725
726       else
727       {
728          /// \todo throw error return value ???
729          /// specified <> unknow in our database
730          return Unknow;
731       }
732    }
733
734    return Unknow;
735 }
736
737 /**
738  * \brief   Retrieve the number of Bits Stored (actually used)
739  *          (as opposite to number of Bits Allocated)
740  * @return  The encountered number of Bits Stored, 0 by default.
741  *          0 means the file is NOT USABLE. The caller has to check it !
742  */
743 int Header::GetBitsStored()
744 {
745    std::string strSize = GetEntryByNumber( 0x0028, 0x0101 );
746    if ( strSize == GDCM_UNFOUND )
747    {
748       dbg.Verbose(0, "Header::GetBitsStored: this is supposed to "
749                      "be mandatory");
750       return 0;  // It's supposed to be mandatory
751                  // the caller will have to check
752    }
753    return atoi( strSize.c_str() );
754 }
755
756 /**
757  * \brief   Retrieve the high bit position.
758  * \warning The method defaults to 0 when information is absent.
759  *          The responsability of checking this value is left to the caller.
760  * @return  The high bit positin when present. 0 when absent.
761  */
762 int Header::GetHighBitPosition()
763 {
764    std::string strSize = GetEntryByNumber( 0x0028, 0x0102 );
765    if ( strSize == GDCM_UNFOUND )
766    {
767       dbg.Verbose(0, "Header::GetHighBitPosition: this is supposed "
768                      "to be mandatory");
769       return 0;
770    }
771    return atoi( strSize.c_str() );
772 }
773
774 /**
775  * \brief   Check wether the pixels are signed or UNsigned data.
776  * \warning The method defaults to false (UNsigned) when information is absent.
777  *          The responsability of checking this value is left to the caller.
778  * @return  True when signed, false when UNsigned
779  */
780 bool Header::IsSignedPixelData()
781 {
782    std::string strSize = GetEntryByNumber( 0x0028, 0x0103 );
783    if ( strSize == GDCM_UNFOUND )
784    {
785       dbg.Verbose(0, "Header::IsSignedPixelData: this is supposed "
786                      "to be mandatory");
787       return false;
788    }
789    int sign = atoi( strSize.c_str() );
790    if ( sign == 0 ) 
791    {
792       return false;
793    }
794    return true;
795 }
796
797 /**
798  * \brief   Retrieve the number of Bits Allocated
799  *          (8, 12 -compacted ACR-NEMA files, 16, ...)
800  * @return  The encountered number of Bits Allocated, 0 by default.
801  *          0 means the file is NOT USABLE. The caller has to check it !
802  */
803 int Header::GetBitsAllocated()
804 {
805    std::string strSize = GetEntryByNumber(0x0028,0x0100);
806    if ( strSize == GDCM_UNFOUND )
807    {
808       dbg.Verbose(0, "Header::GetBitsStored: this is supposed to "
809                      "be mandatory");
810       return 0; // It's supposed to be mandatory
811                 // the caller will have to check
812    }
813    return atoi( strSize.c_str() );
814 }
815
816 /**
817  * \brief   Retrieve the number of Samples Per Pixel
818  *          (1 : gray level, 3 : RGB -1 or 3 Planes-)
819  * @return  The encountered number of Samples Per Pixel, 1 by default.
820  *          (Gray level Pixels)
821  */
822 int Header::GetSamplesPerPixel()
823 {
824    std::string strSize = GetEntryByNumber(0x0028,0x0002);
825    if ( strSize == GDCM_UNFOUND )
826    {
827       dbg.Verbose(0, "Header::GetBitsStored: this is supposed to "
828                      "be mandatory");
829       return 1; // Well, it's supposed to be mandatory ...
830                 // but sometimes it's missing : *we* assume Gray pixels
831    }
832    return atoi( strSize.c_str() );
833 }
834
835 /**
836  * \brief   Check wether this a monochrome picture or not by accessing
837  *          the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
838  * @return  true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
839  */
840 bool Header::IsMonochrome()
841 {
842    std::string PhotometricInterp = GetEntryByNumber( 0x0028, 0x0004 );
843    if (   PhotometricInterp == "MONOCHROME1 "
844        || PhotometricInterp == "MONOCHROME2 " )
845    {
846       return true;
847    }
848    if ( PhotometricInterp == GDCM_UNFOUND )
849    {
850       dbg.Verbose(0, "Header::IsMonochrome: absent Photometric "
851                      "Interpretation");
852    }
853    return false;
854 }
855
856 /**
857  * \brief   Check wether this a "PALETTE COLOR" picture or not by accessing
858  *          the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
859  * @return  true when "PALETTE COLOR". False otherwise.
860  */
861 bool Header::IsPaletteColor()
862 {
863    std::string PhotometricInterp = GetEntryByNumber( 0x0028, 0x0004 );
864    if (   PhotometricInterp == "PALETTE COLOR " )
865    {
866       return true;
867    }
868    if ( PhotometricInterp == GDCM_UNFOUND )
869    {
870       dbg.Verbose(0, "Header::IsPaletteColor: absent Photometric "
871                      "Interpretation");
872    }
873    return false;
874 }
875
876 /**
877  * \brief   Check wether this a "YBR_FULL" color picture or not by accessing
878  *          the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
879  * @return  true when "YBR_FULL". False otherwise.
880  */
881 bool Header::IsYBRFull()
882 {
883    std::string PhotometricInterp = GetEntryByNumber( 0x0028, 0x0004 );
884    if (   PhotometricInterp == "YBR_FULL" )
885    {
886       return true;
887    }
888    if ( PhotometricInterp == GDCM_UNFOUND )
889    {
890       dbg.Verbose(0, "Header::IsYBRFull: absent Photometric "
891                      "Interpretation");
892    }
893    return false;
894 }
895
896 /**
897  * \brief   Retrieve the Planar Configuration for RGB images
898  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
899  * @return  The encountered Planar Configuration, 0 by default.
900  */
901 int Header::GetPlanarConfiguration()
902 {
903    std::string strSize = GetEntryByNumber(0x0028,0x0006);
904    if ( strSize == GDCM_UNFOUND )
905    {
906       return 0;
907    }
908    return atoi( strSize.c_str() );
909 }
910
911 /**
912  * \brief   Return the size (in bytes) of a single pixel of data.
913  * @return  The size in bytes of a single pixel of data; 0 by default
914  *          0 means the file is NOT USABLE; the caller will have to check
915  */
916 int Header::GetPixelSize()
917 {
918    // 0028 0100 US IMG Bits Allocated
919    // (in order no to be messed up by old RGB images)
920    //   if (Header::GetEntryByNumber(0x0028,0x0100) == "24")
921    //      return 3;
922
923    std::string pixelType = GetPixelType();
924    if ( pixelType ==  "8U" || pixelType == "8S" )
925    {
926       return 1;
927    }
928    if ( pixelType == "16U" || pixelType == "16S")
929    {
930       return 2;
931    }
932    if ( pixelType == "32U" || pixelType == "32S")
933    {
934       return 4;
935    }
936    if ( pixelType == "FD" )
937    {
938       return 8;
939    }
940    dbg.Verbose(0, "Header::GetPixelSize: Unknown pixel type");
941    return 0;
942 }
943
944 /**
945  * \brief   Build the Pixel Type of the image.
946  *          Possible values are:
947  *          - 8U  unsigned  8 bit,
948  *          - 8S    signed  8 bit,
949  *          - 16U unsigned 16 bit,
950  *          - 16S   signed 16 bit,
951  *          - 32U unsigned 32 bit,
952  *          - 32S   signed 32 bit,
953  *          - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
954  * \warning 12 bit images appear as 16 bit.
955  *          24 bit images appear as 8 bit
956  * @return  0S if nothing found. NOT USABLE file. The caller has to check
957  */
958 std::string Header::GetPixelType()
959 {
960    std::string bitsAlloc = GetEntryByNumber(0x0028, 0x0100); // Bits Allocated
961    if ( bitsAlloc == GDCM_UNFOUND )
962    {
963       dbg.Verbose(0, "Header::GetPixelType: unfound Bits Allocated");
964       bitsAlloc = "16";
965    }
966
967    if ( bitsAlloc == "64" )
968    {
969       return "FD";
970    }
971    if ( bitsAlloc == "12" )
972    {
973       // It will be unpacked
974       bitsAlloc = "16";
975    }
976    else if ( bitsAlloc == "24" )
977    {
978       // (in order no to be messed up
979       bitsAlloc = "8";  // by old RGB images)
980    }
981
982    std::string sign = GetEntryByNumber(0x0028, 0x0103);//"Pixel Representation"
983
984    if (sign == GDCM_UNFOUND )
985    {
986       dbg.Verbose(0, "Header::GetPixelType: unfound Pixel Representation");
987       bitsAlloc = "0";
988    }
989    if ( sign == "0" )
990    {
991       sign = "U";
992    }
993    else
994    {
995       sign = "S";
996    }
997    return bitsAlloc + sign;
998 }
999
1000
1001 /**
1002  * \brief   Recover the offset (from the beginning of the file) 
1003  *          of *image* pixels (not *icone image* pixels, if any !)
1004  * @return Pixel Offset
1005  */
1006 size_t Header::GetPixelOffset()
1007 {
1008    DocEntry* pxlElement = GetDocEntryByNumber(GrPixel,NumPixel);
1009    if ( pxlElement )
1010    {
1011       return pxlElement->GetOffset();
1012    }
1013    else
1014    {
1015 #ifdef GDCM_DEBUG
1016       std::cout << "Big trouble : Pixel Element ("
1017                 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found"
1018                 << std::endl;  
1019 #endif //GDCM_DEBUG
1020       return 0;
1021    }
1022 }
1023
1024 /// \todo TODO : unify those two (previous one and next one)
1025 /**
1026  * \brief   Recover the pixel area length (in Bytes)
1027  * @return Pixel Element Length, as stored in the header
1028  *         (NOT the memory space necessary to hold the Pixels 
1029  *          -in case of embeded compressed image-)
1030  *         0 : NOT USABLE file. The caller has to check.
1031  */
1032 size_t Header::GetPixelAreaLength()
1033 {
1034    DocEntry* pxlElement = GetDocEntryByNumber(GrPixel,NumPixel);
1035    if ( pxlElement )
1036    {
1037       return pxlElement->GetLength();
1038    }
1039    else
1040    {
1041 #ifdef GDCM_DEBUG
1042       std::cout << "Big trouble : Pixel Element ("
1043                 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found"
1044                 << std::endl;
1045 #endif //GDCM_DEBUG
1046       return 0;
1047    }
1048 }
1049
1050 /**
1051   * \brief tells us if LUT are used
1052   * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1053   *          are NOT considered as LUT, since nobody knows
1054   *          how to deal with them
1055   *          Please warn me if you know sbdy that *does* know ... jprx
1056   * @return true if LUT Descriptors and LUT Tables were found 
1057   */
1058 bool Header::HasLUT()
1059 {
1060    // Check the presence of the LUT Descriptors, and LUT Tables    
1061    // LutDescriptorRed    
1062    if ( !GetDocEntryByNumber(0x0028,0x1101) )
1063    {
1064       return false;
1065    }
1066    // LutDescriptorGreen 
1067    if ( !GetDocEntryByNumber(0x0028,0x1102) )
1068    {
1069       return false;
1070    }
1071    // LutDescriptorBlue 
1072    if ( !GetDocEntryByNumber(0x0028,0x1103) )
1073    {
1074       return false;
1075    }
1076    // Red Palette Color Lookup Table Data
1077    if ( !GetDocEntryByNumber(0x0028,0x1201) )
1078    {
1079       return false;
1080    }
1081    // Green Palette Color Lookup Table Data       
1082    if ( !GetDocEntryByNumber(0x0028,0x1202) )
1083    {
1084       return false;
1085    }
1086    // Blue Palette Color Lookup Table Data      
1087    if ( !GetDocEntryByNumber(0x0028,0x1203) )
1088    {
1089       return false;
1090    }
1091
1092    // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1093    //         NOT taken into account, but we don't know how to use it ...   
1094    return true;
1095 }
1096
1097 /**
1098   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1099   *             else 0
1100   * @return Lookup Table number of Bits , 0 by default
1101   *          when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1102   * @ return bit number of each LUT item 
1103   */
1104 int Header::GetLUTNbits()
1105 {
1106    std::vector<std::string> tokens;
1107    int lutNbits;
1108
1109    //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1110    //                                = Lookup Table Desc-Blue
1111    // Consistency already checked in GetLUTLength
1112    std::string lutDescription = GetEntryByNumber(0x0028,0x1101);
1113    if ( lutDescription == GDCM_UNFOUND )
1114    {
1115       return 0;
1116    }
1117
1118    tokens.clear(); // clean any previous value
1119    Util::Tokenize ( lutDescription, tokens, "\\" );
1120    //LutLength=atoi(tokens[0].c_str());
1121    //LutDepth=atoi(tokens[1].c_str());
1122
1123    lutNbits = atoi( tokens[2].c_str() );
1124    tokens.clear();
1125
1126    return lutNbits;
1127 }
1128
1129 /**
1130  * \brief Accesses the info from 0002,0010 : Transfert Syntax and TS
1131  *        else 1.
1132  * @return The full Transfert Syntax Name (as opposed to Transfert Syntax UID)
1133  */
1134 std::string Header::GetTransfertSyntaxName()
1135 {
1136    // use the TS (TS : Transfert Syntax)
1137    std::string transfertSyntax = GetEntryByNumber(0x0002,0x0010);
1138
1139    if ( transfertSyntax == GDCM_NOTLOADED )
1140    {
1141       std::cout << "Transfert Syntax not loaded. " << std::endl
1142                << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE"
1143                << std::endl;
1144       return "Uncompressed ACR-NEMA";
1145    }
1146    if ( transfertSyntax == GDCM_UNFOUND )
1147    {
1148       dbg.Verbose(0, "Header::GetTransfertSyntaxName:"
1149                      " unfound Transfert Syntax (0002,0010)");
1150       return "Uncompressed ACR-NEMA";
1151    }
1152
1153    while ( ! isdigit(transfertSyntax[transfertSyntax.length()-1]) )
1154    {
1155       transfertSyntax.erase(transfertSyntax.length()-1, 1);
1156    }
1157    // we do it only when we need it
1158    TS* ts         = Global::GetTS();
1159    std::string tsName = ts->GetValue( transfertSyntax );
1160
1161    //delete ts; /// \todo Seg Fault when deleted ?!
1162    return tsName;
1163 }
1164
1165 /**
1166  * \brief Sets the Pixel Area size in the Header
1167  *        --> not-for-rats function
1168  * @param ImageDataSize new Pixel Area Size
1169  *        warning : nothing else is checked
1170  */
1171 void Header::SetImageDataSize(size_t ImageDataSize)
1172 {
1173    ///FIXME I don't understand this code wh ydo we set two times 'car' ?
1174    std::string car = Util::Format("%d", ImageDataSize);
1175  
1176    DocEntry *a = GetDocEntryByNumber(GrPixel, NumPixel);
1177    a->SetLength(ImageDataSize);
1178
1179    ImageDataSize += 8;
1180    car = Util::Format("%d", ImageDataSize);
1181
1182    SetEntryByNumber(car, GrPixel, NumPixel);
1183 }
1184
1185 //-----------------------------------------------------------------------------
1186 // Protected
1187
1188 /**
1189  * \brief anonymize a Header (removes Patient's personal info)
1190  *        (read the code to see which ones ...)
1191  */
1192 bool Header::AnonymizeHeader()
1193 {
1194    // If exist, replace by spaces
1195    SetEntryByNumber ("  ",0x0010, 0x2154); // Telephone   
1196    SetEntryByNumber ("  ",0x0010, 0x1040); // Adress
1197    SetEntryByNumber ("  ",0x0010, 0x0020); // Patient ID
1198
1199    DocEntry* patientNameHE = GetDocEntryByNumber (0x0010, 0x0010);
1200   
1201    if ( patientNameHE ) // we replace it by Study Instance UID (why not)
1202    {
1203       std::string studyInstanceUID =  GetEntryByNumber (0x0020, 0x000d);
1204       if ( studyInstanceUID != GDCM_UNFOUND )
1205       {
1206          ReplaceOrCreateByNumber(studyInstanceUID, 0x0010, 0x0010);
1207       }
1208       else
1209       {
1210          ReplaceOrCreateByNumber(std::string("anonymised"), 0x0010, 0x0010);
1211       }
1212    }
1213
1214   // Just for fun :-(
1215   // (if any) remove or replace all the stuff that contains a Date
1216
1217 //0008 0012 DA ID Instance Creation Date
1218 //0008 0020 DA ID Study Date
1219 //0008 0021 DA ID Series Date
1220 //0008 0022 DA ID Acquisition Date
1221 //0008 0023 DA ID Content Date
1222 //0008 0024 DA ID Overlay Date
1223 //0008 0025 DA ID Curve Date
1224 //0008 002a DT ID Acquisition Datetime
1225 //0018 9074 DT ACQ Frame Acquisition Datetime
1226 //0018 9151 DT ACQ Frame Reference Datetime
1227 //0018 a002 DT ACQ Contribution Date Time
1228 //0020 3403 SH REL Modified Image Date (RET)
1229 //0032 0032 DA SDY Study Verified Date
1230 //0032 0034 DA SDY Study Read Date
1231 //0032 1000 DA SDY Scheduled Study Start Date
1232 //0032 1010 DA SDY Scheduled Study Stop Date
1233 //0032 1040 DA SDY Study Arrival Date
1234 //0032 1050 DA SDY Study Completion Date
1235 //0038 001a DA VIS Scheduled Admission Date
1236 //0038 001c DA VIS Scheduled Discharge Date
1237 //0038 0020 DA VIS Admitting Date
1238 //0038 0030 DA VIS Discharge Date
1239 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1240 //0040 0004 DA PRC Scheduled Procedure Step End Date
1241 //0040 0244 DA PRC Performed Procedure Step Start Date
1242 //0040 0250 DA PRC Performed Procedure Step End Date
1243 //0040 2004 DA PRC Issue Date of Imaging Service Request
1244 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1245 //0040 4011 DT PRC Expected Completion Date and Time
1246 //0040 a030 DT PRC Verification Date Time
1247 //0040 a032 DT PRC Observation Date Time
1248 //0040 a120 DT PRC DateTime
1249 //0040 a121 DA PRC Date
1250 //0040 a13a DT PRC Referenced Datetime
1251 //0070 0082 DA ??? Presentation Creation Date
1252 //0100 0420 DT ??? SOP Autorization Date and Time
1253 //0400 0105 DT ??? Digital Signature DateTime
1254 //2100 0040 DA PJ Creation Date
1255 //3006 0008 DA SSET Structure Set Date
1256 //3008 0024 DA ??? Treatment Control Point Date
1257 //3008 0054 DA ??? First Treatment Date
1258 //3008 0056 DA ??? Most Recent Treatment Date
1259 //3008 0162 DA ??? Safe Position Exit Date
1260 //3008 0166 DA ??? Safe Position Return Date
1261 //3008 0250 DA ??? Treatment Date
1262 //300a 0006 DA RT RT Plan Date
1263 //300a 022c DA RT Air Kerma Rate Reference Date
1264 //300e 0004 DA RT Review Date
1265
1266    return true;
1267 }
1268
1269 /**
1270   * \brief gets the info from 0020,0037 : Image Orientation Patient
1271   * @param iop adress of the (6)float aray to receive values
1272   * @return cosines of image orientation patient
1273   */
1274 void Header::GetImageOrientationPatient( float iop[6] )
1275 {
1276    std::string strImOriPat;
1277    //iop is supposed to be float[6]
1278    iop[0] = iop[1] = iop[2] = iop[3] = iop[4] = iop[5] = 0.;
1279
1280    // 0020 0037 DS REL Image Orientation (Patient)
1281    if ( (strImOriPat = GetEntryByNumber(0x0020,0x0037)) != GDCM_UNFOUND )
1282    {
1283       if( sscanf( strImOriPat.c_str(), "%f\\%f\\%f\\%f\\%f\\%f", 
1284           &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
1285       {
1286          dbg.Verbose(0, "Header::GetImageOrientationPatient: "
1287                         "wrong Image Orientation Patient (0020,0037)");
1288       }
1289    }
1290    //For ACR-NEMA
1291    // 0020 0035 DS REL Image Orientation (RET)
1292    else if ( (strImOriPat = GetEntryByNumber(0x0020,0x0035)) != GDCM_UNFOUND )
1293    {
1294       if( sscanf( strImOriPat.c_str(), "%f\\%f\\%f\\%f\\%f\\%f", 
1295           &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
1296       {
1297          dbg.Verbose(0, "Header::GetImageOrientationPatient: "
1298                         "wrong Image Orientation Patient (0020,0035)");
1299       }
1300    }
1301 }
1302
1303 //-----------------------------------------------------------------------------
1304 // Private
1305
1306 //-----------------------------------------------------------------------------
1307
1308 } // end namespace gdcm