]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
*FIX: Change GetLUTRGBA to return unsigned char instead of void, nicer for python...
[gdcm.git] / src / gdcmHeader.cxx
1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.116 2003/11/13 10:23:40 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 #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       ElVal->SetValue(s.str());
1016       return;   
1017    }
1018    
1019    // We need an additional byte for storing \0 that is not on disk
1020    char* NewValue = (char*)malloc(length+1);
1021    if( !NewValue) {
1022       dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
1023       return;
1024    }
1025    NewValue[length]= 0;
1026    
1027    item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
1028    if ( item_read != 1 ) {
1029       free(NewValue);
1030       dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
1031       ElVal->SetValue("gdcm::UnRead");
1032       return;
1033    }
1034    ElVal->SetValue(NewValue);
1035    free(NewValue);
1036 }
1037
1038 /**
1039  * \ingroup       gdcmHeader
1040  * \brief         Loads the element while preserving the current
1041  *                underlying file position indicator as opposed to
1042  *                to LoadElementValue that modifies it.
1043  * @param ElVal   Element whose value shall be loaded. 
1044  * @return  
1045  */
1046 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
1047    long PositionOnEntry = ftell(fp);
1048    LoadElementValue(ElVal);
1049    fseek(fp, PositionOnEntry, SEEK_SET);
1050 }
1051
1052 /**
1053  * \ingroup gdcmHeader
1054  * \brief Reads a supposed to be 16 Bits integer
1055  * \     (swaps it depending on processor endianity) 
1056  *
1057  * @return integer acts as a boolean
1058  */
1059 guint16 gdcmHeader::ReadInt16(void) {
1060    guint16 g;
1061    size_t item_read;
1062    item_read = fread (&g, (size_t)2,(size_t)1, fp);
1063    if ( item_read != 1 ) {
1064       // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
1065       // if(feof(fp)) 
1066       //    dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
1067       if(ferror(fp)) 
1068          dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
1069       errno = 1;
1070       return 0;
1071    }
1072    errno = 0;
1073    g = SwapShort(g);
1074    return g;
1075 }
1076
1077 /**
1078  * \ingroup gdcmHeader
1079  * \brief  Reads a supposed to be 32 Bits integer
1080  * \       (swaps it depending on processor endianity)  
1081  *
1082  * @return 
1083  */
1084 guint32 gdcmHeader::ReadInt32(void) {
1085    guint32 g;
1086    size_t item_read;
1087    item_read = fread (&g, (size_t)4,(size_t)1, fp);
1088    if ( item_read != 1 ) { 
1089       //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
1090       //if(feof(fp)) 
1091       //   dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
1092      if(ferror(fp)) 
1093          dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");   
1094       errno = 1;
1095       return 0;
1096    }
1097    errno = 0;   
1098    g = SwapLong(g);
1099    return g;
1100 }
1101
1102 /**
1103  * \ingroup gdcmHeader
1104  * \brief   
1105  *
1106  * @return 
1107  */
1108  gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1109
1110    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1111    if (!elValue) {
1112       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1113                   "failed to Locate gdcmElValue");
1114       return (gdcmElValue*)0;
1115    }
1116    return elValue;
1117 }
1118
1119 /**
1120  * \ingroup gdcmHeader
1121  * \brief   Build a new Element Value from all the low level arguments. 
1122  *          Check for existence of dictionary entry, and build
1123  *          a default one when absent.
1124  * @param   Group group   of the underlying DictEntry
1125  * @param   Elem  element of the underlying DictEntry
1126  */
1127 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1128    // Find out if the tag we encountered is in the dictionaries:
1129    gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1130    if (!NewTag)
1131       NewTag = new gdcmDictEntry(Group, Elem);
1132
1133    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1134    if (!NewElVal) {
1135       dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1136                   "failed to allocate gdcmElValue");
1137       return (gdcmElValue*)0;
1138    }
1139    return NewElVal;
1140 }
1141
1142 /**
1143  * \ingroup gdcmHeader
1144  * \brief   TODO
1145  * @param   Value
1146  * @param   Group
1147  * @param   Elem
1148  * \return integer acts as a boolean
1149  */
1150 int gdcmHeader::ReplaceOrCreateByNumber(std::string Value, 
1151                                         guint16 Group, guint16 Elem ) {
1152         // TODO : FIXME JPRx
1153         // curieux, non ?
1154         // on (je) cree une Elvalue ne contenant pas de valeur
1155         // on l'ajoute au ElValSet
1156         // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1157         // --> devrait pouvoir etre fait + simplement ???
1158    if (CheckIfExistByNumber(Group, Elem) == 0) {
1159       gdcmElValue* a =NewElValueByNumber(Group, Elem);
1160       if (a == NULL) 
1161          return 0;
1162       PubElValSet.Add(a);
1163    }   
1164    PubElValSet.SetElValueByNumber(Value, Group, Elem);
1165    return(1);
1166 }   
1167
1168
1169 /**
1170  * \ingroup gdcmHeader
1171  * \brief   Modify (or Creates if not found) an element
1172  * @param   Value new value
1173  * @param   Group
1174  * @param   Elem
1175  * \return integer acts as a boolean 
1176  * 
1177  */
1178 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1179
1180    gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1181    PubElValSet.Add(nvElValue);
1182    std::string v = Value;       
1183    PubElValSet.SetElValueByNumber(v, Group, Elem);
1184    return(1);
1185 }  
1186
1187
1188 /**
1189  * \ingroup gdcmHeader
1190  * \brief   Set a new value if the invoked element exists
1191  *          Seems to be useless !!!
1192  * @param   Value
1193  * @param   Group
1194  * @param   Elem
1195  * \return integer acts as a boolean 
1196  */
1197 int gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1198
1199    //gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1200    std::string v = Value;       
1201    PubElValSet.SetElValueByNumber(v, Group, Elem);
1202    return 1;
1203
1204
1205
1206 /**
1207  * \ingroup gdcmHeader
1208  * \brief   Checks if a given ElValue (group,number) 
1209  * \ exists in the Public ElValSet
1210  * @param   Group
1211  * @param   Elem
1212  * @return  integer acts as a boolean  
1213  */
1214  
1215 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1216    return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1217  }
1218   
1219 /**
1220  * \ingroup gdcmHeader
1221  * \brief   Build a new Element Value from all the low level arguments. 
1222  *          Check for existence of dictionary entry, and build
1223  *          a default one when absent.
1224  * @param   Name    Name of the underlying DictEntry
1225  */
1226 gdcmElValue* gdcmHeader::NewElValueByName(std::string Name) {
1227
1228    gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1229    if (!NewTag)
1230       NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1231
1232    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1233    if (!NewElVal) {
1234       dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1235                   "failed to allocate gdcmElValue");
1236       return (gdcmElValue*)0;
1237    }
1238    return NewElVal;
1239 }  
1240
1241 /**
1242  * \ingroup gdcmHeader
1243  * \brief   Read the next tag but WITHOUT loading it's value
1244  * @return  On succes the newly created ElValue, NULL on failure.      
1245  */
1246 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1247   
1248    guint16 g,n;
1249    gdcmElValue * NewElVal;
1250    
1251    g = ReadInt16();
1252    n = ReadInt16();
1253       
1254    if (errno == 1)
1255       // We reached the EOF (or an error occured) and header parsing
1256       // has to be considered as finished.
1257       return (gdcmElValue *)0;
1258    
1259    NewElVal = NewElValueByNumber(g, n);
1260    FindVR(NewElVal);
1261    FindLength(NewElVal);
1262         
1263    if (errno == 1) {
1264       // Call it quits
1265       return (gdcmElValue *)0;
1266    }
1267    NewElVal->SetOffset(ftell(fp));  
1268    //if ( (g==0x7fe0) && (n==0x0010) ) 
1269    return NewElVal;
1270 }
1271
1272 /**
1273  * \ingroup gdcmHeader
1274  * \brief   Apply some heuristics to predict wether the considered 
1275  *          element value contains/represents an integer or not.
1276  * @param   ElVal The element value on which to apply the predicate.
1277  * @return  The result of the heuristical predicate.
1278  */
1279 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1280    guint16 element = ElVal->GetElement();
1281    std::string  vr = ElVal->GetVR();
1282    guint32 length  = ElVal->GetLength();
1283
1284    // When we have some semantics on the element we just read, and if we
1285    // a priori know we are dealing with an integer, then we shall be
1286    // able to swap it's element value properly.
1287    if ( element == 0 )  {  // This is the group length of the group
1288       if (length == 4)
1289          return true;
1290       else {
1291          dbg.Error("gdcmHeader::IsAnInteger",
1292             "Erroneous Group Length element length.");     
1293       }
1294    }
1295    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1296       return true;
1297    
1298    return false;
1299 }
1300
1301 /**
1302  * \ingroup gdcmHeader
1303  * \brief   Recover the offset (from the beginning of the file) of the pixels.
1304  */
1305 size_t gdcmHeader::GetPixelOffset(void) {
1306    // If this file complies with the norm we should encounter the
1307    // "Image Location" tag (0x0028,  0x0200). This tag contains the
1308    // the group that contains the pixel data (hence the "Pixel Data"
1309    // is found by indirection through the "Image Location").
1310    // Inside the group pointed by "Image Location" the searched element
1311    // is conventionally the element 0x0010 (when the norm is respected).
1312    // When the "Image Location" is absent we default to group 0x7fe0.
1313    guint16 grPixel;
1314    guint16 numPixel;
1315    std::string ImageLocation = GetPubElValByName("Image Location");
1316    if ( ImageLocation == GDCM_UNFOUND ) {
1317       grPixel = 0x7fe0;
1318    } else {
1319       grPixel = (guint16) atoi( ImageLocation.c_str() );
1320    }
1321    if (grPixel != 0x7fe0)
1322       // This is a kludge for old dirty Philips imager.
1323       numPixel = 0x1010;
1324    else
1325       numPixel = 0x0010;
1326          
1327    gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1328                                                               numPixel);
1329    if (PixelElement)
1330       return PixelElement->GetOffset();
1331    else
1332       return 0;
1333 }
1334
1335 /**
1336  * \ingroup gdcmHeader
1337  * \brief   Recover the pixel area length (in Bytes) .
1338  */
1339 size_t gdcmHeader::GetPixelAreaLength(void) {
1340    // If this file complies with the norm we should encounter the
1341    // "Image Location" tag (0x0028,  0x0200). This tag contains the
1342    // the group that contains the pixel data (hence the "Pixel Data"
1343    // is found by indirection through the "Image Location").
1344    // Inside the group pointed by "Image Location" the searched element
1345    // is conventionally the element 0x0010 (when the norm is respected).
1346    // When the "Image Location" is absent we default to group 0x7fe0.
1347    guint16 grPixel;
1348    guint16 numPixel;
1349    std::string ImageLocation = GetPubElValByName("Image Location");
1350    if ( ImageLocation == GDCM_UNFOUND ) {
1351       grPixel = 0x7fe0;
1352    } else {
1353       grPixel = (guint16) atoi( ImageLocation.c_str() );
1354    }
1355    if (grPixel != 0x7fe0)
1356       // This is a kludge for old dirty Philips imager.
1357       numPixel = 0x1010;
1358    else
1359       numPixel = 0x0010;
1360          
1361    gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1362                                                               numPixel);
1363    if (PixelElement)
1364       return PixelElement->GetLength();
1365    else
1366       return 0;
1367 }
1368
1369 /**
1370  * \ingroup gdcmHeader
1371  * \brief   Searches both the public and the shadow dictionary (when they
1372  *          exist) for the presence of the DictEntry with given
1373  *          group and element. The public dictionary has precedence on the
1374  *          shadow one.
1375  * @param   group   group of the searched DictEntry
1376  * @param   element element of the searched DictEntry
1377  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1378  */
1379 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1380                                                  guint16 element) {
1381    gdcmDictEntry * found = (gdcmDictEntry*)0;
1382    if (!RefPubDict && !RefShaDict) {
1383       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1384                      "we SHOULD have a default dictionary");
1385    }
1386    if (RefPubDict) {
1387       found = RefPubDict->GetTagByNumber(group, element);
1388       if (found)
1389          return found;
1390    }
1391    if (RefShaDict) {
1392       found = RefShaDict->GetTagByNumber(group, element);
1393       if (found)
1394          return found;
1395    }
1396    return found;
1397 }
1398
1399 /**
1400  * \ingroup gdcmHeader
1401  * \brief   Searches both the public and the shadow dictionary (when they
1402  *          exist) for the presence of the DictEntry with given name.
1403  *          The public dictionary has precedence on the shadow one.
1404  * @param   Name name of the searched DictEntry
1405  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1406  */
1407 gdcmDictEntry * gdcmHeader::GetDictEntryByName(std::string Name) {
1408    gdcmDictEntry * found = (gdcmDictEntry*)0;
1409    if (!RefPubDict && !RefShaDict) {
1410       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1411                      "we SHOULD have a default dictionary");
1412    }
1413    if (RefPubDict) {
1414       found = RefPubDict->GetTagByName(Name);
1415       if (found)
1416          return found;
1417    }
1418    if (RefShaDict) {
1419       found = RefShaDict->GetTagByName(Name);
1420       if (found)
1421          return found;
1422    }
1423    return found;
1424 }
1425
1426 /**
1427  * \ingroup gdcmHeader
1428  * \brief   Searches within the public dictionary for element value of
1429  *          a given tag.
1430  * @param   group Group of the researched tag.
1431  * @param   element Element of the researched tag.
1432  * @return  Corresponding element value when it exists, and the string
1433  *          GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1434  */
1435 std::string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1436    return PubElValSet.GetElValueByNumber(group, element);
1437 }
1438
1439 /**
1440  * \ingroup gdcmHeader
1441  * \brief   Searches within the public dictionary for element value
1442  *          representation of a given tag.
1443  *
1444  *          Obtaining the VR (Value Representation) might be needed by caller
1445  *          to convert the string typed content to caller's native type 
1446  *          (think of C++ vs Python). The VR is actually of a higher level
1447  *          of semantics than just the native C++ type.
1448  * @param   group Group of the researched tag.
1449  * @param   element Element of the researched tag.
1450  * @return  Corresponding element value representation when it exists,
1451  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1452  */
1453 std::string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1454    gdcmElValue* elem =  PubElValSet.GetElementByNumber(group, element);
1455    if ( !elem )
1456       return GDCM_UNFOUND;
1457    return elem->GetVR();
1458 }
1459
1460 /**
1461  * \ingroup gdcmHeader
1462  * \brief   Searches within the public dictionary for element value of
1463  *          a given tag.
1464  * @param   TagName name of the searched element.
1465  * @return  Corresponding element value when it exists, and the string
1466  *          GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1467  */
1468 std::string gdcmHeader::GetPubElValByName(std::string TagName) {
1469    return PubElValSet.GetElValueByName(TagName);
1470 }
1471
1472 /**
1473  * \ingroup gdcmHeader
1474  * \brief   Searches within the elements parsed with the public dictionary for
1475  *          the element value representation of a given tag.
1476  *
1477  *          Obtaining the VR (Value Representation) might be needed by caller
1478  *          to convert the string typed content to caller's native type 
1479  *          (think of C++ vs Python). The VR is actually of a higher level
1480  *          of semantics than just the native C++ type.
1481  * @param   TagName name of the searched element.
1482  * @return  Corresponding element value representation when it exists,
1483  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1484  */
1485 std::string gdcmHeader::GetPubElValRepByName(std::string TagName) {
1486    gdcmElValue* elem =  PubElValSet.GetElementByName(TagName);
1487    if ( !elem )
1488       return GDCM_UNFOUND;
1489    return elem->GetVR();
1490 }
1491
1492 /**
1493  * \ingroup gdcmHeader
1494  * \brief   Searches within elements parsed with the SHADOW dictionary 
1495  *          for the element value of a given tag.
1496  * @param   group Group of the searched tag.
1497  * @param   element Element of the searched tag.
1498  * @return  Corresponding element value representation when it exists,
1499  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1500  */
1501 std::string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1502    return ShaElValSet.GetElValueByNumber(group, element);
1503 }
1504
1505 /**
1506  * \ingroup gdcmHeader
1507  * \brief   Searches within the elements parsed with the SHADOW dictionary
1508  *          for the element value representation of a given tag.
1509  *
1510  *          Obtaining the VR (Value Representation) might be needed by caller
1511  *          to convert the string typed content to caller's native type 
1512  *          (think of C++ vs Python). The VR is actually of a higher level
1513  *          of semantics than just the native C++ type.
1514  * @param   group Group of the searched tag.
1515  * @param   element Element of the searched tag.
1516  * @return  Corresponding element value representation when it exists,
1517  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1518  */
1519 std::string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1520    gdcmElValue* elem =  ShaElValSet.GetElementByNumber(group, element);
1521    if ( !elem )
1522       return GDCM_UNFOUND;
1523    return elem->GetVR();
1524 }
1525
1526 /**
1527  * \ingroup gdcmHeader
1528  * \brief   Searches within the elements parsed with the shadow dictionary
1529  *          for an element value of given tag.
1530  * @param   TagName name of the searched element.
1531  * @return  Corresponding element value when it exists, and the string
1532  *          GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1533  */
1534 std::string gdcmHeader::GetShaElValByName(std::string TagName) {
1535    return ShaElValSet.GetElValueByName(TagName);
1536 }
1537
1538 /**
1539  * \ingroup gdcmHeader
1540  * \brief   Searches within the elements parsed with the shadow dictionary for
1541  *          the element value representation of a given tag.
1542  *
1543  *          Obtaining the VR (Value Representation) might be needed by caller
1544  *          to convert the string typed content to caller's native type 
1545  *          (think of C++ vs Python). The VR is actually of a higher level
1546  *          of semantics than just the native C++ type.
1547  * @param   TagName name of the searched element.
1548  * @return  Corresponding element value representation when it exists,
1549  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1550  */
1551 std::string gdcmHeader::GetShaElValRepByName(std::string TagName) {
1552    gdcmElValue* elem =  ShaElValSet.GetElementByName(TagName);
1553    if ( !elem )
1554       return GDCM_UNFOUND;
1555    return elem->GetVR();
1556 }
1557
1558 /**
1559  * \ingroup gdcmHeader
1560  * \brief   Searches within elements parsed with the public dictionary 
1561  *          and then within the elements parsed with the shadow dictionary
1562  *          for the element value of a given tag.
1563  * @param   group Group of the searched tag.
1564  * @param   element Element of the searched tag.
1565  * @return  Corresponding element value representation when it exists,
1566  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1567  */
1568 std::string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1569    std::string pub = GetPubElValByNumber(group, element);
1570    if (pub.length())
1571       return pub;
1572    return GetShaElValByNumber(group, element);
1573 }
1574
1575 /**
1576  * \ingroup gdcmHeader
1577  * \brief   Searches within elements parsed with the public dictionary 
1578  *          and then within the elements parsed with the shadow dictionary
1579  *          for the element value representation of a given tag.
1580  *
1581  *          Obtaining the VR (Value Representation) might be needed by caller
1582  *          to convert the string typed content to caller's native type 
1583  *          (think of C++ vs Python). The VR is actually of a higher level
1584  *          of semantics than just the native C++ type.
1585  * @param   group Group of the searched tag.
1586  * @param   element Element of the searched tag.
1587  * @return  Corresponding element value representation when it exists,
1588  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1589  */
1590 std::string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1591    std::string pub = GetPubElValRepByNumber(group, element);
1592    if (pub.length())
1593       return pub;
1594    return GetShaElValRepByNumber(group, element);
1595 }
1596
1597 /**
1598  * \ingroup gdcmHeader
1599  * \brief   Searches within elements parsed with the public dictionary 
1600  *          and then within the elements parsed with the shadow dictionary
1601  *          for the element value of a given tag.
1602  * @param   TagName name of the searched element.
1603  * @return  Corresponding element value when it exists,
1604  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1605  */
1606 std::string gdcmHeader::GetElValByName(std::string TagName) {
1607    std::string pub = GetPubElValByName(TagName);
1608    if (pub.length())
1609       return pub;
1610    return GetShaElValByName(TagName);
1611 }
1612
1613 /**
1614  * \ingroup gdcmHeader
1615  * \brief   Searches within elements parsed with the public dictionary 
1616  *          and then within the elements parsed with the shadow dictionary
1617  *          for the element value representation of a given tag.
1618  *
1619  *          Obtaining the VR (Value Representation) might be needed by caller
1620  *          to convert the string typed content to caller's native type 
1621  *          (think of C++ vs Python). The VR is actually of a higher level
1622  *          of semantics than just the native C++ type.
1623  * @param   TagName name of the searched element.
1624  * @return  Corresponding element value representation when it exists,
1625  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1626  */
1627 std::string gdcmHeader::GetElValRepByName(std::string TagName) {
1628    std::string pub = GetPubElValRepByName(TagName);
1629    if (pub.length())
1630       return pub;
1631    return GetShaElValRepByName(TagName);
1632 }
1633
1634 /**
1635  * \ingroup gdcmHeader
1636  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1637  *          through it's (group, element) and modifies it's content with
1638  *          the given value.
1639  * @param   content new value to substitute with
1640  * @param   group   group of the ElVal to modify
1641  * @param   element element of the ElVal to modify
1642  */
1643 int gdcmHeader::SetPubElValByNumber(std::string content, guint16 group,
1644                                     guint16 element)
1645                                     
1646 //TODO  : homogeneiser les noms : SetPubElValByNumber   
1647 //                    qui appelle PubElValSet.SetElValueByNumber 
1648 //        pourquoi pas            SetPubElValueByNumber ??
1649 {
1650
1651    return (  PubElValSet.SetElValueByNumber (content, group, element) );
1652 }
1653
1654 /**
1655  * \ingroup gdcmHeader
1656  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1657  *          through tag name and modifies it's content with the given value.
1658  * @param   content new value to substitute with
1659  * @param   TagName name of the tag to be modified
1660  */
1661 int gdcmHeader::SetPubElValByName(std::string content, std::string TagName) {
1662    return (  PubElValSet.SetElValueByName (content, TagName) );
1663 }
1664
1665 /**
1666  * \ingroup gdcmHeader
1667  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1668  *          through it's (group, element) and modifies it's length with
1669  *          the given value.
1670  * \warning Use with extreme caution.
1671  * @param   length new length to substitute with
1672  * @param   group   group of the ElVal to modify
1673  * @param   element element of the ElVal to modify
1674  * @return  1 on success, 0 otherwise.
1675  */
1676
1677 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1678                                     guint16 element) {
1679         return (  PubElValSet.SetElValueLengthByNumber (length, group, element) );
1680 }
1681
1682 /**
1683  * \ingroup gdcmHeader
1684  * \brief   Accesses an existing gdcmElValue in the ShaElValSet of this instance
1685  *          through it's (group, element) and modifies it's content with
1686  *          the given value.
1687  * @param   content new value to substitute with
1688  * @param   group   group of the ElVal to modify
1689  * @param   element element of the ElVal to modify
1690  * @return  1 on success, 0 otherwise.
1691  */
1692 int gdcmHeader::SetShaElValByNumber(std::string content,
1693                                     guint16 group, guint16 element) {
1694    return (  ShaElValSet.SetElValueByNumber (content, group, element) );
1695 }
1696
1697 /**
1698  * \ingroup gdcmHeader
1699  * \brief   Accesses an existing gdcmElValue in the ShaElValSet of this instance
1700  *          through tag name and modifies it's content with the given value.
1701  * @param   content new value to substitute with
1702  * @param   ShadowTagName name of the tag to be modified
1703  */
1704 int gdcmHeader::SetShaElValByName(std::string content, std::string ShadowTagName) {
1705    return (  ShaElValSet.SetElValueByName (content, ShadowTagName) );
1706 }
1707
1708 /**
1709  * \ingroup gdcmHeader
1710  * \brief   Parses the header of the file but WITHOUT loading element values.
1711  */
1712 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1713    gdcmElValue * newElValue = (gdcmElValue *)0;
1714    
1715    rewind(fp);
1716    CheckSwap();
1717    while ( (newElValue = ReadNextElement()) ) { 
1718       SkipElementValue(newElValue);
1719       PubElValSet.Add(newElValue);
1720    }
1721 }
1722
1723 /**
1724  * \ingroup gdcmHeader
1725  * \brief  This predicate, based on hopefully reasonable heuristics,
1726  *         decides whether or not the current gdcmHeader was properly parsed
1727  *         and contains the mandatory information for being considered as
1728  *         a well formed and usable image.
1729  * @return true when gdcmHeader is the one of a reasonable Dicom file,
1730  *         false otherwise. 
1731  */
1732 bool gdcmHeader::IsReadable(void) {
1733    if (   GetElValByName("Image Dimensions") != GDCM_UNFOUND
1734       && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1735       return false;
1736    }
1737    if ( GetElValByName("Bits Allocated")       == GDCM_UNFOUND )
1738       return false;
1739    if ( GetElValByName("Bits Stored")          == GDCM_UNFOUND )
1740       return false;
1741    if ( GetElValByName("High Bit")             == GDCM_UNFOUND )
1742       return false;
1743    if ( GetElValByName("Pixel Representation") == GDCM_UNFOUND )
1744       return false;
1745    return true;
1746 }
1747
1748 /**
1749  * \ingroup gdcmHeader
1750  * \brief   Small utility function that creates a new manually crafted
1751  *          (as opposed as read from the file) gdcmElValue with user
1752  *          specified name and adds it to the public tag hash table.
1753  * \note    A fake TagKey is generated so the PubDict can keep it's coherence.
1754  * @param   NewTagName The name to be given to this new tag.
1755  * @param   VR The Value Representation to be given to this new tag.
1756  * @ return The newly hand crafted Element Value.
1757  */
1758 gdcmElValue* gdcmHeader::NewManualElValToPubDict(std::string NewTagName, 
1759                                                  std::string VR) {
1760    gdcmElValue* NewElVal = (gdcmElValue*)0;
1761    guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
1762    guint32 FreeElem = 0;
1763    gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1764
1765    FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1766    if (FreeElem == UINT32_MAX) {
1767       dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1768                      "Group 0xffff in Public Dict is full");
1769       return (gdcmElValue*)0;
1770    }
1771    NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1772                                 VR, "GDCM", NewTagName);
1773    NewElVal = new gdcmElValue(NewEntry);
1774    PubElValSet.Add(NewElVal);
1775    return NewElVal;
1776 }
1777
1778 /**
1779  * \ingroup gdcmHeader
1780  * \brief   Loads the element values of all the elements present in the
1781  *          public tag based hash table.
1782  */
1783 void gdcmHeader::LoadElements(void) {
1784    rewind(fp);
1785    
1786    // We don't use any longer the HashTable, since a lot a stuff is missing
1787    // when SeQuences were encountered 
1788    //  
1789    //TagElValueHT ht = PubElValSet.GetTagHt();
1790    //for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1791    //     LoadElementValue(tag->second);
1792    //}
1793    
1794      for (std::list<gdcmElValue*>::iterator i = GetListElem().begin();  
1795            i != GetListElem().end();
1796            ++i){
1797         LoadElementValue(*i);   
1798      }    
1799     
1800    rewind(fp);
1801
1802    // Load 'non string' values   
1803    std::string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);   
1804    if( PhotometricInterpretation == "PALETTE COLOR " ){ 
1805       LoadElementVoidArea(0x0028,0x1200);  // gray LUT   
1806       LoadElementVoidArea(0x0028,0x1201);  // R    LUT
1807       LoadElementVoidArea(0x0028,0x1202);  // G    LUT
1808       LoadElementVoidArea(0x0028,0x1203);  // B    LUT
1809       
1810       LoadElementVoidArea(0x0028,0x1221);  // Segmented Red   Palette Color LUT Data
1811       LoadElementVoidArea(0x0028,0x1222);  // Segmented Green Palette Color LUT Data
1812       LoadElementVoidArea(0x0028,0x1223);  // Segmented Blue  Palette Color LUT Data
1813    }
1814
1815    // --------------------------------------------------------------
1816    // Special Patch to allow gdcm to read ACR-LibIDO formated images
1817    //
1818    // if recognition code tells us we deal with a LibIDO image
1819    // we switch lineNumber and columnNumber
1820    //
1821    std::string RecCode; 
1822    RecCode = GetPubElValByNumber(0x0008, 0x0010);
1823    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1824        RecCode == "CANRME_AILIBOD1_1." ) {
1825          filetype = ACR_LIBIDO; 
1826          std::string rows    = GetPubElValByNumber(0x0028, 0x0010);
1827          std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1828          SetPubElValByNumber(columns, 0x0028, 0x0010);
1829          SetPubElValByNumber(rows   , 0x0028, 0x0011);
1830    }
1831    // ----------------- End of Special Patch ----------------
1832 }
1833
1834 /**
1835   * \ingroup gdcmHeader
1836   * \brief
1837   * @return
1838   */ 
1839 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1840    PubElValSet.Print(os);
1841 }
1842
1843 /**
1844   * \ingroup gdcmHeader
1845   * \brief 
1846   * @return
1847   */  
1848 void gdcmHeader::PrintPubDict(std::ostream & os) {
1849    RefPubDict->Print(os);
1850 }
1851
1852 /**
1853   * \ingroup gdcmHeader
1854   * \brief
1855   * @return integer, acts as a Boolean
1856   */ 
1857 int gdcmHeader::Write(FILE * fp, FileType type) {
1858
1859    // TODO : move the following lines (and a lot of others, to be written)
1860    // to a future function CheckAndCorrectHeader
1861
1862    if (type == ImplicitVR) {
1863       std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
1864       ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
1865       
1866       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1867       //      values with a VR of UI shall be padded with a single trailing null
1868       //      Dans le cas suivant on doit pader manuellement avec un 0
1869       
1870       PubElValSet.SetElValueLengthByNumber(18, 0x0002, 0x0010);
1871    } 
1872
1873    if (type == ExplicitVR) {
1874       std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
1875       ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
1876       
1877       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1878       //      values with a VR of UI shall be padded with a single trailing null
1879       //      Dans le cas suivant on doit pader manuellement avec un 0
1880       
1881       PubElValSet.SetElValueLengthByNumber(20, 0x0002, 0x0010);
1882    }
1883
1884    return PubElValSet.Write(fp, type);
1885 }
1886
1887 //
1888 // ------------------------ 'non string' elements related functions
1889 //
1890
1891 /**
1892  * \ingroup       gdcmHeader
1893  * \brief         Loads (from disk) the element content 
1894  *                when a string is not suitable
1895  */
1896 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1897    gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1898    if ( !Element )
1899       return NULL;
1900    size_t o =(size_t)Element->GetOffset();
1901    fseek(fp, o, SEEK_SET);
1902    int l=Element->GetLength();
1903    void * a = malloc(l);
1904    if(!a) {
1905         std::cout << "Big Broblem (LoadElementVoidArea, malloc) " 
1906                   << std::hex << Group << " " << Elem << std::endl;
1907         return NULL;
1908    }  
1909    /* int res = */ PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1910    // TODO check the result 
1911    size_t l2 = fread(a, 1, l ,fp);
1912    if(l != l2) {
1913         std::cout << "Big Broblem (LoadElementVoidArea, fread) " 
1914                   << std::hex << Group << " " << Elem << std::endl;
1915         free(a);
1916         return NULL;
1917    }
1918    return a;  
1919 }
1920
1921 /**
1922  * \ingroup gdcmHeader
1923  * \brief   Gets (from Header) the offset  of a 'non string' element value 
1924  * \        (LoadElementValue has already be executed)
1925  * @param   Group
1926  * @param   Elem
1927  * @return File Offset of the Element Value 
1928  */
1929  size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1930    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1931    if (!elValue) {
1932       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1933                       "failed to Locate gdcmElValue");
1934       return (size_t)0;
1935    }
1936    return elValue->GetOffset();
1937 }
1938
1939 /**
1940  * \ingroup gdcmHeader
1941 * \brief   Gets (from Header) a 'non string' element value 
1942  * \        (LoadElementValue has already be executed)  
1943  * @param   Group
1944  * @param   Elem
1945  * @return Pointer to the 'non string' area
1946  
1947  */
1948  void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1949    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1950    if (!elValue) {
1951       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1952                   "failed to Locate gdcmElValue");
1953       return (NULL);
1954    }
1955    return elValue->GetVoidArea();
1956 }
1957
1958
1959 //
1960 // =============================================================================
1961 //   Heuristics based accessors
1962 //==============================================================================
1963 //
1964
1965 // TODO : move to an other file.
1966
1967
1968 /**
1969  * \ingroup gdcmHeader
1970  * \brief   Retrieve the number of columns of image.
1971  * @return  The encountered size when found, 0 by default.
1972  */
1973 int gdcmHeader::GetXSize(void) {
1974    // We cannot check for "Columns" because the "Columns" tag is present
1975    // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1976    std::string StrSize = GetPubElValByNumber(0x0028,0x0011);
1977    if (StrSize == GDCM_UNFOUND)
1978       return 0;
1979    return atoi(StrSize.c_str());
1980 }
1981
1982 /**
1983  * \ingroup gdcmHeader
1984  * \brief   Retrieve the number of lines of image.
1985  * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1986  * @return  The encountered size when found, 1 by default.
1987  */
1988 int gdcmHeader::GetYSize(void) {
1989    // We cannot check for "Rows" because the "Rows" tag is present
1990    // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1991    std::string StrSize = GetPubElValByNumber(0x0028,0x0010);
1992    if (StrSize != GDCM_UNFOUND)
1993       return atoi(StrSize.c_str());
1994    if ( IsDicomV3() )
1995       return 0;
1996    else
1997       // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1998       // hence be a signal (1d image). So we default to 1:
1999       return 1;
2000 }
2001
2002 /**
2003  * \ingroup gdcmHeader
2004  * \brief   Retrieve the number of planes of volume or the number
2005  *          of frames of a multiframe.
2006  * \warning When present we consider the "Number of Frames" as the third
2007  *          dimension. When absent we consider the third dimension as
2008  *          being the "Planes" tag content.
2009  * @return  The encountered size when found, 1 by default.
2010  */
2011 int gdcmHeader::GetZSize(void) {
2012    // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
2013    // as the third dimension.
2014    std::string StrSize = GetPubElValByNumber(0x0028,0x0008);
2015    if (StrSize != GDCM_UNFOUND)
2016       return atoi(StrSize.c_str());
2017
2018    // We then consider the "Planes" entry as the third dimension [we
2019    // cannot retrieve by name since "Planes tag is present both in
2020    // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary]. 
2021    StrSize = GetPubElValByNumber(0x0028,0x0012);
2022    if (StrSize != GDCM_UNFOUND)
2023       return atoi(StrSize.c_str());
2024    return 1;
2025 }
2026
2027 /**
2028  * \ingroup gdcmHeader
2029  * \brief   Retrieve the number of Bits Stored
2030  *          (as opposite to number of Bits Allocated)
2031  * 
2032  * @return  The encountered number of Bits Stored, 0 by default.
2033  */
2034 int gdcmHeader::GetBitsStored(void) { 
2035    std::string StrSize = GetPubElValByNumber(0x0028,0x0101);
2036    if (StrSize == GDCM_UNFOUND)
2037       return 1;
2038    return atoi(StrSize.c_str());
2039 }
2040
2041 /**
2042  * \ingroup gdcmHeader
2043  * \brief   Retrieve the number of Bits Allocated
2044  *          (8, 12 -compacted ACR-NEMA files, 16, ...)
2045  * 
2046  * @return  The encountered number of Bits Allocated, 0 by default.
2047  */
2048 int gdcmHeader::GetBitsAllocated(void) { 
2049    std::string StrSize = GetPubElValByNumber(0x0028,0x0100);
2050    if (StrSize == GDCM_UNFOUND)
2051       return 1;
2052    return atoi(StrSize.c_str());
2053 }
2054
2055 /**
2056  * \ingroup gdcmHeader
2057  * \brief   Retrieve the number of Samples Per Pixel
2058  *          (1 : gray level, 3 : RGB -1 or 3 Planes-)
2059  * 
2060  * @return  The encountered number of Samples Per Pixel, 1 by default.
2061  */
2062 int gdcmHeader::GetSamplesPerPixel(void) { 
2063    std::string StrSize = GetPubElValByNumber(0x0028,0x0002);
2064    if (StrSize == GDCM_UNFOUND)
2065       return 1; // Well, it's supposed to be mandatory ...
2066    return atoi(StrSize.c_str());
2067 }
2068
2069 /**
2070  * \ingroup gdcmHeader
2071  * \brief   Retrieve the Planar Configuration for RGB images
2072  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
2073  * 
2074  * @return  The encountered Planar Configuration, 0 by default.
2075  */
2076 int gdcmHeader::GetPlanarConfiguration(void) { 
2077    std::string StrSize = GetPubElValByNumber(0x0028,0x0006);
2078    if (StrSize == GDCM_UNFOUND)
2079       return 0;
2080    return atoi(StrSize.c_str());
2081 }
2082
2083 /**
2084  * \ingroup gdcmHeader
2085  * \brief   Return the size (in bytes) of a single pixel of data.
2086  * @return  The size in bytes of a single pixel of data.
2087  *
2088  */
2089 int gdcmHeader::GetPixelSize(void) {
2090    std::string PixelType = GetPixelType();
2091    if (PixelType == "8U"  || PixelType == "8S")
2092       return 1;
2093    if (PixelType == "16U" || PixelType == "16S")
2094       return 2;
2095    if (PixelType == "32U" || PixelType == "32S")
2096       return 4;
2097    dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
2098    return 0;
2099 }
2100
2101 /**
2102  * \ingroup gdcmHeader
2103  * \brief   Build the Pixel Type of the image.
2104  *          Possible values are:
2105  *          - 8U  unsigned  8 bit,
2106  *          - 8S    signed  8 bit,
2107  *          - 16U unsigned 16 bit,
2108  *          - 16S   signed 16 bit,
2109  *          - 32U unsigned 32 bit,
2110  *          - 32S   signed 32 bit,
2111  * \warning 12 bit images appear as 16 bit.
2112  * \        24 bit images appear as 8 bit
2113  * @return  
2114  */
2115 std::string gdcmHeader::GetPixelType(void) {
2116    std::string BitsAlloc;
2117    BitsAlloc = GetElValByName("Bits Allocated");
2118    if (BitsAlloc == GDCM_UNFOUND) {
2119       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
2120       BitsAlloc = std::string("16");
2121    }
2122    if (BitsAlloc == "12")            // It will be unpacked
2123       BitsAlloc = std::string("16");
2124    else if (BitsAlloc == "24")       // (in order no to be messed up
2125       BitsAlloc = std::string("8");  // by old RGB images)
2126      
2127    std::string Signed;
2128    Signed = GetElValByName("Pixel Representation");
2129    if (Signed == GDCM_UNFOUND) {
2130       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
2131       BitsAlloc = std::string("0");
2132    }
2133    if (Signed == "0")
2134       Signed = std::string("U");
2135    else
2136
2137 std::cout << "GetPixelType : " << BitsAlloc + Signed << std::endl;
2138       Signed = std::string("S");
2139
2140    return( BitsAlloc + Signed);
2141 }
2142
2143 /**
2144   * \ingroup gdcmHeader
2145   * \brief gets the info from 0002,0010 : Transfert Syntax
2146   * \           else 1.
2147   * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
2148   */
2149 std::string gdcmHeader::GetTransferSyntaxName(void) { 
2150    std::string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
2151    if (TransfertSyntax == GDCM_UNFOUND) {
2152       dbg.Verbose(0, "gdcmHeader::GetTransferSyntaxName: unfound Transfert Syntax (0002,0010)");
2153       return "Uncompressed ACR-NEMA";
2154    }
2155    // we do it only when we need it
2156    gdcmTS * ts = gdcmGlobal::GetTS();
2157    std::string tsName=ts->GetValue(TransfertSyntax);
2158    //delete ts; // Seg Fault when deleted ?!
2159    return tsName;
2160 }
2161
2162 // -------------------------------- Lookup Table related functions ------------
2163
2164 /**
2165   * \ingroup gdcmHeader
2166   * \brief tells us if LUT are used
2167   * \warning Right now, Segmented xxx Palette Color Lookup Table Data
2168   * \        are NOT considered as LUT, since nobody knows
2169   *\         how to deal with them
2170   * @return int acts as a Boolean 
2171   */
2172   
2173 int gdcmHeader::HasLUT(void) {
2174
2175    // Check the presence of the LUT Descriptors 
2176    if (GetPubElValByNumber(0x0028,0x1101) == GDCM_UNFOUND)
2177       return 0;
2178    // LutDescriptorGreen 
2179    if (GetPubElValByNumber(0x0028,0x1102) == GDCM_UNFOUND)
2180       return 0;
2181    // LutDescriptorBlue 
2182    if (GetPubElValByNumber(0x0028,0x1103) == GDCM_UNFOUND)
2183       return 0;
2184    //  It is not enough
2185    // we check also 
2186    if (GetPubElValByNumber(0x0028,0x1201) == GDCM_UNFOUND)
2187       return 0;  
2188    if (GetPubElValByNumber(0x0028,0x1202) == GDCM_UNFOUND)
2189       return 0;
2190    if (GetPubElValByNumber(0x0028,0x1203) == GDCM_UNFOUND)
2191       return 0;   
2192    return 1;
2193 }
2194
2195 /**
2196   * \ingroup gdcmHeader
2197   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2198   * \           else 0
2199   * @return Lookup Table nBit 
2200   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ] 
2201   */
2202   
2203 int gdcmHeader::GetLUTNbits(void) {
2204    std::vector<std::string> tokens;
2205    //int LutLength;
2206    //int LutDepth;
2207    int LutNbits;
2208    //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2209    // Consistency already checked in GetLUTLength
2210    std::string LutDescription = GetPubElValByNumber(0x0028,0x1101);
2211    if (LutDescription == GDCM_UNFOUND)
2212       return 0;
2213    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2214    Tokenize (LutDescription, tokens, "\\");
2215    //LutLength=atoi(tokens[0].c_str());
2216    //LutDepth=atoi(tokens[1].c_str());
2217    LutNbits=atoi(tokens[2].c_str());
2218    tokens.clear();
2219    return LutNbits;
2220 }
2221
2222 /**
2223   * \ingroup gdcmHeader
2224   * \brief builts Red/Green/Blue/Alpha LUT from Header
2225   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2226   * \        and (0028,1101),(0028,1102),(0028,1102)  
2227   * \          - xxx Palette Color Lookup Table Descriptor - are found
2228   * \        and (0028,1201),(0028,1202),(0028,1202) 
2229   * \          - xxx Palette Color Lookup Table Data - are found 
2230   * \warning does NOT deal with :
2231   * \ 0028 1100 Gray Lookup Table Descriptor (Retired)
2232   * \ 0028 1221 Segmented Red Palette Color Lookup Table Data
2233   * \ 0028 1222 Segmented Green Palette Color Lookup Table Data
2234   * \ 0028 1223 Segmented Blue Palette Color Lookup Table Data 
2235   * \ no known Dicom reader deails with them :-(
2236   * @return Lookup Table RGBA
2237   */ 
2238   
2239 unsigned char * gdcmHeader::GetLUTRGBA(void) {
2240 // Not so easy : see 
2241 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
2242 // and  OT-PAL-8-face.dcm
2243
2244 //  if Photometric Interpretation # PALETTE COLOR, no LUT to be done
2245                  
2246    if (gdcmHeader::GetPubElValByNumber(0x0028,0x0004) != "PALETTE COLOR ") {
2247         return NULL;
2248    }  
2249
2250    int lengthR, debR, nbitsR;
2251    int lengthG, debG, nbitsG;
2252    int lengthB, debB, nbitsB;
2253    
2254 // Get info from Lut Descriptors
2255 // (the 3 LUT descriptors may be different)    
2256    
2257    std::string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
2258    if (LutDescriptionR == GDCM_UNFOUND)
2259       return NULL;
2260    std::string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
2261    if (LutDescriptionG == GDCM_UNFOUND)
2262       return NULL;   
2263    std::string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
2264    if (LutDescriptionB == GDCM_UNFOUND)
2265       return NULL;
2266       
2267    std::vector<std::string> tokens;
2268       
2269    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2270    Tokenize (LutDescriptionR, tokens, "\\");
2271    lengthR=atoi(tokens[0].c_str()); // Red LUT length in Bytes
2272    debR   =atoi(tokens[1].c_str()); // subscript of the first Lut Value
2273    nbitsR =atoi(tokens[2].c_str()); // Lut item size (in Bits)
2274    tokens.clear();
2275    
2276    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2277    Tokenize (LutDescriptionG, tokens, "\\");
2278    lengthG=atoi(tokens[0].c_str()); // Green LUT length in Bytes
2279    debG   =atoi(tokens[1].c_str());
2280    nbitsG =atoi(tokens[2].c_str());
2281    tokens.clear();  
2282    
2283    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2284    Tokenize (LutDescriptionB, tokens, "\\");
2285    lengthB=atoi(tokens[0].c_str()); // Blue LUT length in Bytes
2286    debB   =atoi(tokens[1].c_str());
2287    nbitsB =atoi(tokens[2].c_str());
2288    tokens.clear();
2289  
2290 // Load LUTs into memory, (as they were stored on disk)
2291    
2292    unsigned char *lutR =(unsigned char *)
2293                                    GetPubElValVoidAreaByNumber(0x0028,0x1201);
2294    unsigned char *lutG =(unsigned char *)
2295                                    GetPubElValVoidAreaByNumber(0x0028,0x1202);
2296    unsigned char *lutB =(unsigned char *)
2297                                    GetPubElValVoidAreaByNumber(0x0028,0x1203); 
2298    
2299    if (!lutR || !lutG || !lutB ) {
2300         return NULL;
2301    } 
2302  // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT 
2303    
2304   unsigned char *LUTRGBA = (unsigned char *)calloc(1024,1); // 256 * 4 (R, G, B, Alpha) 
2305   if (!LUTRGBA) {
2306      return NULL;
2307   }
2308   memset(LUTRGBA, 0, 1024);
2309         // Bits Allocated
2310    int nb;
2311    std::string str_nb = GetPubElValByNumber(0x0028,0x0100);
2312    if (str_nb == GDCM_UNFOUND ) {
2313       nb = 16;
2314    } else {
2315       nb = atoi(str_nb.c_str() );
2316    }  
2317   int mult;
2318   
2319   if (nbitsR==16 && nb==8) // when LUT item size is different than pixel size
2320      mult=2;               // high byte must be = low byte 
2321   else                     // See PS 3.3-2003 C.11.1.1.2 p 619
2322      mult=1; 
2323  
2324  
2325             // if we get a black image, let's just remove the '+1'
2326             // from 'i*mult+1' and check again 
2327             // if it works, we shall have to check the 3 Palettes
2328             // to see which byte is ==0 (first one, or second one)
2329             // and fix the code
2330             // We give up the checking to avoid some overhead 
2331             
2332   unsigned char *a;      
2333   int i;
2334   a= LUTRGBA+0;
2335   for(i=0;i<lengthR;i++) {
2336      *a = lutR[i*mult+1]; 
2337      a+=4;       
2338   }        
2339   a= LUTRGBA+1;
2340   for(i=0;i<lengthG;i++) {
2341      *a = lutG[i*mult+1]; 
2342      a+=4;       
2343   }  
2344   a= LUTRGBA+2;
2345   for(i=0;i<lengthB;i++) {
2346      *a = lutB[i*mult+1]; 
2347      a+=4;       
2348   }  
2349   a= LUTRGBA+3;
2350   for(i=0;i<256;i++) {
2351      *a = 1; // Alpha component
2352      a+=4; 
2353   } 
2354       
2355 //How to free the now useless LUTs?
2356 //
2357 //free(LutR); free(LutB); free(LutG);
2358
2359   return(LUTRGBA);   
2360
2361