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