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