]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
a8966f1512a7e57e6a2cf2dda41b2e15ae199947
[gdcm.git] / src / gdcmHeader.cxx
1 // gdcmHeader.cxx
2 //-----------------------------------------------------------------------------
3 #include "gdcmHeader.h"
4
5 #include <stdio.h>
6 #include <cerrno>
7 // For nthos:
8 #ifdef _MSC_VER
9 #include <winsock.h>
10 #else
11 #include <netinet/in.h>
12 #endif
13 #include <cctype>    // for isalpha
14
15 #ifdef GDCM_NO_ANSI_STRING_STREAM
16 #  include <strstream>
17 #  define  ostringstream ostrstream
18 # else
19 #  include <sstream>
20 #endif
21
22 #include "gdcmUtil.h"
23 #include "gdcmTS.h"
24
25 //-----------------------------------------------------------------------------
26 // Refer to gdcmHeader::CheckSwap()
27 const unsigned int gdcmHeader::HEADER_LENGTH_TO_READ = 256;
28
29 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
30 const unsigned int gdcmHeader::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
31
32 //-----------------------------------------------------------------------------
33 // Constructor / Destructor
34 /**
35  * \ingroup gdcmHeader
36  * \brief   
37  * @param   InFilename
38  * @param   exception_on_error
39  * @param   enable_sequences = true to allow the header 
40  *          to be parsed *inside* the SeQuences, 
41  *          when they have an actual length 
42  */
43 gdcmHeader::gdcmHeader(const char *InFilename, 
44                        bool exception_on_error,
45                        bool enable_sequences ) {
46    if (enable_sequences)
47       enableSequences = 1;
48    else
49       enableSequences = 0;
50    
51    SetMaxSizeLoadElementValue(MAX_SIZE_LOAD_ELEMENT_VALUE);
52    filename = InFilename;
53    Initialise();
54    if ( !OpenFile(exception_on_error))
55       return;
56    ParseHeader();
57    LoadElements();
58    CloseFile();
59 }
60
61 /**
62  * \ingroup gdcmHeader
63  * \brief   
64  * @param   exception_on_error
65  */
66 gdcmHeader::gdcmHeader(bool exception_on_error) {
67   SetMaxSizeLoadElementValue(MAX_SIZE_LOAD_ELEMENT_VALUE);
68   Initialise();
69 }
70
71 /**
72  * \ingroup gdcmHeader
73  * \brief   Canonical destructor.
74  */
75 gdcmHeader::~gdcmHeader (void) {
76   dicom_vr =   (gdcmVR*)0; 
77   Dicts    =   (gdcmDictSet*)0;
78   RefPubDict = (gdcmDict*)0;
79   RefShaDict = (gdcmDict*)0;
80   return;
81 }
82
83 //-----------------------------------------------------------------------------
84 // Print
85
86 /**
87   * \ingroup gdcmHeader
88   * \brief
89   * @return
90   */ 
91 void gdcmHeader::PrintPubElVal(std::ostream & os) {
92    PubElValSet.Print(os);
93 }
94
95 /**
96   * \ingroup gdcmHeader
97   * \brief 
98   * @return
99   */  
100 void gdcmHeader::PrintPubDict(std::ostream & os) {
101    RefPubDict->Print(os);
102 }
103
104 //-----------------------------------------------------------------------------
105 // Public
106
107 /**
108  * \ingroup gdcmHeader
109  * \brief  This predicate, based on hopefully reasonable heuristics,
110  *         decides whether or not the current gdcmHeader was properly parsed
111  *         and contains the mandatory information for being considered as
112  *         a well formed and usable image.
113  * @return true when gdcmHeader is the one of a reasonable Dicom file,
114  *         false otherwise. 
115  */
116 bool gdcmHeader::IsReadable(void) {
117    std::string res = GetPubElValByNumber(0x0028, 0x0005);
118    if (       res != GDCM_UNFOUND
119       && atoi(res.c_str()) > 4 ) {
120       return false; // Image Dimensions
121    }
122    if ( GetPubElValByNumber(0x0028, 0x0100) == GDCM_UNFOUND )
123       return false; // "Bits Allocated"
124    if ( GetPubElValByNumber(0x0028, 0x0101) == GDCM_UNFOUND )
125       return false; // "Bits Stored"
126    if ( GetPubElValByNumber(0x0028, 0x0102) == GDCM_UNFOUND )
127       return false; // "High Bit"
128    if ( GetPubElValByNumber(0x0028, 0x0103) == GDCM_UNFOUND )
129       return false; // "Pixel Representation"
130    return true;
131 }
132
133 /**
134  * \ingroup gdcmHeader
135  * \brief   Determines if the Transfer Syntax was already encountered
136  *          and if it corresponds to a ImplicitVRLittleEndian one.
137  *
138  * @return  True when ImplicitVRLittleEndian found. False in all other cases.
139  */
140 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
141    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
142    if ( !Element )
143       return false;
144    LoadElementValueSafe(Element);
145    std::string Transfer = Element->GetValue();
146    if ( Transfer == "1.2.840.10008.1.2" )
147       return true;
148    return false;
149 }
150
151 /**
152  * \ingroup gdcmHeader
153  * \brief   Determines if the Transfer Syntax was already encountered
154  *          and if it corresponds to a ExplicitVRLittleEndian one.
155  *
156  * @return  True when ExplicitVRLittleEndian found. False in all other cases.
157  */
158 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
159    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
160    if ( !Element )
161       return false;
162    LoadElementValueSafe(Element);
163    std::string Transfer = Element->GetValue();
164    if ( Transfer == "1.2.840.10008.1.2.1" )
165       return true;
166    return false;
167 }
168
169 /**
170  * \ingroup gdcmHeader
171  * \brief   Determines if the Transfer Syntax was already encountered
172  *          and if it corresponds to a DeflatedExplicitVRLittleEndian one.
173  *
174  * @return  True when DeflatedExplicitVRLittleEndian found. False in all other cases.
175  */
176 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
177    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
178    if ( !Element )
179       return false;
180    LoadElementValueSafe(Element);
181    std::string Transfer = Element->GetValue();
182    if ( Transfer == "1.2.840.10008.1.2.1.99" )
183       return true;
184    return false;
185 }
186
187 /**
188  * \ingroup gdcmHeader
189  * \brief   Determines if the Transfer Syntax was already encountered
190  *          and if it corresponds to a Explicit VR Big Endian one.
191  *
192  * @return  True when big endian found. False in all other cases.
193  */
194 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
195    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
196    if ( !Element )
197       return false;
198    LoadElementValueSafe(Element);
199    std::string Transfer = Element->GetValue();
200    if ( Transfer == "1.2.840.10008.1.2.2" )  //1.2.2 ??? A verifier !
201       return true;
202    return false;
203 }
204
205 /**
206  * \ingroup gdcmHeader
207  * \brief   Determines if the Transfer Syntax was already encountered
208  *          and if it corresponds to a JPEGBaseLineProcess1 one.
209  *
210  * @return  True when JPEGBaseLineProcess1found. False in all other cases.
211  */
212 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
213    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
214    if ( !Element )
215       return false;
216    LoadElementValueSafe(Element);
217    std::string Transfer = Element->GetValue();
218    if ( Transfer == "1.2.840.10008.1.2.4.50" )
219       return true;
220    return false;
221 }
222
223 /**
224  * \ingroup gdcmHeader
225  * \brief   Determines if the Transfer Syntax was already encountered
226  *          and if it corresponds to a JPEGExtendedProcess2-4 one.
227  *
228  * @return  True when JPEGExtendedProcess2-4 found. False in all other cases.
229  */
230 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
231    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
232    if ( !Element )
233       return false;
234    LoadElementValueSafe(Element);
235    std::string Transfer = Element->GetValue();
236    if ( Transfer == "1.2.840.10008.1.2.4.51" )
237       return true;
238    return false;
239 }
240
241 /**
242  * \ingroup gdcmHeader
243  * \brief   Determines if the Transfer Syntax was already encountered
244  *          and if it corresponds to a JPEGExtendeProcess3-5 one.
245  *
246  * @return  True when JPEGExtendedProcess3-5 found. False in all other cases.
247  */
248 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
249    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
250    if ( !Element )
251       return false;
252    LoadElementValueSafe(Element);
253    std::string Transfer = Element->GetValue();
254    if ( Transfer == "1.2.840.10008.1.2.4.52" )
255       return true;
256    return false;
257 }
258
259 /**
260  * \ingroup gdcmHeader
261  * \brief   Determines if the Transfer Syntax was already encountered
262  *          and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
263  *
264  * @return  True when JPEGSpectralSelectionProcess6-8 found. False in all
265  *          other cases.
266  */
267 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
268    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
269    if ( !Element )
270       return false;
271    LoadElementValueSafe(Element);
272    std::string Transfer = Element->GetValue();
273    if ( Transfer == "1.2.840.10008.1.2.4.53" )
274       return true;
275    return false;
276 }
277
278 /**
279  * \ingroup gdcmHeader
280  * \brief   Determines if the Transfer Syntax was already encountered
281  *          and if it corresponds to a RLE Lossless one.
282  *
283  * @return  True when RLE Lossless found. False in all
284  *          other cases.
285  */
286 bool gdcmHeader::IsRLELossLessTransferSyntax(void) {
287    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
288    if ( !Element )
289       return false;
290    LoadElementValueSafe(Element);
291    std::string Transfer = Element->GetValue();
292    if ( Transfer == "1.2.840.10008.1.2.5" )
293       return true;
294    return false;
295 }
296
297 /**
298  * \ingroup gdcmHeader
299  * \brief   
300  *
301  * @return 
302  */
303 bool gdcmHeader::IsJPEGLossless(void) {
304    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
305     // faire qq chose d'intelligent a la place de Ã§a
306    if ( !Element )
307       return false;
308    LoadElementValueSafe(Element);
309    const char * Transfert = Element->GetValue().c_str();
310    if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
311    if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
312    if (Element->GetValue() == "1.2.840.10008.1.2.4.57")   return true;
313
314    return false;
315 }
316
317 /**
318  * \ingroup gdcmHeader
319  * \brief   Determines if the Transfer Syntax was already encountered
320  *          and if it corresponds to a JPEG200 one.0
321  *
322  * @return  True when JPEG2000 (Lossly or LossLess) found. False in all
323  *          other cases.
324  */
325 bool gdcmHeader::IsJPEG2000(void) {
326    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
327    if ( !Element )
328       return false;
329    LoadElementValueSafe(Element);
330    std::string Transfer = Element->GetValue();
331    if (    (Transfer == "1.2.840.10008.1.2.4.90") 
332         || (Transfer == "1.2.840.10008.1.2.4.91") )
333       return true;
334    return false;
335 }
336
337 /**
338  * \ingroup gdcmHeader
339  * \brief   Predicate for dicom version 3 file.
340  * @return  True when the file is a dicom version 3.
341  */
342 bool gdcmHeader::IsDicomV3(void) {
343    if (   (filetype == ExplicitVR)
344        || (filetype == ImplicitVR) )
345       return true;
346    return false;
347 }
348
349 /**
350  * \ingroup gdcmHeader
351  * \brief  
352  * @return 
353  */
354 FileType gdcmHeader::GetFileType(void)
355 {
356    return(filetype);
357 }
358
359 /**
360  * \ingroup gdcmHeader
361  * \brief   Retrieve the number of columns of image.
362  * @return  The encountered size when found, 0 by default.
363  */
364 int gdcmHeader::GetXSize(void) {
365    // We cannot check for "Columns" because the "Columns" tag is present
366    // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
367    std::string StrSize = GetPubElValByNumber(0x0028,0x0011);
368    if (StrSize == GDCM_UNFOUND)
369       return 0;
370    return atoi(StrSize.c_str());
371 }
372
373 /**
374  * \ingroup gdcmHeader
375  * \brief   Retrieve the number of lines of image.
376  * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
377  * @return  The encountered size when found, 1 by default.
378  */
379 int gdcmHeader::GetYSize(void) {
380    // We cannot check for "Rows" because the "Rows" tag is present
381    // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
382    std::string StrSize = GetPubElValByNumber(0x0028,0x0010);
383    if (StrSize != GDCM_UNFOUND)
384       return atoi(StrSize.c_str());
385    if ( IsDicomV3() )
386       return 0;
387    else
388       // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
389       // hence be a signal (1d image). So we default to 1:
390       return 1;
391 }
392
393 /**
394  * \ingroup gdcmHeader
395  * \brief   Retrieve the number of planes of volume or the number
396  *          of frames of a multiframe.
397  * \warning When present we consider the "Number of Frames" as the third
398  *          dimension. When absent we consider the third dimension as
399  *          being the "Planes" tag content.
400  * @return  The encountered size when found, 1 by default.
401  */
402 int gdcmHeader::GetZSize(void) {
403    // Both  DicomV3 and ACR/Nema consider the "Number of Frames"
404    // as the third dimension.
405    std::string StrSize = GetPubElValByNumber(0x0028,0x0008);
406    if (StrSize != GDCM_UNFOUND)
407       return atoi(StrSize.c_str());
408
409    // We then consider the "Planes" entry as the third dimension [we
410    // cannot retrieve by name since "Planes tag is present both in
411    // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary]. 
412    StrSize = GetPubElValByNumber(0x0028,0x0012);
413    if (StrSize != GDCM_UNFOUND)
414       return atoi(StrSize.c_str());
415    return 1;
416 }
417
418 /**
419  * \ingroup gdcmHeader
420  * \brief   Retrieve the number of Bits Stored
421  *          (as opposite to number of Bits Allocated)
422  * 
423  * @return  The encountered number of Bits Stored, 0 by default.
424  */
425 int gdcmHeader::GetBitsStored(void) { 
426    std::string StrSize = GetPubElValByNumber(0x0028,0x0101);
427    if (StrSize == GDCM_UNFOUND)
428       return 1;
429    return atoi(StrSize.c_str());
430 }
431
432 /**
433  * \ingroup gdcmHeader
434  * \brief   Retrieve the number of Bits Allocated
435  *          (8, 12 -compacted ACR-NEMA files, 16, ...)
436  * 
437  * @return  The encountered number of Bits Allocated, 0 by default.
438  */
439 int gdcmHeader::GetBitsAllocated(void) { 
440    std::string StrSize = GetPubElValByNumber(0x0028,0x0100);
441    if (StrSize == GDCM_UNFOUND)
442       return 1;
443    return atoi(StrSize.c_str());
444 }
445
446 /**
447  * \ingroup gdcmHeader
448  * \brief   Retrieve the number of Samples Per Pixel
449  *          (1 : gray level, 3 : RGB -1 or 3 Planes-)
450  * 
451  * @return  The encountered number of Samples Per Pixel, 1 by default.
452  */
453 int gdcmHeader::GetSamplesPerPixel(void) { 
454    std::string StrSize = GetPubElValByNumber(0x0028,0x0002);
455    if (StrSize == GDCM_UNFOUND)
456       return 1; // Well, it's supposed to be mandatory ...
457    return atoi(StrSize.c_str());
458 }
459
460 /**
461  * \ingroup gdcmHeader
462  * \brief   Retrieve the Planar Configuration for RGB images
463  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
464  * 
465  * @return  The encountered Planar Configuration, 0 by default.
466  */
467 int gdcmHeader::GetPlanarConfiguration(void) { 
468    std::string StrSize = GetPubElValByNumber(0x0028,0x0006);
469    if (StrSize == GDCM_UNFOUND)
470       return 0;
471    return atoi(StrSize.c_str());
472 }
473
474 /**
475  * \ingroup gdcmHeader
476  * \brief   Return the size (in bytes) of a single pixel of data.
477  * @return  The size in bytes of a single pixel of data.
478  *
479  */
480 int gdcmHeader::GetPixelSize(void) {
481    std::string PixelType = GetPixelType();
482    if (PixelType == "8U"  || PixelType == "8S")
483       return 1;
484    if (PixelType == "16U" || PixelType == "16S")
485       return 2;
486    if (PixelType == "32U" || PixelType == "32S")
487       return 4;
488    dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
489    return 0;
490 }
491
492 /**
493  * \ingroup gdcmHeader
494  * \brief   Build the Pixel Type of the image.
495  *          Possible values are:
496  *          - 8U  unsigned  8 bit,
497  *          - 8S    signed  8 bit,
498  *          - 16U unsigned 16 bit,
499  *          - 16S   signed 16 bit,
500  *          - 32U unsigned 32 bit,
501  *          - 32S   signed 32 bit,
502  * \warning 12 bit images appear as 16 bit.
503  * \        24 bit images appear as 8 bit
504  * @return  
505  */
506 std::string gdcmHeader::GetPixelType(void) {
507    std::string BitsAlloc;
508    BitsAlloc = GetPubElValByNumber(0x0028, 0x0100); // Bits Allocated
509    if (BitsAlloc == GDCM_UNFOUND) {
510       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
511       BitsAlloc = std::string("16");
512    }
513    if (BitsAlloc == "12")            // It will be unpacked
514       BitsAlloc = std::string("16");
515    else if (BitsAlloc == "24")       // (in order no to be messed up
516       BitsAlloc = std::string("8");  // by old RGB images)
517      
518    std::string Signed;
519    Signed = GetPubElValByNumber(0x0028, 0x0103); // "Pixel Representation"
520    if (Signed == GDCM_UNFOUND) {
521       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
522       BitsAlloc = std::string("0");
523    }
524    if (Signed == "0")
525       Signed = std::string("U");
526    else
527       Signed = std::string("S");
528
529    return( BitsAlloc + Signed);
530 }
531
532 /**
533  * \ingroup gdcmHeader
534  * \brief   Recover the offset (from the beginning of the file) of the pixels.
535  */
536 size_t gdcmHeader::GetPixelOffset(void) {
537    // If this file complies with the norm we should encounter the
538    // "Image Location" tag (0x0028,  0x0200). This tag contains the
539    // the group that contains the pixel data (hence the "Pixel Data"
540    // is found by indirection through the "Image Location").
541    // Inside the group pointed by "Image Location" the searched element
542    // is conventionally the element 0x0010 (when the norm is respected).
543    // When the "Image Location" is absent we default to group 0x7fe0.
544    guint16 grPixel;
545    guint16 numPixel;
546    std::string ImageLocation = GetPubElValByNumber(0x0028, 0x0200);
547    if ( ImageLocation == GDCM_UNFOUND ) { // Image Location
548       grPixel = 0x7fe0;
549    } else {
550       grPixel = (guint16) atoi( ImageLocation.c_str() );
551    }
552    if (grPixel != 0x7fe0)
553       // This is a kludge for old dirty Philips imager.
554       numPixel = 0x1010;
555    else
556       numPixel = 0x0010;
557          
558    gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
559                                                               numPixel);
560    if (PixelElement)
561       return PixelElement->GetOffset();
562    else
563       return 0;
564 }
565
566 /**
567  * \ingroup gdcmHeader
568  * \brief   Recover the pixel area length (in Bytes) .
569  */
570 size_t gdcmHeader::GetPixelAreaLength(void) {
571    // If this file complies with the norm we should encounter the
572    // "Image Location" tag (0x0028,  0x0200). This tag contains the
573    // the group that contains the pixel data (hence the "Pixel Data"
574    // is found by indirection through the "Image Location").
575    // Inside the group pointed by "Image Location" the searched element
576    // is conventionally the element 0x0010 (when the norm is respected).
577    // When the "Image Location" is absent we default to group 0x7fe0.
578    guint16 grPixel;
579    guint16 numPixel;
580    std::string ImageLocation = GetPubElValByNumber(0x0028, 0x0200);
581    if ( ImageLocation == GDCM_UNFOUND ) {
582       grPixel = 0x7fe0;
583    } else {
584       grPixel = (guint16) atoi( ImageLocation.c_str() );
585    }
586    if (grPixel != 0x7fe0)
587       // This is a kludge for old dirty Philips imager.
588       numPixel = 0x1010;
589    else
590       numPixel = 0x0010;
591          
592    gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
593                                                               numPixel);
594    if (PixelElement)
595       return PixelElement->GetLength();
596    else
597       return 0;
598 }
599
600 /**
601   * \ingroup gdcmHeader
602   * \brief tells us if LUT are used
603   * \warning Right now, Segmented xxx Palette Color Lookup Table Data
604   * \        are NOT considered as LUT, since nobody knows
605   *\         how to deal with them
606   * @return int acts as a Boolean 
607   */
608 bool gdcmHeader::HasLUT(void) {
609
610    // Check the presence of the LUT Descriptors 
611    if (GetPubElValByNumber(0x0028,0x1101) == GDCM_UNFOUND)
612       return false;
613    // LutDescriptorGreen 
614    if (GetPubElValByNumber(0x0028,0x1102) == GDCM_UNFOUND)
615       return false;
616    // LutDescriptorBlue 
617    if (GetPubElValByNumber(0x0028,0x1103) == GDCM_UNFOUND)
618       return false;
619    //  It is not enough
620    // we check also 
621    if (GetPubElValByNumber(0x0028,0x1201) == GDCM_UNFOUND)
622       return false;  
623    if (GetPubElValByNumber(0x0028,0x1202) == GDCM_UNFOUND)
624       return false;
625    if (GetPubElValByNumber(0x0028,0x1203) == GDCM_UNFOUND)
626       return false;   
627    return true;
628 }
629
630 /**
631   * \ingroup gdcmHeader
632   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
633   * \           else 0
634   * @return Lookup Table nBit 
635   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ] 
636   */
637 int gdcmHeader::GetLUTNbits(void) {
638    std::vector<std::string> tokens;
639    //int LutLength;
640    //int LutDepth;
641    int LutNbits;
642    //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
643    // Consistency already checked in GetLUTLength
644    std::string LutDescription = GetPubElValByNumber(0x0028,0x1101);
645    if (LutDescription == GDCM_UNFOUND)
646       return 0;
647    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
648    Tokenize (LutDescription, tokens, "\\");
649    //LutLength=atoi(tokens[0].c_str());
650    //LutDepth=atoi(tokens[1].c_str());
651    LutNbits=atoi(tokens[2].c_str());
652    tokens.clear();
653    return LutNbits;
654 }
655
656 /**
657   * \ingroup gdcmHeader
658   * \brief builts Red/Green/Blue/Alpha LUT from Header
659   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
660   * \        and (0028,1101),(0028,1102),(0028,1102)  
661   * \          - xxx Palette Color Lookup Table Descriptor - are found
662   * \        and (0028,1201),(0028,1202),(0028,1202) 
663   * \          - xxx Palette Color Lookup Table Data - are found 
664   * \warning does NOT deal with :
665   * \ 0028 1100 Gray Lookup Table Descriptor (Retired)
666   * \ 0028 1221 Segmented Red Palette Color Lookup Table Data
667   * \ 0028 1222 Segmented Green Palette Color Lookup Table Data
668   * \ 0028 1223 Segmented Blue Palette Color Lookup Table Data 
669   * \ no known Dicom reader deails with them :-(
670   * @return Lookup Table RGBA
671   */ 
672 unsigned char * gdcmHeader::GetLUTRGBA(void) {
673 // Not so easy : see 
674 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
675 // and  OT-PAL-8-face.dcm
676
677 //  if Photometric Interpretation # PALETTE COLOR, no LUT to be done
678    if (gdcmHeader::GetPubElValByNumber(0x0028,0x0004) != "PALETTE COLOR ") {
679         return NULL;
680    }  
681
682    int lengthR, debR, nbitsR;
683    int lengthG, debG, nbitsG;
684    int lengthB, debB, nbitsB;
685    
686 // Get info from Lut Descriptors
687 // (the 3 LUT descriptors may be different)    
688    std::string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
689    if (LutDescriptionR == GDCM_UNFOUND)
690       return NULL;
691    std::string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
692    if (LutDescriptionG == GDCM_UNFOUND)
693       return NULL;   
694    std::string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
695    if (LutDescriptionB == GDCM_UNFOUND)
696       return NULL;
697       
698    std::vector<std::string> tokens;
699       
700    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
701    Tokenize (LutDescriptionR, tokens, "\\");
702    lengthR=atoi(tokens[0].c_str()); // Red LUT length in Bytes
703    debR   =atoi(tokens[1].c_str()); // subscript of the first Lut Value
704    nbitsR =atoi(tokens[2].c_str()); // Lut item size (in Bits)
705    tokens.clear();
706    
707    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
708    Tokenize (LutDescriptionG, tokens, "\\");
709    lengthG=atoi(tokens[0].c_str()); // Green LUT length in Bytes
710    debG   =atoi(tokens[1].c_str());
711    nbitsG =atoi(tokens[2].c_str());
712    tokens.clear();  
713    
714    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
715    Tokenize (LutDescriptionB, tokens, "\\");
716    lengthB=atoi(tokens[0].c_str()); // Blue LUT length in Bytes
717    debB   =atoi(tokens[1].c_str());
718    nbitsB =atoi(tokens[2].c_str());
719    tokens.clear();
720  
721 // Load LUTs into memory, (as they were stored on disk)
722    unsigned char *lutR = (unsigned char *)
723                                    GetPubElValVoidAreaByNumber(0x0028,0x1201);
724    unsigned char *lutG = (unsigned char *)
725                                    GetPubElValVoidAreaByNumber(0x0028,0x1202);
726    unsigned char *lutB = (unsigned char *)
727                                    GetPubElValVoidAreaByNumber(0x0028,0x1203); 
728    
729    if (!lutR || !lutG || !lutB ) {
730         return NULL;
731    } 
732  // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT 
733    
734   unsigned char *LUTRGBA = (unsigned char *)calloc(1024,1); // 256 * 4 (R, G, B, Alpha) 
735   if (!LUTRGBA) {
736      return NULL;
737   }
738   memset(LUTRGBA, 0, 1024);
739         // Bits Allocated
740    int nb;
741    std::string str_nb = GetPubElValByNumber(0x0028,0x0100);
742    if (str_nb == GDCM_UNFOUND ) {
743       nb = 16;
744    } else {
745       nb = atoi(str_nb.c_str() );
746    }  
747   int mult;
748   
749   if (nbitsR==16 && nb==8) // when LUT item size is different than pixel size
750      mult=2;               // high byte must be = low byte 
751   else                     // See PS 3.3-2003 C.11.1.1.2 p 619
752      mult=1; 
753  
754    // if we get a black image, let's just remove the '+1'
755    // from 'i*mult+1' and check again 
756    // if it works, we shall have to check the 3 Palettes
757    // to see which byte is ==0 (first one, or second one)
758    // and fix the code
759    // We give up the checking to avoid some overhead 
760   unsigned char *a;      
761   int i;
762
763   a = LUTRGBA+0;
764   for(i=0;i<lengthR;i++) {
765      *a = lutR[i*mult+1]; 
766      a+=4;       
767   }        
768   a = LUTRGBA+1;
769   for(i=0;i<lengthG;i++) {
770      *a = lutG[i*mult+1]; 
771      a+=4;       
772   }  
773   a = LUTRGBA+2;
774   for(i=0;i<lengthB;i++) {
775      *a = lutB[i*mult+1]; 
776      a+=4;       
777   }  
778   a = LUTRGBA+3;
779   for(i=0;i<256;i++) {
780      *a = 1; // Alpha component
781      a+=4; 
782   } 
783       
784 //How to free the now useless LUTs?
785
786 //free(LutR); free(LutB); free(LutG);
787   return(LUTRGBA);   
788
789
790 /**
791  * \ingroup gdcmHeader
792  * \brief gets the info from 0002,0010 : Transfert Syntax
793  * \      else 1.
794  * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
795  */
796 std::string gdcmHeader::GetTransfertSyntaxName(void) { 
797    // use the gdcmTS (TS : Transfert Syntax)
798    std::string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
799    if (TransfertSyntax == GDCM_UNFOUND) {
800       dbg.Verbose(0, "gdcmHeader::GetTransfertSyntaxName: unfound Transfert Syntax (0002,0010)");
801       return "Uncompressed ACR-NEMA";
802    }
803    // we do it only when we need it
804    gdcmTS * ts = gdcmGlobal::GetTS();
805    std::string tsName=ts->GetValue(TransfertSyntax);
806    //delete ts; // Seg Fault when deleted ?!
807    return tsName;
808 }
809
810 /**
811  * \ingroup gdcmHeader
812  * \brief   Searches within the public dictionary for element value of
813  *          a given tag.
814  * @param   tagName name of the searched element.
815  * @return  Corresponding element value when it exists, and the string
816  *          GDCM_UNFOUND ("gdcm::Unfound") otherwise.
817  */
818 std::string gdcmHeader::GetPubElValByName(std::string tagName) {
819    gdcmDictEntry *dictEntry = RefPubDict->GetTagByName(tagName); 
820    if( dictEntry == NULL)
821       return GDCM_UNFOUND;
822    return(PubElValSet.GetElValueByNumber(dictEntry->GetGroup(),
823                                          dictEntry->GetElement()));  
824 }
825
826 /**
827  * \ingroup gdcmHeader
828  * \brief   Searches within the elements parsed with the public dictionary for
829  *          the element value representation of a given tag.
830  *
831  *          Obtaining the VR (Value Representation) might be needed by caller
832  *          to convert the string typed content to caller's native type 
833  *          (think of C++ vs Python). The VR is actually of a higher level
834  *          of semantics than just the native C++ type.
835  * @param   tagName name of the searched element.
836  * @return  Corresponding element value representation when it exists,
837  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
838  */
839 std::string gdcmHeader::GetPubElValRepByName(std::string tagName) {
840    gdcmDictEntry *dictEntry = RefPubDict->GetTagByName(tagName); 
841    if( dictEntry == NULL)
842       return GDCM_UNFOUND;   
843    gdcmElValue* elem =  PubElValSet.GetElementByNumber(
844                                          dictEntry->GetGroup(),
845                                          dictEntry->GetElement());                                      
846    return elem->GetVR();
847 }
848
849 /**
850  * \ingroup gdcmHeader
851  * \brief   Searches within the public dictionary for element value of
852  *          a given tag.
853  * @param   group Group of the researched tag.
854  * @param   element Element of the researched tag.
855  * @return  Corresponding element value when it exists, and the string
856  *          GDCM_UNFOUND ("gdcm::Unfound") otherwise.
857  */
858 std::string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
859    return PubElValSet.GetElValueByNumber(group, element);
860 }
861
862 /**
863  * \ingroup gdcmHeader
864  * \brief   Searches within the public dictionary for element value
865  *          representation of a given tag.
866  *
867  *          Obtaining the VR (Value Representation) might be needed by caller
868  *          to convert the string typed content to caller's native type 
869  *          (think of C++ vs Python). The VR is actually of a higher level
870  *          of semantics than just the native C++ type.
871  * @param   group Group of the researched tag.
872  * @param   element Element of the researched tag.
873  * @return  Corresponding element value representation when it exists,
874  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
875  */
876 std::string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
877    gdcmElValue* elem =  PubElValSet.GetElementByNumber(group, element);
878    if ( !elem )
879       return GDCM_UNFOUND;
880    return elem->GetVR();
881 }
882
883 /**
884  * \ingroup gdcmHeader
885  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
886  *          through tag name and modifies it's content with the given value.
887  * @param   content new value to substitute with
888  * @param   tagName name of the tag to be modified
889  */
890 bool gdcmHeader::SetPubElValByName(std::string content, std::string tagName) {
891    //return (  PubElValSet.SetElValueByName (content, tagName) );
892    gdcmDictEntry *dictEntry = RefPubDict->GetTagByName(tagName); 
893    if( dictEntry == NULL)
894       return false;       
895    return(PubElValSet.SetElValueByNumber(content,
896                                          dictEntry->GetGroup(),
897                                          dictEntry->GetElement()));   
898 }
899
900 /**
901  * \ingroup gdcmHeader
902  * \brief   Accesses an existing gdcmElValue (i.e. a Dicom Element)
903  *          in the PubElValSet of this instance
904  *          through it's (group, element) and modifies it's content with
905  *          the given value.
906  * @param   content new value to substitute with
907  * @param   group   group of the Dicom Element to modify
908  * @param   element element of the Dicom Element to modify
909  */
910 bool gdcmHeader::SetPubElValByNumber(std::string content, guint16 group,
911                                     guint16 element)
912                                     
913 //TODO  : homogeneiser les noms : SetPubElValByNumber   
914 //                    qui appelle PubElValSet.SetElValueByNumber 
915 //        pourquoi pas            SetPubElValueByNumber ??
916 {
917    return (  PubElValSet.SetElValueByNumber (content, group, element) );
918 }
919
920 /**
921  * \ingroup gdcmHeader
922  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
923  *          through it's (group, element) and modifies it's length with
924  *          the given value.
925  * \warning Use with extreme caution.
926  * @param   length new length to substitute with
927  * @param   group   group of the ElVal to modify
928  * @param   element element of the ElVal to modify
929  * @return  1 on success, 0 otherwise.
930  */
931
932 bool gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
933                                     guint16 element) {
934         return (  PubElValSet.SetElValueLengthByNumber (length, group, element) );
935 }
936
937 /**
938  * \ingroup gdcmHeader
939  * \brief   Searches within elements parsed with the public dictionary 
940  *          and then within the elements parsed with the shadow dictionary
941  *          for the element value of a given tag.
942  * @param   tagName name of the searched element.
943  * @return  Corresponding element value when it exists,
944  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
945  */
946 std::string gdcmHeader::GetElValByName(std::string tagName) {
947    std::string pub = GetPubElValByName(tagName);
948       return pub;
949 }
950
951 /**
952  * \ingroup gdcmHeader
953  * \brief   Searches within elements parsed with the public dictionary 
954  *          and then within the elements parsed with the shadow dictionary
955  *          for the element value representation of a given tag.
956  *
957  *          Obtaining the VR (Value Representation) might be needed by caller
958  *          to convert the string typed content to caller's native type 
959  *          (think of C++ vs Python). The VR is actually of a higher level
960  *          of semantics than just the native C++ type.
961  * @param   tagName name of the searched element.
962  * @return  Corresponding element value representation when it exists,
963  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
964  */
965 std::string gdcmHeader::GetElValRepByName(std::string tagName) {
966    std::string pub = GetPubElValRepByName(tagName);
967       return pub;
968 }
969
970 /**
971  * \ingroup gdcmHeader
972  * \brief   Searches within elements parsed with the public dictionary 
973  *          and then within the elements parsed with the shadow dictionary
974  *          for the element value of a given tag.
975  * @param   group Group of the searched tag.
976  * @param   element Element of the searched tag.
977  * @return  Corresponding element value representation when it exists,
978  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
979  */
980 std::string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
981    std::string pub = GetPubElValByNumber(group, element);
982       return pub;
983 }
984
985 /**
986  * \ingroup gdcmHeader
987  * \brief   Searches within elements parsed with the public dictionary 
988  *          and then within the elements parsed with the shadow dictionary
989  *          for the element value representation of a given tag.
990  *
991  *          Obtaining the VR (Value Representation) might be needed by caller
992  *          to convert the string typed content to caller's native type 
993  *          (think of C++ vs Python). The VR is actually of a higher level
994  *          of semantics than just the native C++ type.
995  * @param   group Group of the searched tag.
996  * @param   element Element of the searched tag.
997  * @return  Corresponding element value representation when it exists,
998  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
999  */
1000 std::string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1001    std::string pub = GetPubElValRepByNumber(group, element);
1002       return pub;
1003 }
1004
1005 /**
1006  * \ingroup gdcmElValSet
1007  * \brief  Sets the value (string) of the target Dicom Element
1008  * @param   content string value of the Dicom Element
1009  * @param   tagName name of the searched Dicom Element.
1010  * @return  true when found
1011  */
1012 bool gdcmHeader::SetElValueByName(std::string content,
1013                                   std::string tagName) {
1014                                     
1015    gdcmDictEntry *dictEntry = RefPubDict->GetTagByName(tagName); 
1016    if( dictEntry == NULL)
1017       return false;                                 
1018                                                                                                     
1019                                     
1020    TagKey key = gdcmDictEntry::TranslateToKey(dictEntry->GetGroup(), 
1021                                               dictEntry->GetElement());
1022    if ( ! PubElValSet.GetTagHt().count(key))
1023       return false;
1024    int l = content.length();
1025    if(l%2) {  // Odd length are padded with a space (020H).
1026       l++;
1027       content = content + '\0';
1028    }
1029       
1030    //tagHt[key]->SetValue(content);   
1031    gdcmElValue * a;
1032    IterHT p;
1033    TagElValueHT::iterator p2;
1034    // DO NOT remove the following lines : they explain the stuff   
1035    //p= tagHt.equal_range(key); // get a pair of iterators first-last synonym
1036    //p2=p.first;                // iterator on the first synonym 
1037    //a=p2->second;              // H Table target column (2-nd col)
1038     
1039    // or, easier :
1040    a = ((PubElValSet.GetTagHt().equal_range(key)).first)->second; 
1041        
1042    a-> SetValue(content); 
1043    
1044    //std::string vr = tagHt[key]->GetVR();
1045    std::string vr = a->GetVR();
1046    
1047    guint32 lgr;
1048    if( (vr == "US") || (vr == "SS") ) 
1049       lgr = 2;
1050    else if( (vr == "UL") || (vr == "SL") )
1051       lgr = 4;
1052    else
1053       lgr = l;     
1054    //tagHt[key]->SetLength(lgr);
1055    a->SetLength(lgr);   
1056    return true;
1057 }
1058
1059 /**
1060  * \ingroup gdcmHeader
1061  * \brief   
1062  * @param   exception_on_error
1063  * @return  
1064  */
1065 FILE *gdcmHeader::OpenFile(bool exception_on_error)
1066   throw(gdcmFileError) {
1067   fp=fopen(filename.c_str(),"rb");
1068   if(exception_on_error) {
1069     if(!fp)
1070       throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
1071   }
1072
1073   if ( fp ) {
1074      guint16 zero;
1075      fread(&zero,  (size_t)2, (size_t)1, fp);
1076
1077     //ACR -- or DICOM with no Preamble
1078     if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
1079        return(fp);
1080
1081     //DICOM
1082     fseek(fp, 126L, SEEK_CUR);
1083     char dicm[4];
1084     fread(dicm,  (size_t)4, (size_t)1, fp);
1085     if( memcmp(dicm, "DICM", 4) == 0 )
1086        return(fp);
1087
1088     fclose(fp);
1089     dbg.Verbose(0, "gdcmHeader::gdcmHeader not DICOM/ACR", filename.c_str());
1090   }
1091   else {
1092     dbg.Verbose(0, "gdcmHeader::gdcmHeader cannot open file", filename.c_str());
1093   }
1094   return(NULL);
1095 }
1096
1097 /**
1098  * \ingroup gdcmHeader
1099  * \brief   
1100  * @return  TRUE if the close was successfull 
1101  */
1102 bool gdcmHeader::CloseFile(void) {
1103   int closed = fclose(fp);
1104   fp = (FILE *)0;
1105   if (! closed)
1106      return false;
1107   return true;
1108 }
1109
1110 /**
1111  * \ingroup gdcmHeader
1112  * \brief   Parses the header of the file but WITHOUT loading element values.
1113  */
1114 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1115    gdcmElValue * newElValue = (gdcmElValue *)0;
1116    
1117    rewind(fp);
1118    CheckSwap();
1119    while ( (newElValue = ReadNextElement()) ) { 
1120       SkipElementValue(newElValue);
1121       PubElValSet.Add(newElValue);
1122    }
1123 }
1124
1125 /**
1126  * \ingroup gdcmHeader
1127  * \brief
1128  * @return integer, acts as a Boolean
1129  */ 
1130 bool gdcmHeader::Write(FILE * fp, FileType type) {
1131
1132    // TODO : move the following lines (and a lot of others, to be written)
1133    // to a future function CheckAndCorrectHeader
1134
1135    if (type == ImplicitVR) {
1136       std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
1137       ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
1138       
1139       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1140       //      values with a VR of UI shall be padded with a single trailing null
1141       //      Dans le cas suivant on doit pader manuellement avec un 0
1142       
1143       PubElValSet.SetElValueLengthByNumber(18, 0x0002, 0x0010);
1144    } 
1145
1146    if (type == ExplicitVR) {
1147       std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
1148       ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
1149       
1150       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1151       //      values with a VR of UI shall be padded with a single trailing null
1152       //      Dans le cas suivant on doit pader manuellement avec un 0
1153       
1154       PubElValSet.SetElValueLengthByNumber(20, 0x0002, 0x0010);
1155    }
1156
1157    return PubElValSet.Write(fp, type);
1158 }
1159
1160 /**
1161  * \ingroup   gdcmFile
1162  * \brief Sets the Pixel Area size in the Header
1163  *        --> not-for-rats function
1164  * 
1165  * \warning WARNING doit-etre etre publique ? 
1166  * TODO : y aurait il un inconvenient Ã  fusionner ces 2 fonctions
1167  *
1168  * @param ImageDataSize new Pixel Area Size
1169  *        warning : nothing else is checked
1170  */
1171 void gdcmHeader::SetImageDataSize(size_t ImageDataSize) {
1172    std::string content1;
1173    char car[20];        
1174    // Assumes ElValue (0x7fe0, 0x0010) exists ...       
1175    sprintf(car,"%d",ImageDataSize);
1176  
1177    gdcmElValue *a = GetElValueByNumber(0x7fe0, 0x0010);
1178    a->SetLength(ImageDataSize);
1179                 
1180    ImageDataSize+=8;
1181    sprintf(car,"%d",ImageDataSize);
1182    content1=car;        
1183    SetPubElValByNumber(content1, 0x7fe0, 0x0000);
1184 }
1185
1186 /**
1187  * \ingroup gdcmHeader
1188  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1189  *          processor order.
1190  * @return  The properly swaped 32 bits integer.
1191  */
1192 guint32 gdcmHeader::SwapLong(guint32 a) {
1193    switch (sw) {
1194    case    0 :
1195       break;
1196    case 4321 :
1197       a=(   ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000)    | 
1198             ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1199       break;
1200    
1201    case 3412 :
1202       a=(   ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1203       break;
1204    
1205    case 2143 :
1206       a=(    ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1207       break;
1208    default :
1209       dbg.Error(" gdcmHeader::SwapLong : unset swap code");
1210       a=0;
1211    }
1212    return(a);
1213 }
1214
1215 /**
1216  * \ingroup gdcmHeader
1217  * \brief   Swaps the bytes so they agree with the processor order
1218  * @return  The properly swaped 16 bits integer.
1219  */
1220 guint16 gdcmHeader::SwapShort(guint16 a) {
1221    if ( (sw==4321)  || (sw==2143) )
1222       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1223    return (a);
1224 }
1225
1226 //-----------------------------------------------------------------------------
1227 // Protected
1228 /**
1229  * \ingroup gdcmHeader
1230  * \brief   
1231  *
1232  * @return 
1233  */
1234 gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1235
1236    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1237    if (!elValue) {
1238       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1239                   "failed to Locate gdcmElValue");
1240       return (gdcmElValue*)0;
1241    }
1242    return elValue;
1243 }
1244
1245 /**
1246  * \ingroup gdcmHeader
1247  * \brief   Checks if a given ElValue (group,number) 
1248  * \ exists in the Public ElValSet
1249  * @param   Group
1250  * @param   Elem
1251  * @return  integer acts as a boolean  
1252  */
1253 bool gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1254    return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1255 }
1256
1257 /**
1258  * \ingroup gdcmHeader
1259  * \brief   Gets (from Header) the offset  of a 'non string' element value 
1260  * \        (LoadElementValue has already be executed)
1261  * @param   Group
1262  * @param   Elem
1263  * @return File Offset of the Element Value 
1264  */
1265 size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1266    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1267    if (!elValue) {
1268       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1269                       "failed to Locate gdcmElValue");
1270       return (size_t)0;
1271    }
1272    return elValue->GetOffset();
1273 }
1274
1275 /**
1276  * \ingroup gdcmHeader
1277  * \brief   Gets (from Header) a 'non string' element value 
1278  * \        (LoadElementValue has already be executed)  
1279  * @param   Group
1280  * @param   Elem
1281  * @return Pointer to the 'non string' area
1282  */
1283 void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1284    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1285    if (!elValue) {
1286       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1287                   "failed to Locate gdcmElValue");
1288       return (NULL);
1289    }
1290    return elValue->GetVoidArea();
1291 }
1292
1293 /**
1294  * \ingroup       gdcmHeader
1295  * \brief         Loads (from disk) the element content 
1296  *                when a string is not suitable
1297  */
1298 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1299    gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1300    if ( !Element )
1301       return NULL;
1302    size_t o =(size_t)Element->GetOffset();
1303    fseek(fp, o, SEEK_SET);
1304    int l=Element->GetLength();
1305    void * a = malloc(l);
1306    if(!a) {
1307         return NULL;
1308    }  
1309    /* int res = */ PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1310    // TODO check the result 
1311    size_t l2 = fread(a, 1, l ,fp);
1312    if(l != l2) {
1313         free(a);
1314         return NULL;
1315    }
1316    return a;  
1317 }
1318
1319 /**
1320  * \ingroup gdcmHeader
1321  * \brief   TODO
1322  * @param   Value
1323  * @param   Group
1324  * @param   Elem
1325  * \return integer acts as a boolean
1326  */
1327 bool gdcmHeader::ReplaceOrCreateByNumber(std::string Value, 
1328                                         guint16 Group, guint16 Elem ) {
1329         // TODO : FIXME JPRx
1330         // curieux, non ?
1331         // on (je) cree une Elvalue ne contenant pas de valeur
1332         // on l'ajoute au ElValSet
1333         // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1334         // --> devrait pouvoir etre fait + simplement ???
1335    if (CheckIfExistByNumber(Group, Elem) == 0) {
1336       gdcmElValue* a =NewElValueByNumber(Group, Elem);
1337       if (a == NULL) 
1338          return false;
1339       PubElValSet.Add(a);
1340    }   
1341    PubElValSet.SetElValueByNumber(Value, Group, Elem);
1342    return(true);
1343 }   
1344
1345 /**
1346  * \ingroup gdcmHeader
1347  * \brief   Modify (or Creates if not found) an element
1348  * @param   Value new value
1349  * @param   Group
1350  * @param   Elem
1351  * \return integer acts as a boolean 
1352  * 
1353  */
1354 bool gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1355
1356    gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1357    // TODO : check if fails
1358    PubElValSet.Add(nvElValue);
1359    std::string v = Value;       
1360    PubElValSet.SetElValueByNumber(v, Group, Elem);
1361    return(true);
1362 }  
1363
1364 /**
1365  * \ingroup gdcmHeader
1366  * \brief   Set a new value if the invoked element exists
1367  *          Seems to be useless !!!
1368  * @param   Value
1369  * @param   Group
1370  * @param   Elem
1371  * \return integer acts as a boolean 
1372  */
1373 bool gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1374
1375    //gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1376    std::string v = Value;       
1377    PubElValSet.SetElValueByNumber(v, Group, Elem);
1378    return true;
1379
1380
1381 //-----------------------------------------------------------------------------
1382 // Private
1383 /**
1384  * \ingroup gdcmHeader
1385  * \brief   Loads the element values of all the elements present in the
1386  *          public tag based hash table.
1387  */
1388 void gdcmHeader::LoadElements(void) {
1389    rewind(fp);
1390    
1391    // We don't use any longer the HashTable, since a lot a stuff is missing
1392    // when SeQuences were encountered 
1393    //  
1394    //TagElValueHT ht = PubElValSet.GetTagHt();
1395    //for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1396    //     LoadElementValue(tag->second);
1397    //}
1398    
1399      for (ListTag::iterator i = GetPubListElem().begin();  
1400            i != GetPubListElem().end();
1401            ++i){
1402         LoadElementValue(*i);   
1403      }    
1404     
1405    rewind(fp);
1406
1407    // Load 'non string' values   
1408    std::string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);   
1409    if( PhotometricInterpretation == "PALETTE COLOR " ){ 
1410       LoadElementVoidArea(0x0028,0x1200);  // gray LUT   
1411       LoadElementVoidArea(0x0028,0x1201);  // R    LUT
1412       LoadElementVoidArea(0x0028,0x1202);  // G    LUT
1413       LoadElementVoidArea(0x0028,0x1203);  // B    LUT
1414       
1415       LoadElementVoidArea(0x0028,0x1221);  // Segmented Red   Palette Color LUT Data
1416       LoadElementVoidArea(0x0028,0x1222);  // Segmented Green Palette Color LUT Data
1417       LoadElementVoidArea(0x0028,0x1223);  // Segmented Blue  Palette Color LUT Data
1418    }
1419
1420    // --------------------------------------------------------------
1421    // Special Patch to allow gdcm to read ACR-LibIDO formated images
1422    //
1423    // if recognition code tells us we deal with a LibIDO image
1424    // we switch lineNumber and columnNumber
1425    //
1426    std::string RecCode; 
1427    RecCode = GetPubElValByNumber(0x0008, 0x0010);
1428    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1429        RecCode == "CANRME_AILIBOD1_1." ) {
1430          filetype = ACR_LIBIDO; 
1431          std::string rows    = GetPubElValByNumber(0x0028, 0x0010);
1432          std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1433          SetPubElValByNumber(columns, 0x0028, 0x0010);
1434          SetPubElValByNumber(rows   , 0x0028, 0x0011);
1435    }
1436    // ----------------- End of Special Patch ----------------
1437 }
1438
1439 /**
1440  * \ingroup       gdcmHeader
1441  * \brief         Loads the element content if it's length is not bigger
1442  *                than the value specified with
1443  *                gdcmHeader::SetMaxSizeLoadElementValue()
1444  * @param        ElVal string value of the Dicom Element
1445  */
1446 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
1447    size_t item_read;
1448    guint16 group  = ElVal->GetGroup();
1449    std::string  vr= ElVal->GetVR();
1450    guint32 length = ElVal->GetLength();
1451    bool SkipLoad  = false;
1452
1453    fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
1454    
1455    // the test was commented out to 'go inside' the SeQuences
1456    // we don't any longer skip them !
1457     
1458    // if( vr == "SQ" )  
1459    //    SkipLoad = true;
1460
1461    // A SeQuence "contains" a set of Elements.  
1462    //          (fffe e000) tells us an Element is beginning
1463    //          (fffe e00d) tells us an Element just ended
1464    //          (fffe e0dd) tells us the current SeQuence just ended
1465    if( group == 0xfffe )
1466       SkipLoad = true;
1467
1468    if ( SkipLoad ) {
1469       ElVal->SetLength(0);
1470       ElVal->SetValue("gdcm::Skipped");
1471       return;
1472    }
1473
1474    // When the length is zero things are easy:
1475    if ( length == 0 ) {
1476       ElVal->SetValue("");
1477       return;
1478    }
1479
1480    // The elements whose length is bigger than the specified upper bound
1481    // are not loaded. Instead we leave a short notice of the offset of
1482    // the element content and it's length.
1483    if (length > MaxSizeLoadElementValue) {
1484       std::ostringstream s;
1485       s << "gdcm::NotLoaded.";
1486       s << " Address:" << (long)ElVal->GetOffset();
1487       s << " Length:"  << ElVal->GetLength();
1488       s << " x(" << std::hex << ElVal->GetLength() << ")";
1489       ElVal->SetValue(s.str());
1490       return;
1491    }
1492    
1493    // When an integer is expected, read and convert the following two or
1494    // four bytes properly i.e. as an integer as opposed to a string.
1495         
1496         // Actually, elements with Value Multiplicity > 1
1497         // contain a set of integers (not a single one)         
1498         // Any compacter code suggested (?)
1499    if ( IsAnInteger(ElVal) ) {
1500       guint32 NewInt;
1501       std::ostringstream s;
1502       int nbInt;
1503       if (vr == "US" || vr == "SS") {
1504          nbInt = length / 2;
1505          NewInt = ReadInt16();
1506          s << NewInt;
1507          if (nbInt > 1) {
1508             for (int i=1; i < nbInt; i++) {
1509                s << '\\';
1510                NewInt = ReadInt16();
1511                s << NewInt;
1512             }
1513          }
1514                         
1515       } else if (vr == "UL" || vr == "SL") {
1516          nbInt = length / 4;
1517          NewInt = ReadInt32();
1518          s << NewInt;
1519          if (nbInt > 1) {
1520             for (int i=1; i < nbInt; i++) {
1521                s << '\\';
1522                NewInt = ReadInt32();
1523                s << NewInt;
1524             }
1525          }
1526       }                                 
1527 #ifdef GDCM_NO_ANSI_STRING_STREAM
1528       s << std::ends; // to avoid oddities on Solaris
1529 #endif //GDCM_NO_ANSI_STRING_STREAM
1530       ElVal->SetValue(s.str());
1531       return;   
1532    }
1533    
1534    // We need an additional byte for storing \0 that is not on disk
1535    char* NewValue = (char*)malloc(length+1);
1536    if( !NewValue) {
1537       dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
1538       return;
1539    }
1540    NewValue[length]= 0;
1541    
1542    item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
1543    if ( item_read != 1 ) {
1544       free(NewValue);
1545       dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
1546       ElVal->SetValue("gdcm::UnRead");
1547       return;
1548    }
1549    ElVal->SetValue(NewValue);
1550    free(NewValue);
1551 }
1552
1553 /**
1554  * \ingroup       gdcmHeader
1555  * \brief         Loads the element while preserving the current
1556  *                underlying file position indicator as opposed to
1557  *                to LoadElementValue that modifies it.
1558  * @param ElVal   Element whose value shall be loaded. 
1559  * @return  
1560  */
1561 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
1562    long PositionOnEntry = ftell(fp);
1563    LoadElementValue(ElVal);
1564    fseek(fp, PositionOnEntry, SEEK_SET);
1565 }
1566
1567 /**
1568  * \ingroup gdcmHeader
1569  * \brief   
1570  *
1571  * @return 
1572  */
1573  void gdcmHeader::FindLength (gdcmElValue * ElVal) {
1574    guint16 element = ElVal->GetElement();
1575    guint16 group   = ElVal->GetGroup();
1576    std::string  vr = ElVal->GetVR();
1577    guint16 length16;
1578    if( (element == 0x0010) && (group == 0x7fe0) ) {
1579       dbg.SetDebug(-1);
1580       dbg.Verbose(2, "gdcmHeader::FindLength: ",
1581                      "we reached 7fe0 0010");
1582    }   
1583    
1584    if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
1585       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
1586       
1587          // The following reserved two bytes (see PS 3.5-2001, section
1588          // 7.1.2 Data element structure with explicit vr p27) must be
1589          // skipped before proceeding on reading the length on 4 bytes.
1590          fseek(fp, 2L, SEEK_CUR);
1591
1592          guint32 length32 = ReadInt32();
1593
1594          if ( (vr == "OB") && (length32 == 0xffffffff) ) {
1595             ElVal->SetLength(FindLengthOB());
1596             return;
1597          }
1598          FixFoundLength(ElVal, length32); 
1599          return;
1600       }
1601
1602       // Length is encoded on 2 bytes.
1603       length16 = ReadInt16();
1604       
1605       // We can tell the current file is encoded in big endian (like
1606       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1607       // and it's value is the one of the encoding of a big endian file.
1608       // In order to deal with such big endian encoded files, we have
1609       // (at least) two strategies:
1610       // * when we load the "Transfer Syntax" tag with value of big endian
1611       //   encoding, we raise the proper flags. Then we wait for the end
1612       //   of the META group (0x0002) among which is "Transfer Syntax",
1613       //   before switching the swap code to big endian. We have to postpone
1614       //   the switching of the swap code since the META group is fully encoded
1615       //   in little endian, and big endian coding only starts at the next
1616       //   group. The corresponding code can be hard to analyse and adds
1617       //   many additional unnecessary tests for regular tags.
1618       // * the second strategy consists in waiting for trouble, that shall
1619       //   appear when we find the first group with big endian encoding. This
1620       //   is easy to detect since the length of a "Group Length" tag (the
1621       //   ones with zero as element number) has to be of 4 (0x0004). When we
1622       //   encounter 1024 (0x0400) chances are the encoding changed and we
1623       //   found a group with big endian encoding.
1624       // We shall use this second strategy. In order to make sure that we
1625       // can interpret the presence of an apparently big endian encoded
1626       // length of a "Group Length" without committing a big mistake, we
1627       // add an additional check: we look in the already parsed elements
1628       // for the presence of a "Transfer Syntax" whose value has to be "big
1629       // endian encoding". When this is the case, chances are we have got our
1630       // hands on a big endian encoded file: we switch the swap code to
1631       // big endian and proceed...
1632       if ( (element  == 0x0000) && (length16 == 0x0400) ) {
1633          if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
1634             dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
1635             errno = 1;
1636             return;
1637          }
1638          length16 = 4;
1639          SwitchSwapToBigEndian();
1640          // Restore the unproperly loaded values i.e. the group, the element
1641          // and the dictionary entry depending on them.
1642          guint16 CorrectGroup   = SwapShort(ElVal->GetGroup());
1643          guint16 CorrectElem    = SwapShort(ElVal->GetElement());
1644          gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1645                                                        CorrectElem);
1646          if (!NewTag) {
1647             // This correct tag is not in the dictionary. Create a new one.
1648             NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
1649          }
1650          // FIXME this can create a memory leaks on the old entry that be
1651          // left unreferenced.
1652          ElVal->SetDictEntry(NewTag);
1653       }
1654        
1655       // Heuristic: well some files are really ill-formed.
1656       if ( length16 == 0xffff) {
1657          length16 = 0;
1658          //dbg.Verbose(0, "gdcmHeader::FindLength",
1659          //            "Erroneous element length fixed.");
1660          // Actually, length= 0xffff means that we deal with
1661          // Unknown Sequence Length 
1662       }
1663
1664       FixFoundLength(ElVal, (guint32)length16);
1665       return;
1666    }
1667
1668    // Either implicit VR or a non DICOM conformal (see not below) explicit
1669    // VR that ommited the VR of (at least) this element. Farts happen.
1670    // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1671    // on Data elements "Implicit and Explicit VR Data Elements shall
1672    // not coexist in a Data Set and Data Sets nested within it".]
1673    // Length is on 4 bytes.
1674    FixFoundLength(ElVal, ReadInt32());
1675    return;
1676 }
1677
1678 /**
1679  * \ingroup   gdcmHeader
1680  * \brief     Find the value representation of the current tag.
1681  * @param ElVal
1682  */
1683 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
1684    if (filetype != ExplicitVR)
1685       return;
1686
1687    char VR[3];
1688    std::string vr;
1689    int lgrLue;
1690    char msg[100]; // for sprintf. Sorry
1691
1692    long PositionOnEntry = ftell(fp);
1693    // Warning: we believe this is explicit VR (Value Representation) because
1694    // we used a heuristic that found "UL" in the first tag. Alas this
1695    // doesn't guarantee that all the tags will be in explicit VR. In some
1696    // cases (see e-film filtered files) one finds implicit VR tags mixed
1697    // within an explicit VR file. Hence we make sure the present tag
1698    // is in explicit VR and try to fix things if it happens not to be
1699    // the case.
1700    bool RealExplicit = true;
1701    
1702    lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
1703    VR[2]=0;
1704    vr = std::string(VR);
1705       
1706    // Assume we are reading a falsely explicit VR file i.e. we reached
1707    // a tag where we expect reading a VR but are in fact we read the
1708    // first to bytes of the length. Then we will interogate (through find)
1709    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1710    // both GCC and VC++ implementations of the STL map. Hence when the
1711    // expected VR read happens to be non-ascii characters we consider
1712    // we hit falsely explicit VR tag.
1713
1714    if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
1715       RealExplicit = false;
1716
1717    // CLEANME searching the dicom_vr at each occurence is expensive.
1718    // PostPone this test in an optional integrity check at the end
1719    // of parsing or only in debug mode.
1720    if ( RealExplicit && !dicom_vr->Count(vr) )
1721       RealExplicit= false;
1722
1723    if ( RealExplicit ) {
1724       if ( ElVal->IsVRUnknown() ) {
1725          // When not a dictionary entry, we can safely overwrite the vr.
1726          ElVal->SetVR(vr);
1727          return; 
1728       }
1729       if ( ElVal->GetVR() == vr ) {
1730          // The vr we just read and the dictionary agree. Nothing to do.
1731          return;
1732       }
1733       // The vr present in the file and the dictionary disagree. We assume
1734       // the file writer knew best and use the vr of the file. Since it would
1735       // be unwise to overwrite the vr of a dictionary (since it would
1736       // compromise it's next user), we need to clone the actual DictEntry
1737       // and change the vr for the read one.
1738       gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
1739                                  ElVal->GetElement(),
1740                                  vr,
1741                                  "FIXME",
1742                                  ElVal->GetName());
1743       ElVal->SetDictEntry(NewTag);
1744       return; 
1745    }
1746    
1747    // We thought this was explicit VR, but we end up with an
1748    // implicit VR tag. Let's backtrack.   
1749    
1750       sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", 
1751                    ElVal->GetGroup(),ElVal->GetElement());
1752       dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
1753    
1754    fseek(fp, PositionOnEntry, SEEK_SET);
1755    // When this element is known in the dictionary we shall use, e.g. for
1756    // the semantics (see the usage of IsAnInteger), the vr proposed by the
1757    // dictionary entry. Still we have to flag the element as implicit since
1758    // we know now our assumption on expliciteness is not furfilled.
1759    // avoid  .
1760    if ( ElVal->IsVRUnknown() )
1761       ElVal->SetVR("Implicit");
1762    ElVal->SetImplicitVr();
1763 }
1764
1765 /**
1766  * \ingroup gdcmHeader
1767  * \brief   
1768  *
1769  * @return 
1770  */
1771  guint32 gdcmHeader::FindLengthOB(void) {
1772    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1773    guint16 g;
1774    guint16 n; 
1775    long PositionOnEntry = ftell(fp);
1776    bool FoundSequenceDelimiter = false;
1777    guint32 TotalLength = 0;
1778    guint32 ItemLength;
1779
1780    while ( ! FoundSequenceDelimiter) {
1781       g = ReadInt16();
1782       n = ReadInt16();   
1783       if (errno == 1)
1784          return 0;
1785       TotalLength += 4;  // We even have to decount the group and element 
1786      
1787       if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ {
1788          char msg[100]; // for sprintf. Sorry
1789          sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1790          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg); 
1791          errno = 1;
1792          return 0;
1793       }
1794       if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header  */ 
1795          FoundSequenceDelimiter = true;
1796       else if ( n != 0xe000 ){
1797          char msg[100];  // for sprintf. Sorry
1798          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1799                       n, g,n);
1800          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
1801          errno = 1;
1802          return 0;
1803       }
1804       ItemLength = ReadInt32();
1805       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
1806                                       // the ItemLength with ReadInt32                                     
1807       SkipBytes(ItemLength);
1808    }
1809    fseek(fp, PositionOnEntry, SEEK_SET);
1810    return TotalLength;
1811 }
1812
1813 /**
1814  * \ingroup gdcmHeader
1815  * \brief   
1816  * @param ElVal 
1817  * @return 
1818  */
1819 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
1820     SkipBytes(ElVal->GetLength());
1821 }
1822
1823 /**
1824  * \ingroup gdcmHeader
1825  * \brief   When the length of an element value is obviously wrong (because
1826  *          the parser went Jabberwocky) one can hope improving things by
1827  *          applying this heuristic.
1828  */
1829 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
1830
1831    ElVal->SetReadLength(FoundLength); // will be updated only if a bug is found
1832                      
1833    if ( FoundLength == 0xffffffff) {  
1834       FoundLength = 0;
1835    }
1836       
1837       // Sorry for the patch!  
1838       // XMedCom did the trick to read some nasty GE images ...
1839    else if (FoundLength == 13) {
1840       // The following 'if' will be removed when there is no more
1841       // images on Creatis HDs with a 13 length for Manufacturer...
1842       if ( (ElVal->GetGroup() != 0x0008) ||  
1843            ( (ElVal->GetElement() != 0x0070) && (ElVal->GetElement() != 0x0080) ) ) {
1844       // end of remove area
1845          FoundLength =10;
1846          ElVal->SetReadLength(10); // a bug is to be fixed
1847       }
1848    } 
1849      // to fix some garbage 'Leonardo' Siemens images
1850      // May be commented out to avoid overhead
1851    else if ( (ElVal->GetGroup() == 0x0009) &&
1852        ( (ElVal->GetElement() == 0x1113) || (ElVal->GetElement() == 0x1114) ) ){
1853       FoundLength =4;
1854       ElVal->SetReadLength(4); // a bug is to be fixed 
1855    } 
1856      // end of fix
1857          
1858    // to try to 'go inside' SeQuences (with length), and not to skip them        
1859    else if ( ElVal->GetVR() == "SQ") { 
1860       if (enableSequences)    // only if the user does want to !
1861          FoundLength =0;         
1862    } 
1863     
1864    ElVal->SetUsableLength(FoundLength);
1865 }
1866
1867 /**
1868  * \ingroup gdcmHeader
1869  * \brief   Apply some heuristics to predict wether the considered 
1870  *          element value contains/represents an integer or not.
1871  * @param   ElVal The element value on which to apply the predicate.
1872  * @return  The result of the heuristical predicate.
1873  */
1874 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1875    guint16 element = ElVal->GetElement();
1876    guint16 group   = ElVal->GetGroup();
1877    std::string  vr = ElVal->GetVR();
1878    guint32 length  = ElVal->GetLength();
1879
1880    // When we have some semantics on the element we just read, and if we
1881    // a priori know we are dealing with an integer, then we shall be
1882    // able to swap it's element value properly.
1883    if ( element == 0 )  {  // This is the group length of the group
1884       if (length == 4)
1885          return true;
1886       else {
1887          std::ostringstream s;
1888          s << "Erroneous Group Length element length  on :" \
1889            << std::hex << group << " , " << element;
1890          dbg.Error("gdcmHeader::IsAnInteger",
1891             s.str().c_str());     
1892       }
1893    }
1894    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1895       return true;
1896    
1897    return false;
1898 }
1899
1900 /**
1901  * \ingroup gdcmHeader
1902  * \brief Reads a supposed to be 16 Bits integer
1903  * \     (swaps it depending on processor endianity) 
1904  *
1905  * @return integer acts as a boolean
1906  */
1907 guint16 gdcmHeader::ReadInt16(void) {
1908    guint16 g;
1909    size_t item_read;
1910    item_read = fread (&g, (size_t)2,(size_t)1, fp);
1911    if ( item_read != 1 ) {
1912       // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
1913       // if(feof(fp)) 
1914       //    dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
1915       if(ferror(fp)) 
1916          dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
1917       errno = 1;
1918       return 0;
1919    }
1920    errno = 0;
1921    g = SwapShort(g);
1922    return g;
1923 }
1924
1925 /**
1926  * \ingroup gdcmHeader
1927  * \brief  Reads a supposed to be 32 Bits integer
1928  * \       (swaps it depending on processor endianity)  
1929  *
1930  * @return 
1931  */
1932 guint32 gdcmHeader::ReadInt32(void) {
1933    guint32 g;
1934    size_t item_read;
1935    item_read = fread (&g, (size_t)4,(size_t)1, fp);
1936    if ( item_read != 1 ) { 
1937       //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
1938       //if(feof(fp)) 
1939       //   dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
1940      if(ferror(fp)) 
1941          dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");   
1942       errno = 1;
1943       return 0;
1944    }
1945    errno = 0;   
1946    g = SwapLong(g);
1947    return g;
1948 }
1949
1950 /**
1951  * \ingroup gdcmHeader
1952  * \brief   
1953  *
1954  * @return 
1955  */
1956 void gdcmHeader::SkipBytes(guint32 NBytes) {
1957    //FIXME don't dump the returned value
1958    (void)fseek(fp, (long)NBytes, SEEK_CUR);
1959 }
1960
1961 /**
1962  * \ingroup gdcmHeader
1963  * \brief   
1964  */
1965 void gdcmHeader::Initialise(void) {
1966    dicom_vr = gdcmGlobal::GetVR();
1967    dicom_ts = gdcmGlobal::GetTS();
1968    Dicts    = gdcmGlobal::GetDicts();
1969    RefPubDict = Dicts->GetDefaultPubDict();
1970    RefShaDict = (gdcmDict*)0;
1971 }
1972
1973 /**
1974  * \ingroup gdcmHeader
1975  * \brief   Discover what the swap code is (among little endian, big endian,
1976  *          bad little endian, bad big endian).
1977  *
1978  */
1979 void gdcmHeader::CheckSwap()
1980 {
1981    // Fourth semantics:
1982    //
1983    // ---> Warning : This fourth field is NOT part 
1984    //                of the 'official' Dicom Dictionnary
1985    //                and should NOT be used.
1986    //                (Not defined for all the groups
1987    //                 may be removed in a future release)
1988    //
1989    // CMD      Command        
1990    // META     Meta Information 
1991    // DIR      Directory
1992    // ID
1993    // PAT      Patient
1994    // ACQ      Acquisition
1995    // REL      Related
1996    // IMG      Image
1997    // SDY      Study
1998    // VIS      Visit 
1999    // WAV      Waveform
2000    // PRC
2001    // DEV      Device
2002    // NMI      Nuclear Medicine
2003    // MED
2004    // BFS      Basic Film Session
2005    // BFB      Basic Film Box
2006    // BIB      Basic Image Box
2007    // BAB
2008    // IOB
2009    // PJ
2010    // PRINTER
2011    // RT       Radio Therapy
2012    // DVH   
2013    // SSET
2014    // RES      Results
2015    // CRV      Curve
2016    // OLY      Overlays
2017    // PXL      Pixels
2018    // DL       Delimiters
2019    //
2020
2021    // The only guaranted way of finding the swap code is to find a
2022    // group tag since we know it's length has to be of four bytes i.e.
2023    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2024    // occurs when we can't find such group...
2025    guint32  s;
2026    guint32  x=4;  // x : for ntohs
2027    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2028     
2029    int lgrLue;
2030    char * entCur;
2031    char deb[HEADER_LENGTH_TO_READ];
2032     
2033    // First, compare HostByteOrder and NetworkByteOrder in order to
2034    // determine if we shall need to swap bytes (i.e. the Endian type).
2035    if (x==ntohs(x))
2036       net2host = true;
2037    else
2038       net2host = false; 
2039     //cout << net2host << endl;
2040          
2041    // The easiest case is the one of a DICOM header, since it possesses a
2042    // file preamble where it suffice to look for the string "DICM".
2043    lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2044    
2045    entCur = deb + 128;
2046    if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2047       dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
2048       // Next, determine the value representation (VR). Let's skip to the
2049       // first element (0002, 0000) and check there if we find "UL" 
2050       // - or "OB" if the 1st one is (0002,0001) -,
2051       // in which case we (almost) know it is explicit VR.
2052       // WARNING: if it happens to be implicit VR then what we will read
2053       // is the length of the group. If this ascii representation of this
2054       // length happens to be "UL" then we shall believe it is explicit VR.
2055       // FIXME: in order to fix the above warning, we could read the next
2056       // element value (or a couple of elements values) in order to make
2057       // sure we are not commiting a big mistake.
2058       // We need to skip :
2059       // * the 128 bytes of File Preamble (often padded with zeroes),
2060       // * the 4 bytes of "DICM" string,
2061       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2062       // i.e. a total of  136 bytes.
2063       entCur = deb + 136;
2064       // FIXME
2065       // Use gdcmHeader::dicom_vr to test all the possibilities
2066       // instead of just checking for UL, OB and UI !?
2067       if(  (memcmp(entCur, "UL", (size_t)2) == 0) ||
2068            (memcmp(entCur, "OB", (size_t)2) == 0) ||
2069            (memcmp(entCur, "UI", (size_t)2) == 0) )   
2070       {
2071          filetype = ExplicitVR;
2072          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
2073                      "explicit Value Representation");
2074       } else {
2075          filetype = ImplicitVR;
2076          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
2077                      "not an explicit Value Representation");
2078       }
2079       if (net2host) {
2080          sw = 4321;
2081          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
2082                         "HostByteOrder != NetworkByteOrder");
2083       } else {
2084          sw = 0;
2085          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
2086                         "HostByteOrder = NetworkByteOrder");
2087       }
2088       
2089       // Position the file position indicator at first tag (i.e.
2090       // after the file preamble and the "DICM" string).
2091       rewind(fp);
2092       fseek (fp, 132L, SEEK_SET);
2093       return;
2094    } // End of DicomV3
2095
2096    // Alas, this is not a DicomV3 file and whatever happens there is no file
2097    // preamble. We can reset the file position indicator to where the data
2098    // is (i.e. the beginning of the file).
2099     dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
2100    rewind(fp);
2101
2102    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2103    // By clean we mean that the length of the first tag is written down.
2104    // If this is the case and since the length of the first group HAS to be
2105    // four (bytes), then determining the proper swap code is straightforward.
2106
2107    entCur = deb + 4;
2108    // We assume the array of char we are considering contains the binary
2109    // representation of a 32 bits integer. Hence the following dirty
2110    // trick :
2111    s = *((guint32 *)(entCur));
2112    
2113    switch (s) {
2114    case 0x00040000 :
2115       sw = 3412;
2116       filetype = ACR;
2117       return;
2118    case 0x04000000 :
2119       sw = 4321;
2120       filetype = ACR;
2121       return;
2122    case 0x00000400 :
2123       sw = 2143;
2124       filetype = ACR;
2125       return;
2126    case 0x00000004 :
2127       sw = 0;
2128       filetype = ACR;
2129       return;
2130    default :
2131       dbg.Verbose(0, "gdcmHeader::CheckSwap:",
2132                      "ACR/NEMA unfound swap info (time to raise bets)");
2133    }
2134
2135    // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2136    // It is time for despaired wild guesses. So, let's assume this file
2137    // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
2138    // not present. Then the only info we have is the net2host one.
2139    filetype = Unknown;
2140    if (! net2host )
2141       sw = 0;
2142    else
2143       sw = 4321;
2144    return;
2145 }
2146
2147 /**
2148  * \ingroup gdcmHeader
2149  * \brief   
2150  */
2151 void gdcmHeader::SwitchSwapToBigEndian(void) {
2152    dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
2153                   "Switching to BigEndian mode.");
2154    if ( sw == 0    ) {
2155       sw = 4321;
2156       return;
2157    }
2158    if ( sw == 4321 ) {
2159       sw = 0;
2160       return;
2161    }
2162    if ( sw == 3412 ) {
2163       sw = 2143;
2164       return;
2165    }
2166    if ( sw == 2143 )
2167       sw = 3412;
2168 }
2169
2170 /**
2171  * \ingroup gdcmHeader
2172  * \brief   
2173  * @param NewSize
2174  * @return 
2175  */
2176 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
2177    if (NewSize < 0)
2178       return;
2179    if ((guint32)NewSize >= (guint32)0xffffffff) {
2180       MaxSizeLoadElementValue = 0xffffffff;
2181       return;
2182    }
2183    MaxSizeLoadElementValue = NewSize;
2184 }
2185
2186 /**
2187  * \ingroup gdcmHeader
2188  * \brief   Searches both the public and the shadow dictionary (when they
2189  *          exist) for the presence of the DictEntry with given
2190  *          group and element. The public dictionary has precedence on the
2191  *          shadow one.
2192  * @param   group   group of the searched DictEntry
2193  * @param   element element of the searched DictEntry
2194  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2195  */
2196 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
2197                                                  guint16 element) {
2198    gdcmDictEntry * found = (gdcmDictEntry*)0;
2199    if (!RefPubDict && !RefShaDict) {
2200       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
2201                      "we SHOULD have a default dictionary");
2202    }
2203    if (RefPubDict) {
2204       found = RefPubDict->GetTagByNumber(group, element);
2205       if (found)
2206          return found;
2207    }
2208    if (RefShaDict) {
2209       found = RefShaDict->GetTagByNumber(group, element);
2210       if (found)
2211          return found;
2212    }
2213    return found;
2214 }
2215
2216 /**
2217  * \ingroup gdcmHeader
2218  * \brief   Searches both the public and the shadow dictionary (when they
2219  *          exist) for the presence of the DictEntry with given name.
2220  *          The public dictionary has precedence on the shadow one.
2221  * @param   Name name of the searched DictEntry
2222  * @return  Corresponding DictEntry when it exists, NULL otherwise.
2223  */
2224 gdcmDictEntry * gdcmHeader::GetDictEntryByName(std::string Name) {
2225    gdcmDictEntry * found = (gdcmDictEntry*)0;
2226    if (!RefPubDict && !RefShaDict) {
2227       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
2228                      "we SHOULD have a default dictionary");
2229    }
2230    if (RefPubDict) {
2231       found = RefPubDict->GetTagByName(Name);
2232       if (found)
2233          return found;
2234    }
2235    if (RefShaDict) {
2236       found = RefShaDict->GetTagByName(Name);
2237       if (found)
2238          return found;
2239    }
2240    return found;
2241 }
2242
2243 /**
2244  * \ingroup gdcmHeader
2245  * \brief   Read the next tag but WITHOUT loading it's value
2246  * @return  On succes the newly created ElValue, NULL on failure.      
2247  */
2248 gdcmElValue * gdcmHeader::ReadNextElement(void) {
2249   
2250    guint16 g,n;
2251    gdcmElValue * NewElVal;
2252    
2253    g = ReadInt16();
2254    n = ReadInt16();
2255       
2256    if (errno == 1)
2257       // We reached the EOF (or an error occured) and header parsing
2258       // has to be considered as finished.
2259       return (gdcmElValue *)0;
2260    
2261    NewElVal = NewElValueByNumber(g, n);
2262    FindVR(NewElVal);
2263    FindLength(NewElVal);
2264         
2265    if (errno == 1) {
2266       // Call it quits
2267       return (gdcmElValue *)0;
2268    }
2269    NewElVal->SetOffset(ftell(fp));  
2270    //if ( (g==0x7fe0) && (n==0x0010) ) 
2271    return NewElVal;
2272 }
2273
2274 /**
2275  * \ingroup gdcmHeader
2276  * \brief   Build a new Element Value from all the low level arguments. 
2277  *          Check for existence of dictionary entry, and build
2278  *          a default one when absent.
2279  * @param   Name    Name of the underlying DictEntry
2280  */
2281 gdcmElValue* gdcmHeader::NewElValueByName(std::string Name) {
2282
2283    gdcmDictEntry * NewTag = GetDictEntryByName(Name);
2284    if (!NewTag)
2285       NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2286
2287    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
2288    if (!NewElVal) {
2289       dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
2290                   "failed to allocate gdcmElValue");
2291       return (gdcmElValue*)0;
2292    }
2293    return NewElVal;
2294 }  
2295
2296 /**
2297  * \ingroup gdcmHeader
2298  * \brief   Build a new Element Value from all the low level arguments. 
2299  *          Check for existence of dictionary entry, and build
2300  *          a default one when absent.
2301  * @param   Group group   of the underlying DictEntry
2302  * @param   Elem  element of the underlying DictEntry
2303  */
2304 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
2305    // Find out if the tag we encountered is in the dictionaries:
2306    gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
2307    if (!NewTag)
2308       NewTag = new gdcmDictEntry(Group, Elem);
2309
2310    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
2311    if (!NewElVal) {
2312       dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
2313                   "failed to allocate gdcmElValue");
2314       return (gdcmElValue*)0;
2315    }
2316    return NewElVal;
2317 }
2318
2319 /**
2320  * \ingroup gdcmHeader
2321  * \brief   Searches within the public dictionary for a Dicom Element of
2322  *          a given tag.
2323  * @param   tagName name of the searched Dicom Element.
2324  * @return  Corresponding Dicom Element when it exists, and NULL
2325  *          otherwise.
2326  */
2327  gdcmElValue* gdcmHeader::GetElementByName(std::string tagName) {
2328    gdcmDictEntry *dictEntry = RefPubDict->GetTagByName(tagName); 
2329    if( dictEntry == NULL)
2330       return (gdcmElValue*)NULL;
2331   return(PubElValSet.GetElementByNumber(dictEntry->GetGroup(),
2332                                         dictEntry->GetElement()));  
2333 }
2334
2335 /**
2336  * \ingroup gdcmHeader
2337  * \brief   Small utility function that creates a new manually crafted
2338  *          (as opposed as read from the file) gdcmElValue with user
2339  *          specified name and adds it to the public tag hash table.
2340  * \note    A fake TagKey is generated so the PubDict can keep it's coherence.
2341  * @param   NewTagName The name to be given to this new tag.
2342  * @param   VR The Value Representation to be given to this new tag.
2343  * @ return The newly hand crafted Element Value.
2344  */
2345 gdcmElValue* gdcmHeader::NewManualElValToPubDict(std::string NewTagName, 
2346                                                  std::string VR) {
2347    gdcmElValue* NewElVal = (gdcmElValue*)0;
2348    guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
2349    guint32 FreeElem = 0;
2350    gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
2351
2352    FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
2353    if (FreeElem == UINT32_MAX) {
2354       dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
2355                      "Group 0xffff in Public Dict is full");
2356       return (gdcmElValue*)0;
2357    }
2358    NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
2359                                 VR, "GDCM", NewTagName);
2360    NewElVal = new gdcmElValue(NewEntry);
2361    PubElValSet.Add(NewElVal);
2362    return NewElVal;
2363 }
2364
2365 //-----------------------------------------------------------------------------