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