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