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