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