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