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