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