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