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