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