]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
- gdcmDebug set to 0 in ordrer to avaoid some spurious outputs
[gdcm.git] / src / gdcmHeader.cxx
1
2 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.77 2003/07/03 11:29:34 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 already 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 already 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 already 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 already 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 already 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 already 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 already 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 already 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       long l = ftell(fp);
592
593       if (errno == 1)
594          return 0;
595       TotalLength += 4;  // We even have to decount the group and element 
596      
597       if ( g != 0xfffe           && g!=0xb00c ) /*for bogus header */ {
598          char msg[100]; // for sprintf. Sorry
599          sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
600          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg); 
601          long l = ftell(fp);
602          errno = 1;
603          return 0;
604       }
605       if ( n == 0xe0dd       || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header  */ 
606          FoundSequenceDelimiter = true;
607       else if ( n != 0xe000 ){
608          char msg[100];  // for sprintf. Sorry
609          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,n);
610          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
611          errno = 1;
612          return 0;
613       }
614       ItemLength = ReadInt32();
615       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
616                                       // the ItemLength with ReadInt32
617                                       
618       SkipBytes(ItemLength);
619    }
620    fseek(fp, PositionOnEntry, SEEK_SET);
621    return TotalLength;
622 }
623
624 /**
625  * \ingroup gdcmHeader
626  * \brief   
627  *
628  * @return 
629  */
630  void gdcmHeader::FindLength (gdcmElValue * ElVal) {
631    guint16 element = ElVal->GetElement();
632    guint16 group   = ElVal->GetGroup();
633    string  vr      = ElVal->GetVR();
634    guint16 length16;
635    if( (element == 0x0010) && (group == 0x7fe0) ) {
636       dbg.SetDebug(0);
637       dbg.Verbose(2, "gdcmHeader::FindLength: ",
638                      "on est sur 7fe0 0010");
639    }   
640    
641    if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
642       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
643       
644          // The following reserved two bytes (see PS 3.5-2001, section
645          // 7.1.2 Data element structure with explicit vr p27) must be
646          // skipped before proceeding on reading the length on 4 bytes.
647          fseek(fp, 2L, SEEK_CUR);
648
649          guint32 length32 = ReadInt32();
650          if ( (vr == "OB") && (length32 == 0xffffffff) ) {
651             ElVal->SetLength(FindLengthOB());
652             return;
653          }
654          FixFoundLength(ElVal, length32);        
655          return;
656       }
657
658       // Length is encoded on 2 bytes.
659       length16 = ReadInt16();
660       
661       // We can tell the current file is encoded in big endian (like
662       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
663       // and it's value is the one of the encoding of a big endian file.
664       // In order to deal with such big endian encoded files, we have
665       // (at least) two strategies:
666       // * when we load the "Transfer Syntax" tag with value of big endian
667       //   encoding, we raise the proper flags. Then we wait for the end
668       //   of the META group (0x0002) among which is "Transfer Syntax",
669       //   before switching the swap code to big endian. We have to postpone
670       //   the switching of the swap code since the META group is fully encoded
671       //   in little endian, and big endian coding only starts at the next
672       //   group. The corresponding code can be hard to analyse and adds
673       //   many additional unnecessary tests for regular tags.
674       // * the second strategy consists in waiting for trouble, that shall
675       //   appear when we find the first group with big endian encoding. This
676       //   is easy to detect since the length of a "Group Length" tag (the
677       //   ones with zero as element number) has to be of 4 (0x0004). When we
678       //   encouter 1024 (0x0400) chances are the encoding changed and we
679       //   found a group with big endian encoding.
680       // We shall use this second strategy. In order to make sure that we
681       // can interpret the presence of an apparently big endian encoded
682       // length of a "Group Length" without committing a big mistake, we
683       // add an additional check: we look in the already parsed elements
684       // for the presence of a "Transfer Syntax" whose value has to be "big
685       // endian encoding". When this is the case, chances are we have got our
686       // hands on a big endian encoded file: we switch the swap code to
687       // big endian and proceed...
688       if ( (element  == 0x0000) && (length16 == 0x0400) ) {
689          if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
690             dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
691             errno = 1;
692             return;
693          }
694          length16 = 4;
695          SwitchSwapToBigEndian();
696          // Restore the unproperly loaded values i.e. the group, the element
697          // and the dictionary entry depending on them.
698          guint16 CorrectGroup   = SwapShort(ElVal->GetGroup());
699          guint16 CorrectElem    = SwapShort(ElVal->GetElement());
700          gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
701                                                        CorrectElem);
702          if (!NewTag) {
703             // This correct tag is not in the dictionary. Create a new one.
704             NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
705          }
706          // FIXME this can create a memory leaks on the old entry that be
707          // left unreferenced.
708          ElVal->SetDictEntry(NewTag);
709       }
710        
711       // Heuristic: well some files are really ill-formed.
712       if ( length16 == 0xffff) {
713          length16 = 0;
714          dbg.Verbose(0, "gdcmHeader::FindLength",
715                      "Erroneous element length fixed.");
716       }
717       FixFoundLength(ElVal, (guint32)length16);
718       return;
719    }
720
721    // Either implicit VR or a non DICOM conformal (see not below) explicit
722    // VR that ommited the VR of (at least) this element. Farts happen.
723    // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
724    // on Data elements "Implicit and Explicit VR Data Elements shall
725    // not coexist in a Data Set and Data Sets nested within it".]
726    // Length is on 4 bytes.
727    FixFoundLength(ElVal, ReadInt32());
728 }
729
730 /**
731  * \ingroup gdcmHeader
732  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
733  *          processor order.
734  *
735  * @return  The suggested integer.
736  */
737 guint32 gdcmHeader::SwapLong(guint32 a) {
738    switch (sw) {
739    case    0 :
740       break;
741    case 4321 :
742       a=(   ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000)    | 
743             ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
744       break;
745    
746    case 3412 :
747       a=(   ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
748       break;
749    
750    case 2143 :
751       a=(    ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
752       break;
753    default :
754       dbg.Error(" gdcmHeader::SwapLong : unset swap code");
755       a=0;
756    }
757    return(a);
758 }
759
760 /**
761  * \ingroup gdcmHeader
762  * \brief   Swaps the bytes so they agree with the processor order
763  * @return  The properly swaped 16 bits integer.
764  */
765 guint16 gdcmHeader::SwapShort(guint16 a) {
766    if ( (sw==4321)  || (sw==2143) )
767       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
768    return (a);
769 }
770
771 /**
772  * \ingroup gdcmHeader
773  * \brief   
774  *
775  * @return 
776  */
777  void gdcmHeader::SkipBytes(guint32 NBytes) {
778    //FIXME don't dump the returned value
779    (void)fseek(fp, (long)NBytes, SEEK_CUR);
780 }
781
782 /**
783  * \ingroup gdcmHeader
784  * \brief   
785  *
786  * @return 
787  */
788  void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
789    SkipBytes(ElVal->GetLength());
790 }
791
792 /**
793  * \ingroup gdcmHeader
794  * \brief   
795  *
796  * @return 
797  */
798  void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
799    if (NewSize < 0)
800       return;
801    if ((guint32)NewSize >= (guint32)0xffffffff) {
802       MaxSizeLoadElementValue = 0xffffffff;
803       return;
804    }
805    MaxSizeLoadElementValue = NewSize;
806 }
807
808 /**
809  * \ingroup       gdcmHeader
810  * \brief         Loads the element content if it's length is not bigger
811  *                than the value specified with
812  *                gdcmHeader::SetMaxSizeLoadElementValue()
813  */
814 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
815    size_t item_read;
816    guint16 group  = ElVal->GetGroup();
817    string  vr     = ElVal->GetVR();
818    guint32 length = ElVal->GetLength();
819    bool SkipLoad  = false;
820
821    fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
822    
823    // FIXME Sequences not treated yet !
824    //
825    // Ne faudrait-il pas au contraire trouver immediatement
826    // une maniere 'propre' de traiter les sequences (vr = SQ)
827    // car commencer par les ignorer risque de conduire a qq chose
828    // qui pourrait ne pas etre generalisable
829    // Well, I'm expecting your code !!!
830     
831    if( vr == "SQ" )
832       SkipLoad = true;
833
834    // Heuristic : a sequence "contains" a set of tags (called items). It looks
835    // like the last tag of a sequence (the one that terminates the sequence)
836    // has a group of 0xfffe (with a dummy length).
837    if( group == 0xfffe )
838       SkipLoad = true;
839
840    if ( SkipLoad ) {
841       ElVal->SetLength(0);
842       ElVal->SetValue("gdcm::Skipped");
843       return;
844    }
845
846    // When the length is zero things are easy:
847    if ( length == 0 ) {
848       ElVal->SetValue("");
849       return;
850    }
851
852    // The elements whose length is bigger than the specified upper bound
853    // are not loaded. Instead we leave a short notice of the offset of
854    // the element content and it's length.
855    if (length > MaxSizeLoadElementValue) {
856       ostringstream s;
857       s << "gdcm::NotLoaded.";
858       s << " Address:" << (long)ElVal->GetOffset();
859       s << " Length:"  << ElVal->GetLength();
860       ElVal->SetValue(s.str());
861       return;
862    }
863    
864    // When an integer is expected, read and convert the following two or
865    // four bytes properly i.e. as an integer as opposed to a string.
866         
867         // pour les elements de Value Multiplicity > 1
868         // on aura en fait une serie d'entiers  
869         // on devrait pouvoir faire + compact (?)
870                 
871    if ( IsAnInteger(ElVal) ) {
872       guint32 NewInt;
873       ostringstream s;
874       int nbInt;
875       if (vr == "US" || vr == "SS") {
876          nbInt = length / 2;
877          NewInt = ReadInt16();
878          s << NewInt;
879          if (nbInt > 1) {
880             for (int i=1; i < nbInt; i++) {
881                s << '\\';
882                NewInt = ReadInt16();
883                s << NewInt;
884             }
885          }
886                         
887       } else if (vr == "UL" || vr == "SL") {
888          nbInt = length / 4;
889          NewInt = ReadInt32();
890          s << NewInt;
891          if (nbInt > 1) {
892             for (int i=1; i < nbInt; i++) {
893                s << '\\';
894                NewInt = ReadInt32();
895                s << NewInt;
896             }
897          }
898       }                                 
899       ElVal->SetValue(s.str());
900       return;   
901    }
902    
903    // We need an additional byte for storing \0 that is not on disk
904    char* NewValue = (char*)malloc(length+1);
905    if( !NewValue) {
906       dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
907       return;
908    }
909    NewValue[length]= 0;
910    
911    item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
912    if ( item_read != 1 ) {
913       free(NewValue);
914       dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
915       ElVal->SetValue("gdcm::UnRead");
916       return;
917    }
918    ElVal->SetValue(NewValue);
919    free(NewValue);
920 }
921
922 /**
923  * \ingroup       gdcmHeader
924  * \brief         Loads the element while preserving the current
925  *                underlying file position indicator as opposed to
926  *                to LoadElementValue that modifies it.
927  * @param ElVal   Element whose value shall be loaded. 
928  * @return  
929  */
930 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
931    long PositionOnEntry = ftell(fp);
932    LoadElementValue(ElVal);
933    fseek(fp, PositionOnEntry, SEEK_SET);
934 }
935
936 /**
937  * \ingroup gdcmHeader
938  * \brief   
939  *
940  * @return 
941  */
942 guint16 gdcmHeader::ReadInt16(void) {
943    guint16 g;
944    size_t item_read;
945    item_read = fread (&g, (size_t)2,(size_t)1, fp);
946    if ( item_read != 1 ) {
947       // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
948       // if(feof(fp)) 
949       //    dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
950       if(ferror(fp)) 
951          dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
952       errno = 1;
953       return 0;
954    }
955    errno = 0;
956    g = SwapShort(g);
957    return g;
958 }
959
960 /**
961  * \ingroup gdcmHeader
962  * \brief   
963  *
964  * @return 
965  */
966 guint32 gdcmHeader::ReadInt32(void) {
967    guint32 g;
968    size_t item_read;
969    item_read = fread (&g, (size_t)4,(size_t)1, fp);
970    if ( item_read != 1 ) { 
971       //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
972       //if(feof(fp)) 
973       //   dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
974      if(ferror(fp)) 
975          dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");   
976       errno = 1;
977       return 0;
978    }
979    errno = 0;   
980    g = SwapLong(g);
981    return g;
982 }
983
984 /**
985  * \ingroup gdcmHeader
986  * \brief   
987  *
988  * @return 
989  */
990  gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
991
992    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
993    if (!elValue) {
994       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
995                   "failed to Locate gdcmElValue");
996       return (gdcmElValue*)0;
997    }
998    return elValue;
999 }
1000
1001 /**
1002  * \ingroup gdcmHeader
1003  * \brief   Build a new Element Value from all the low level arguments. 
1004  *          Check for existence of dictionary entry, and build
1005  *          a default one when absent.
1006  * @param   Group group   of the underlying DictEntry
1007  * @param   Elem  element of the underlying DictEntry
1008  */
1009 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1010    // Find out if the tag we encountered is in the dictionaries:
1011    gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1012    if (!NewTag)
1013       NewTag = new gdcmDictEntry(Group, Elem);
1014
1015    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1016    if (!NewElVal) {
1017       dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1018                   "failed to allocate gdcmElValue");
1019       return (gdcmElValue*)0;
1020    }
1021    return NewElVal;
1022 }
1023
1024 /**
1025  * \ingroup gdcmHeader
1026  * \brief   TODO
1027  * @param   Value
1028  * @param   Group
1029  * @param   Elem
1030  */
1031 int gdcmHeader::ReplaceOrCreateByNumber(string Value, guint16 Group, guint16 Elem ) {
1032
1033         // TODO : FIXME JPRx
1034         // curieux, non ?
1035         // on (je) cree une Elvalue ne contenant pas de valeur
1036         // on l'ajoute au ElValSet
1037         // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1038         // --> devrait pouvoir etre fait + simplement ???
1039         
1040    gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1041    PubElValSet.Add(nvElValue);  
1042    PubElValSet.SetElValueByNumber(Value, Group, Elem);
1043    return(1);
1044 }   
1045
1046
1047 /**
1048  * \ingroup gdcmHeader
1049  * \brief   TODO
1050  * @param   Value
1051  * @param   Group
1052  * @param   Elem 
1053  */
1054 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1055
1056    gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1057    PubElValSet.Add(nvElValue);
1058    string v = Value;    
1059    PubElValSet.SetElValueByNumber(v, Group, Elem);
1060    return(1);
1061 }  
1062
1063 /**
1064  * \ingroup gdcmHeader
1065  * \brief   TODO
1066  * @param   Group
1067  * @param   Elem  
1068  */
1069  
1070 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1071    return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1072  }
1073  
1074  
1075 /**
1076  * \ingroup gdcmHeader
1077  * \brief   Build a new Element Value from all the low level arguments. 
1078  *          Check for existence of dictionary entry, and build
1079  *          a default one when absent.
1080  * @param   Name    Name of the underlying DictEntry
1081  */
1082 gdcmElValue* gdcmHeader::NewElValueByName(string Name) {
1083
1084    gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1085    if (!NewTag)
1086       NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1087
1088    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1089    if (!NewElVal) {
1090       dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1091                   "failed to allocate gdcmElValue");
1092       return (gdcmElValue*)0;
1093    }
1094    return NewElVal;
1095 }  
1096
1097 /**
1098  * \ingroup gdcmHeader
1099  * \brief   Read the next tag but WITHOUT loading it's value
1100  * @return  On succes the newly created ElValue, NULL on failure.      
1101  */
1102 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1103   
1104    guint16 g,n;
1105    gdcmElValue * NewElVal;
1106    
1107    g = ReadInt16();
1108    n = ReadInt16();
1109    
1110    if ( (g==0x7fe0) && (n==0x0010) ) 
1111         if (DEBUG) 
1112            printf("in gdcmHeader::ReadNextElement try to read 7fe0 0010 \n");
1113    
1114    if (errno == 1)
1115       // We reached the EOF (or an error occured) and header parsing
1116       // has to be considered as finished.
1117       return (gdcmElValue *)0;
1118    
1119    NewElVal = NewElValueByNumber(g, n);
1120    FindVR(NewElVal);
1121    FindLength(NewElVal);
1122    if (errno == 1) {
1123       // Call it quits
1124       if (DEBUG) printf("in gdcmHeader::ReadNextElement : g %04x n %04x errno %d\n",g, n, errno);
1125       return (gdcmElValue *)0;
1126    }
1127    NewElVal->SetOffset(ftell(fp));  
1128    if ( (g==0x7fe0) && (n==0x0010) ) 
1129       if (DEBUG) 
1130          printf("sortie de gdcmHeader::ReadNextElement 7fe0 0010 \n");
1131    return NewElVal;
1132 }
1133
1134 /**
1135  * \ingroup gdcmHeader
1136  * \brief   Apply some heuristics to predict wether the considered 
1137  *          element value contains/represents an integer or not.
1138  * @param   ElVal The element value on which to apply the predicate.
1139  * @return  The result of the heuristical predicate.
1140  */
1141 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1142    guint16 group   = ElVal->GetGroup();
1143    guint16 element = ElVal->GetElement();
1144    string  vr      = ElVal->GetVR();
1145    guint32 length  = ElVal->GetLength();
1146
1147    // When we have some semantics on the element we just read, and if we
1148    // a priori know we are dealing with an integer, then we shall be
1149    // able to swap it's element value properly.
1150    if ( element == 0 )  {  // This is the group length of the group
1151       if (length == 4)
1152          return true;
1153       else {
1154          if (DEBUG) printf("Erroneous Group Length element length (%04x , %04x) : %d\n",
1155             group, element,length);
1156                     
1157          dbg.Error("gdcmHeader::IsAnInteger",
1158             "Erroneous Group Length element length.");     
1159       }
1160    }
1161    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1162       return true;
1163    
1164    return false;
1165 }
1166
1167 /**
1168  * \ingroup gdcmHeader
1169  * \brief   Recover the offset (from the beginning of the file) of the pixels.
1170  */
1171 size_t gdcmHeader::GetPixelOffset(void) {
1172    // If this file complies with the norm we should encounter the
1173    // "Image Location" tag (0x0028,  0x0200). This tag contains the
1174    // the group that contains the pixel data (hence the "Pixel Data"
1175    // is found by indirection through the "Image Location").
1176    // Inside the group pointed by "Image Location" the searched element
1177    // is conventionally the element 0x0010 (when the norm is respected).
1178    // When the "Image Location" is absent we default to group 0x7fe0.
1179    guint16 grPixel;
1180    guint16 numPixel;
1181    string ImageLocation = GetPubElValByName("Image Location");
1182    if ( ImageLocation == "gdcm::Unfound" ) {
1183       grPixel = 0x7fe0;
1184    } else {
1185       grPixel = (guint16) atoi( ImageLocation.c_str() );
1186    }
1187    if (grPixel != 0x7fe0)
1188       // This is a kludge for old dirty Philips imager.
1189       numPixel = 0x1010;
1190    else
1191       numPixel = 0x0010;
1192          
1193    gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1194                                                               numPixel);
1195    if (PixelElement)
1196       return PixelElement->GetOffset();
1197    else
1198       return 0;
1199 }
1200
1201 /**
1202  * \ingroup gdcmHeader
1203  * \brief   Searches both the public and the shadow dictionary (when they
1204  *          exist) for the presence of the DictEntry with given
1205  *          group and element. The public dictionary has precedence on the
1206  *          shadow one.
1207  * @param   group   group of the searched DictEntry
1208  * @param   element element of the searched DictEntry
1209  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1210  */
1211 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1212                                                  guint16 element) {
1213    gdcmDictEntry * found = (gdcmDictEntry*)0;
1214    if (!RefPubDict && !RefShaDict) {
1215       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1216                      "we SHOULD have a default dictionary");
1217    }
1218    if (RefPubDict) {
1219       found = RefPubDict->GetTagByNumber(group, element);
1220       if (found)
1221          return found;
1222    }
1223    if (RefShaDict) {
1224       found = RefShaDict->GetTagByNumber(group, element);
1225       if (found)
1226          return found;
1227    }
1228    return found;
1229 }
1230
1231 /**
1232  * \ingroup gdcmHeader
1233  * \brief   Searches both the public and the shadow dictionary (when they
1234  *          exist) for the presence of the DictEntry with given name.
1235  *          The public dictionary has precedence on the shadow one.
1236  * @param   Name name of the searched DictEntry
1237  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1238  */
1239 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1240    gdcmDictEntry * found = (gdcmDictEntry*)0;
1241    if (!RefPubDict && !RefShaDict) {
1242       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1243                      "we SHOULD have a default dictionary");
1244    }
1245    if (RefPubDict) {
1246       found = RefPubDict->GetTagByName(Name);
1247       if (found)
1248          return found;
1249    }
1250    if (RefShaDict) {
1251       found = RefShaDict->GetTagByName(Name);
1252       if (found)
1253          return found;
1254    }
1255    return found;
1256 }
1257
1258 /**
1259  * \ingroup gdcmHeader
1260  * \brief   Searches within the public dictionary for element value of
1261  *          a given tag.
1262  * @param   group Group of the researched tag.
1263  * @param   element Element of the researched tag.
1264  * @return  Corresponding element value when it exists, and the string
1265  *          "gdcm::Unfound" otherwise.
1266  */
1267 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1268    return PubElValSet.GetElValueByNumber(group, element);
1269 }
1270
1271 /**
1272  * \ingroup gdcmHeader
1273  * \brief   Searches within the public dictionary for element value
1274  *          representation of a given tag.
1275  *
1276  *          Obtaining the VR (Value Representation) might be needed by caller
1277  *          to convert the string typed content to caller's native type 
1278  *          (think of C++ vs Python). The VR is actually of a higher level
1279  *          of semantics than just the native C++ type.
1280  * @param   group Group of the researched tag.
1281  * @param   element Element of the researched tag.
1282  * @return  Corresponding element value representation when it exists,
1283  *          and the string "gdcm::Unfound" otherwise.
1284  */
1285 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1286    gdcmElValue* elem =  PubElValSet.GetElementByNumber(group, element);
1287    if ( !elem )
1288       return "gdcm::Unfound";
1289    return elem->GetVR();
1290 }
1291
1292 /**
1293  * \ingroup gdcmHeader
1294  * \brief   Searches within the public dictionary for element value of
1295  *          a given tag.
1296  * @param   TagName name of the researched element.
1297  * @return  Corresponding element value when it exists, and the string
1298  *          "gdcm::Unfound" otherwise.
1299  */
1300 string gdcmHeader::GetPubElValByName(string TagName) {
1301    return PubElValSet.GetElValueByName(TagName);
1302 }
1303
1304 /**
1305  * \ingroup gdcmHeader
1306  * \brief   Searches within the elements parsed with the public dictionary for
1307  *          the element value representation of a given tag.
1308  *
1309  *          Obtaining the VR (Value Representation) might be needed by caller
1310  *          to convert the string typed content to caller's native type 
1311  *          (think of C++ vs Python). The VR is actually of a higher level
1312  *          of semantics than just the native C++ type.
1313  * @param   TagName name of the researched element.
1314  * @return  Corresponding element value representation when it exists,
1315  *          and the string "gdcm::Unfound" otherwise.
1316  */
1317 string gdcmHeader::GetPubElValRepByName(string TagName) {
1318    gdcmElValue* elem =  PubElValSet.GetElementByName(TagName);
1319    if ( !elem )
1320       return "gdcm::Unfound";
1321    return elem->GetVR();
1322 }
1323
1324 /**
1325  * \ingroup gdcmHeader
1326  * \brief   Searches within elements parsed with the SHADOW dictionary 
1327  *          for the element value of a given tag.
1328  * @param   group Group of the researched tag.
1329  * @param   element Element of the researched tag.
1330  * @return  Corresponding element value representation when it exists,
1331  *          and the string "gdcm::Unfound" otherwise.
1332  */
1333 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1334    return ShaElValSet.GetElValueByNumber(group, element);
1335 }
1336
1337 /**
1338  * \ingroup gdcmHeader
1339  * \brief   Searches within the elements parsed with the SHADOW dictionary
1340  *          for the element value representation of a given tag.
1341  *
1342  *          Obtaining the VR (Value Representation) might be needed by caller
1343  *          to convert the string typed content to caller's native type 
1344  *          (think of C++ vs Python). The VR is actually of a higher level
1345  *          of semantics than just the native C++ type.
1346  * @param   group Group of the researched tag.
1347  * @param   element Element of the researched tag.
1348  * @return  Corresponding element value representation when it exists,
1349  *          and the string "gdcm::Unfound" otherwise.
1350  */
1351 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1352    gdcmElValue* elem =  ShaElValSet.GetElementByNumber(group, element);
1353    if ( !elem )
1354       return "gdcm::Unfound";
1355    return elem->GetVR();
1356 }
1357
1358 /**
1359  * \ingroup gdcmHeader
1360  * \brief   Searches within the elements parsed with the shadow dictionary
1361  *          for an element value of given tag.
1362  * @param   TagName name of the researched element.
1363  * @return  Corresponding element value when it exists, and the string
1364  *          "gdcm::Unfound" otherwise.
1365  */
1366 string gdcmHeader::GetShaElValByName(string TagName) {
1367    return ShaElValSet.GetElValueByName(TagName);
1368 }
1369
1370 /**
1371  * \ingroup gdcmHeader
1372  * \brief   Searches within the elements parsed with the shadow dictionary for
1373  *          the element value representation of a given tag.
1374  *
1375  *          Obtaining the VR (Value Representation) might be needed by caller
1376  *          to convert the string typed content to caller's native type 
1377  *          (think of C++ vs Python). The VR is actually of a higher level
1378  *          of semantics than just the native C++ type.
1379  * @param   TagName name of the researched element.
1380  * @return  Corresponding element value representation when it exists,
1381  *          and the string "gdcm::Unfound" otherwise.
1382  */
1383 string gdcmHeader::GetShaElValRepByName(string TagName) {
1384    gdcmElValue* elem =  ShaElValSet.GetElementByName(TagName);
1385    if ( !elem )
1386       return "gdcm::Unfound";
1387    return elem->GetVR();
1388 }
1389
1390 /**
1391  * \ingroup gdcmHeader
1392  * \brief   Searches within elements parsed with the public dictionary 
1393  *          and then within the elements parsed with the shadow dictionary
1394  *          for the element value of a given tag.
1395  * @param   group Group of the researched tag.
1396  * @param   element Element of the researched tag.
1397  * @return  Corresponding element value representation when it exists,
1398  *          and the string "gdcm::Unfound" otherwise.
1399  */
1400 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1401    string pub = GetPubElValByNumber(group, element);
1402    if (pub.length())
1403       return pub;
1404    return GetShaElValByNumber(group, element);
1405 }
1406
1407 /**
1408  * \ingroup gdcmHeader
1409  * \brief   Searches within elements parsed with the public dictionary 
1410  *          and then within the elements parsed with the shadow dictionary
1411  *          for the element value representation of a given tag.
1412  *
1413  *          Obtaining the VR (Value Representation) might be needed by caller
1414  *          to convert the string typed content to caller's native type 
1415  *          (think of C++ vs Python). The VR is actually of a higher level
1416  *          of semantics than just the native C++ type.
1417  * @param   group Group of the researched tag.
1418  * @param   element Element of the researched tag.
1419  * @return  Corresponding element value representation when it exists,
1420  *          and the string "gdcm::Unfound" otherwise.
1421  */
1422 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1423    string pub = GetPubElValRepByNumber(group, element);
1424    if (pub.length())
1425       return pub;
1426    return GetShaElValRepByNumber(group, element);
1427 }
1428
1429 /**
1430  * \ingroup gdcmHeader
1431  * \brief   Searches within elements parsed with the public dictionary 
1432  *          and then within the elements parsed with the shadow dictionary
1433  *          for the element value of a given tag.
1434  * @param   TagName name of the researched element.
1435  * @return  Corresponding element value when it exists,
1436  *          and the string "gdcm::Unfound" otherwise.
1437  */
1438 string gdcmHeader::GetElValByName(string TagName) {
1439    string pub = GetPubElValByName(TagName);
1440    if (pub.length())
1441       return pub;
1442    return GetShaElValByName(TagName);
1443 }
1444
1445 /**
1446  * \ingroup gdcmHeader
1447  * \brief   Searches within elements parsed with the public dictionary 
1448  *          and then within the elements parsed with the shadow dictionary
1449  *          for the element value representation of a given tag.
1450  *
1451  *          Obtaining the VR (Value Representation) might be needed by caller
1452  *          to convert the string typed content to caller's native type 
1453  *          (think of C++ vs Python). The VR is actually of a higher level
1454  *          of semantics than just the native C++ type.
1455  * @param   TagName name of the researched element.
1456  * @return  Corresponding element value representation when it exists,
1457  *          and the string "gdcm::Unfound" otherwise.
1458  */
1459 string gdcmHeader::GetElValRepByName(string TagName) {
1460    string pub = GetPubElValRepByName(TagName);
1461    if (pub.length())
1462       return pub;
1463    return GetShaElValRepByName(TagName);
1464 }
1465
1466 /**
1467  * \ingroup gdcmHeader
1468  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1469  *          through it's (group, element) and modifies it's content with
1470  *          the given value.
1471  * @param   content new value to substitute with
1472  * @param   group   group of the ElVal to modify
1473  * @param   element element of the ElVal to modify
1474  */
1475 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1476                                     guint16 element)
1477                                     
1478 //TODO  : homogeneiser les noms : SetPubElValByNumber   qui appelle PubElValSet.SetElValueByNumber 
1479 //        pourquoi pas            SetPubElValueByNumber ??
1480 {
1481
1482    return (  PubElValSet.SetElValueByNumber (content, group, element) );
1483 }
1484
1485 /**
1486  * \ingroup gdcmHeader
1487  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1488  *          through tag name and modifies it's content with the given value.
1489  * @param   content new value to substitute with
1490  * @param   TagName name of the tag to be modified
1491  */
1492 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1493    return (  PubElValSet.SetElValueByName (content, TagName) );
1494 }
1495
1496 /**
1497  * \ingroup gdcmHeader
1498  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1499  *          through it's (group, element) and modifies it's length with
1500  *          the given value.
1501  * \warning Use with extreme caution.
1502  * @param   length new length to substitute with
1503  * @param   group   group of the ElVal to modify
1504  * @param   element element of the ElVal to modify
1505  * @return  1 on success, 0 otherwise.
1506  */
1507
1508 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1509                                     guint16 element) {
1510         return (  PubElValSet.SetElValueLengthByNumber (length, group, element) );
1511 }
1512
1513 /**
1514  * \ingroup gdcmHeader
1515  * \brief   Accesses an existing gdcmElValue in the ShaElValSet of this instance
1516  *          through it's (group, element) and modifies it's content with
1517  *          the given value.
1518  * @param   content new value to substitute with
1519  * @param   group   group of the ElVal to modify
1520  * @param   element element of the ElVal to modify
1521  * @return  1 on success, 0 otherwise.
1522  */
1523 int gdcmHeader::SetShaElValByNumber(string content,
1524                                     guint16 group, guint16 element) {
1525    return (  ShaElValSet.SetElValueByNumber (content, group, element) );
1526 }
1527
1528 /**
1529  * \ingroup gdcmHeader
1530  * \brief   Accesses an existing gdcmElValue in the ShaElValSet of this instance
1531  *          through tag name and modifies it's content with the given value.
1532  * @param   content new value to substitute with
1533  * @param   ShadowTagName name of the tag to be modified
1534  */
1535 int gdcmHeader::SetShaElValByName(string content, string ShadowTagName) {
1536    return (  ShaElValSet.SetElValueByName (content, ShadowTagName) );
1537 }
1538
1539 /**
1540  * \ingroup gdcmHeader
1541  * \brief   Parses the header of the file but WITHOUT loading element values.
1542  */
1543 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1544    gdcmElValue * newElValue = (gdcmElValue *)0;
1545    
1546    rewind(fp);
1547    CheckSwap();
1548    while ( (newElValue = ReadNextElement()) ) {
1549       SkipElementValue(newElValue);
1550       PubElValSet.Add(newElValue);
1551    }
1552 }
1553
1554
1555 //
1556 // TODO : JPR
1557 // des que les element values sont chargees, stocker, 
1558 // en une seule fois, dans des entiers 
1559 // NX, NY, NZ, Bits allocated, Bits Stored, High Bit, Samples Per Pixel
1560 // (TODO : preciser les autres)
1561 // et refaire ceux des accesseurs qui renvoient les entiers correspondants
1562 //
1563 // --> peut etre dangereux ?
1564 // si l'utilisateur modifie 'manuellement' l'un des paramètres
1565 // l'entier de sera pas modifié ...
1566 // (pb de la mise Ã  jour en cas de redondance :-(
1567
1568 /**
1569  * \ingroup gdcmHeader
1570  * \brief   Retrieve the number of columns of image.
1571  * @return  The encountered size when found, 0 by default.
1572  */
1573 int gdcmHeader::GetXSize(void) {
1574    // We cannot check for "Columns" because the "Columns" tag is present
1575    // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1576    string StrSize = GetPubElValByNumber(0x0028,0x0011);
1577    if (StrSize == "gdcm::Unfound")
1578       return 0;
1579    return atoi(StrSize.c_str());
1580 }
1581
1582 /**
1583  * \ingroup gdcmHeader
1584  * \brief   Retrieve the number of lines of image.
1585  * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1586  * @return  The encountered size when found, 1 by default.
1587  */
1588 int gdcmHeader::GetYSize(void) {
1589    // We cannot check for "Rows" because the "Rows" tag is present
1590    // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1591    string StrSize = GetPubElValByNumber(0x0028,0x0010);
1592    if (StrSize != "gdcm::Unfound")
1593       return atoi(StrSize.c_str());
1594    if ( IsDicomV3() )
1595       return 0;
1596    else
1597       // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1598       // hence be a signal (1d image). So we default to 1:
1599       return 1;
1600 }
1601
1602 /**
1603  * \ingroup gdcmHeader
1604  * \brief   Retrieve the number of planes of volume or the number
1605  *          of frames of a multiframe.
1606  * \warning When present we consider the "Number of Frames" as the third
1607  *          dimension. When absent we consider the third dimension as
1608  *          being the "Planes" tag content.
1609  * @return  The encountered size when found, 1 by default.
1610  */
1611 int gdcmHeader::GetZSize(void) {
1612    // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1613    // as the third dimension.
1614    string StrSize = GetPubElValByNumber(0x0028,0x0008);
1615    if (StrSize != "gdcm::Unfound")
1616       return atoi(StrSize.c_str());
1617
1618    // We then consider the "Planes" entry as the third dimension [we
1619    // cannot retrieve by name since "Planes tag is present both in
1620    // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary]. 
1621    StrSize = GetPubElValByNumber(0x0028,0x0012);
1622    if (StrSize != "gdcm::Unfound")
1623       return atoi(StrSize.c_str());
1624    return 1;
1625 }
1626
1627 /**
1628  * \ingroup gdcmHeader
1629  * \brief   Retrieve the number of Bits Stored
1630  *          (as opposite to number of Bits Allocated)
1631  * 
1632  * @return  The encountered number of Bits Stored, 0 by default.
1633  */
1634 int gdcmHeader::GetBitsStored(void) { 
1635    string StrSize = GetPubElValByNumber(0x0028,0x0101);
1636    if (StrSize == "gdcm::Unfound")
1637       return 1;
1638    return atoi(StrSize.c_str());
1639 }
1640
1641
1642 /**
1643  * \ingroup gdcmHeader
1644  * \brief   Retrieve the number of Samples Per Pixel
1645  *          (1 : gray level, 3 : RGB)
1646  * 
1647  * @return  The encountered number of Samples Per Pixel, 1 by default.
1648  */
1649 int gdcmHeader::GetSamplesPerPixel(void) { 
1650    string StrSize = GetPubElValByNumber(0x0028,0x0002);
1651    if (StrSize == "gdcm::Unfound")
1652       return 1; // Well, it's supposed to be mandatory ...
1653    return atoi(StrSize.c_str());
1654 }
1655
1656
1657 /* ================ COMMENT OUT after unfreeze
1658 **
1659  * \ingroup gdcmHeader
1660  * \brief   Retrieve the Planar Configuration for RGB images
1661  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1662  * 
1663  * @return  The encountered Planar Configuration, 0 by default.
1664  *
1665 int gdcmHeader::GetPlanarConfiguration(void) { 
1666    string StrSize = GetPubElValByNumber(0x0028,0x0006);
1667    if (StrSize == "gdcm::Unfound")
1668       return 0;
1669    return atoi(StrSize.c_str());
1670 }
1671
1672  ======================================= */
1673
1674 /**
1675  * \ingroup gdcmHeader
1676  * \brief   Return the size (in bytes) of a single pixel of data.
1677  * @return  The size in bytes of a single pixel of data.
1678  *
1679  */
1680 int gdcmHeader::GetPixelSize(void) {
1681    string PixelType = GetPixelType();
1682    if (PixelType == "8U"  || PixelType == "8S")
1683       return 1;
1684    if (PixelType == "16U" || PixelType == "16S")
1685       return 2;
1686    if (PixelType == "32U" || PixelType == "32S")
1687       return 4;
1688    dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1689    return 0;
1690 }
1691
1692 /**
1693  * \ingroup gdcmHeader
1694  * \brief   Build the Pixel Type of the image.
1695  *          Possible values are:
1696  *          - 8U  unsigned  8 bit,
1697  *          - 8S    signed  8 bit,
1698  *          - 16U unsigned 16 bit,
1699  *          - 16S   signed 16 bit,
1700  *          - 32U unsigned 32 bit,
1701  *          - 32S   signed 32 bit,
1702  * \warning 12 bit images appear as 16 bit.
1703  * @return  
1704  */
1705 string gdcmHeader::GetPixelType(void) {
1706    string BitsAlloc;
1707    BitsAlloc = GetElValByName("Bits Allocated");
1708    if (BitsAlloc == "gdcm::Unfound") {
1709       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1710       BitsAlloc = string("16");
1711    }
1712    if (BitsAlloc == "12")
1713       BitsAlloc = string("16");
1714
1715    string Signed;
1716    Signed = GetElValByName("Pixel Representation");
1717    if (Signed == "gdcm::Unfound") {
1718       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1719       BitsAlloc = string("0");
1720    }
1721    if (Signed == "0")
1722       Signed = string("U");
1723    else
1724       Signed = string("S");
1725
1726    return( BitsAlloc + Signed);
1727 }
1728
1729
1730 /**
1731  * \ingroup gdcmHeader
1732  * \brief  This predicate, based on hopefully reasonnable heuristics,
1733  *         decides whether or not the current gdcmHeader was properly parsed
1734  *         and contains the mandatory information for being considered as
1735  *         a well formed and usable image.
1736  * @return true when gdcmHeader is the one of a reasonable Dicom file,
1737  *         false otherwise. 
1738  */
1739 bool gdcmHeader::IsReadable(void) {
1740    if (   GetElValByName("Image Dimensions") != "gdcm::Unfound"
1741       && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1742       return false;
1743    }
1744    if ( GetElValByName("Bits Allocated")       == "gdcm::Unfound" )
1745       return false;
1746    if ( GetElValByName("Bits Stored")          == "gdcm::Unfound" )
1747       return false;
1748    if ( GetElValByName("High Bit")             == "gdcm::Unfound" )
1749       return false;
1750    if ( GetElValByName("Pixel Representation") == "gdcm::Unfound" )
1751       return false;
1752    return true;
1753 }
1754
1755 /**
1756  * \ingroup gdcmHeader
1757  * \brief   Small utility function that creates a new manually crafted
1758  *          (as opposed as read from the file) gdcmElValue with user
1759  *          specified name and adds it to the public tag hash table.
1760  * \note    A fake TagKey is generated so the PubDict can keep it's coherence.
1761  * @param   NewTagName The name to be given to this new tag.
1762  * @param   VR The Value Representation to be given to this new tag.
1763  * @ return The newly hand crafted Element Value.
1764  */
1765 gdcmElValue* gdcmHeader::NewManualElValToPubDict(string NewTagName, string VR) {
1766    gdcmElValue* NewElVal = (gdcmElValue*)0;
1767    guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
1768    guint32 FreeElem = 0;
1769    gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1770
1771    FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1772    if (FreeElem == UINT32_MAX) {
1773       dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1774                      "Group 0xffff in Public Dict is full");
1775       return (gdcmElValue*)0;
1776    }
1777    NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1778                                 VR, "GDCM", NewTagName);
1779    NewElVal = new gdcmElValue(NewEntry);
1780    PubElValSet.Add(NewElVal);
1781    return NewElVal;
1782 }
1783
1784 /**
1785  * \ingroup gdcmHeader
1786  * \brief   Loads the element values of all the elements present in the
1787  *          public tag based hash table.
1788  */
1789 void gdcmHeader::LoadElements(void) {
1790    rewind(fp);   
1791    TagElValueHT ht = PubElValSet.GetTagHt();
1792    for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1793       LoadElementValue(tag->second);
1794    }
1795 }
1796
1797 /**
1798   * \ingroup gdcmHeader
1799   * \brief
1800   * @return
1801   */ 
1802 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1803    PubElValSet.Print(os);
1804 }
1805
1806 /**
1807   * \ingroup gdcmHeader
1808   * \brief
1809   * @return
1810   */  
1811 void gdcmHeader::PrintPubDict(std::ostream & os) {
1812    RefPubDict->Print(os);
1813 }
1814
1815 /**
1816   * \ingroup gdcmHeader
1817   * \brief
1818   * @return
1819   */ 
1820 int gdcmHeader::Write(FILE * fp, FileType type) {
1821    return PubElValSet.Write(fp, type);
1822 }
1823
1824 /**
1825   * \ingroup gdcmHeader
1826   * \brief gets the info from 0028,0030 : Pixel Spacing
1827   * \           else 1.
1828   * @return X dimension of a pixel
1829   */
1830 float gdcmHeader::GetXSpacing(void) {
1831     float xspacing, yspacing;
1832     string StrSpacing = GetPubElValByNumber(0x0028,0x0030);
1833
1834     if (StrSpacing == "gdcm::Unfound") {
1835        dbg.Verbose(0, "gdcmHeader::GetXSpacing: unfound Pixel Spacing (0028,0030)");
1836        return 1.;
1837      }
1838    if( sscanf( StrSpacing.c_str(), "%f\\%f", &xspacing, &yspacing) != 2)
1839      return 0.;
1840    //else
1841    return xspacing;
1842 }
1843
1844 /**
1845   * \ingroup gdcmHeader
1846   * \brief gets the info from 0028,0030 : Pixel Spacing
1847   * \           else 1.
1848   * @return Y dimension of a pixel
1849   */
1850 float gdcmHeader::GetYSpacing(void) {
1851    float xspacing, yspacing;
1852    string StrSpacing = GetPubElValByNumber(0x0028,0x0030);
1853   
1854    if (StrSpacing == "gdcm::Unfound") {
1855       dbg.Verbose(0, "gdcmHeader::GetYSpacing: unfound Pixel Spacing (0028,0030)");
1856       return 1.;
1857     }
1858   if( sscanf( StrSpacing.c_str(), "%f\\%f", &xspacing, &yspacing) != 2)
1859     return 0.;
1860   if (yspacing == 0.) {
1861     dbg.Verbose(0, "gdcmHeader::GetYSpacing: gdcmData/CT-MONO2-8-abdo.dcm problem");
1862     // seems to be a bug in the header ...
1863     sscanf( StrSpacing.c_str(), "%f\\0\\%f", &xspacing, &yspacing);
1864   }
1865   return yspacing;
1866
1867
1868
1869 /**
1870   *\ingroup gdcmHeader
1871   *\brief gets the info from 0018,0088 : Space Between Slices
1872   *\               else from 0018,0050 : Slice Thickness
1873   *\               else 1.
1874   * @return Z dimension of a voxel-to be
1875   */
1876 float gdcmHeader::GetZSpacing(void) {
1877    // TODO : translate into English
1878    // Spacing Between Slices : distance entre le milieu de chaque coupe
1879    // Les coupes peuvent etre :
1880    //   jointives     (Spacing between Slices = Slice Thickness)
1881    //   chevauchantes (Spacing between Slices < Slice Thickness)
1882    //   disjointes    (Spacing between Slices > Slice Thickness)
1883    // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
1884    //   ca interesse le physicien de l'IRM, pas le visualisateur de volumes ...
1885    //   Si le Spacing Between Slices est absent, 
1886    //   on suppose que les coupes sont jointives
1887    
1888    string StrSpacingBSlices = GetPubElValByNumber(0x0018,0x0088);
1889
1890    if (StrSpacingBSlices == "gdcm::Unfound") {
1891       dbg.Verbose(0, "gdcmHeader::GetZSpacing: unfound StrSpacingBSlices");
1892       string StrSliceThickness = GetPubElValByNumber(0x0018,0x0050);       
1893       if (StrSliceThickness == "gdcm::Unfound")
1894          return 1.;
1895       else
1896          // if no 'Spacing Between Slices' is found, 
1897          // we assume slices join together
1898          // (no overlapping, no interslice gap)
1899          // if they don't, we're fucked up
1900          return atof(StrSliceThickness.c_str());  
1901    } else {
1902       return atof(StrSpacingBSlices.c_str());
1903    }
1904 }
1905
1906 //
1907 // Image Position Patient                              (0020,0032):
1908 // If not found (ACR_NEMA) we try Image Position       (0020,0030)
1909 // If not found (ACR-NEMA), we consider Slice Location (0020,1041)
1910 //                                   or Location       (0020,0050) 
1911 // as the Z coordinate, 
1912 // 0. for all the coordinates if nothing is found
1913 // TODO : find a way to inform the caller nothing was found
1914 // TODO : How to tell the caller a wrong number of values was found?
1915
1916
1917 /**
1918   * \ingroup gdcmHeader
1919   * \brief gets the info from 0020,0032 : Image Position Patient
1920   *\                else from 0020,0030 : Image Position (RET)
1921   *\                else 0.
1922   * @return up-left image corner position
1923   */
1924 float gdcmHeader::GetXImagePosition(void) {
1925     float xImPos, yImPos, zImPos;  
1926     string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1927
1928     if (StrImPos == "gdcm::Unfound") {
1929        dbg.Verbose(0, "gdcmHeader::GetXImagePosition: unfound Image Position Patient (0020,0032)");
1930        StrImPos = GetPubElValByNumber(0x0020,0x0030); // For ACR-NEMA images
1931        if (StrImPos == "gdcm::Unfound") {
1932           dbg.Verbose(0, "gdcmHeader::GetXImagePosition: unfound Image Position (RET) (0020,0030)");
1933           // How to tell the caller nothing was found ?
1934        }  
1935        return 0.;
1936      }
1937    if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3)
1938      return 0.;
1939    return xImPos;
1940 }
1941
1942 /**
1943   * \ingroup gdcmHeader
1944   * \brief gets the info from 0020,0032 : Image Position Patient
1945   * \               else from 0020,0030 : Image Position (RET)
1946   * \               else 0.
1947   * @return up-left image corner position
1948   */
1949 float gdcmHeader::GetYImagePosition(void) {
1950     float xImPos, yImPos, zImPos;
1951     string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1952
1953     if (StrImPos == "gdcm::Unfound") {
1954        dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Image Position Patient (0020,0032)");
1955        StrImPos = GetPubElValByNumber(0x0020,0x0030); // For ACR-NEMA images
1956        if (StrImPos == "gdcm::Unfound") {
1957           dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Image Position (RET) (0020,0030)");
1958        }  
1959        return 0.;
1960      }
1961    if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3)
1962      return 0.;
1963    return yImPos;
1964 }
1965
1966 /**
1967   * \ingroup gdcmHeader
1968   * \brief gets the info from 0020,0032 : Image Position Patient
1969   * \               else from 0020,0030 : Image Position (RET)
1970   * \               else from 0020,1041 : Slice Location
1971   * \               else from 0020,0050 : Location
1972   * \               else 0.
1973   * @return up-left image corner position
1974   */
1975 float gdcmHeader::GetZImagePosition(void) {
1976    float xImPos, yImPos, zImPos; 
1977    string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1978    if (StrImPos != "gdcm::Unfound") {
1979       if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3) {
1980          dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Image Position Patient (0020,0032)");
1981          return 0.;  // bug in the element 0x0020,0x0032
1982       } else {
1983          return zImPos;
1984       }    
1985    }  
1986    StrImPos = GetPubElValByNumber(0x0020,0x0030); // For ACR-NEMA images
1987    if (StrImPos != "gdcm::Unfound") {
1988       if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3) {
1989          dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Image Position (RET) (0020,0030)");
1990          return 0.;  // bug in the element 0x0020,0x0032
1991       } else {
1992          return zImPos;
1993       }    
1994    }                
1995    string StrSliceLocation = GetPubElValByNumber(0x0020,0x1041);// for *very* old ACR-NEMA images
1996    if (StrSliceLocation != "gdcm::Unfound") {
1997       if( sscanf( StrSliceLocation.c_str(), "%f", &zImPos) !=1) {
1998          dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Slice Location (0020,1041)");
1999          return 0.;  // bug in the element 0x0020,0x1041
2000       } else {
2001          return zImPos;
2002       }
2003    }   
2004    dbg.Verbose(0, "gdcmHeader::GetZImagePosition: unfound Slice Location (0020,1041)");
2005    string StrLocation = GetPubElValByNumber(0x0020,0x0050);
2006    if (StrLocation != "gdcm::Unfound") {
2007       if( sscanf( StrLocation.c_str(), "%f", &zImPos) !=1) {
2008          dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Location (0020,0050)");
2009          return 0.;  // bug in the element 0x0020,0x0050
2010       } else {
2011          return zImPos;
2012       }
2013    }
2014    dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Location (0020,0050)");  
2015    return 0.; // Hopeless
2016 }
2017
2018
2019