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