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