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