]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
Correction calcul 'gdcmZSize' dans AddAndDefaultElements.
[gdcm.git] / src / gdcmHeader.cxx
1 // gdcmHeader.cxx
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
16 #include "iddcmjpeg.h"
17
18 // Refer to gdcmHeader::CheckSwap()
19 #define HEADER_LENGTH_TO_READ       256
20 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
21 #define _MaxSizeLoadElementValue_   1024
22
23 VRHT * gdcmHeader::dicom_vr = (VRHT*)0;
24
25 void gdcmHeader::Initialise(void) {
26    if (!gdcmHeader::dicom_vr)
27       InitVRDict();
28    Dicts = new gdcmDictSet();
29    RefPubDict = Dicts->GetDefaultPubDict();
30    RefShaDict = (gdcmDict*)0;
31 }
32
33 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error) 
34   throw(gdcmFileError) {
35   SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
36   filename = InFilename;
37   Initialise();
38   fp=fopen(InFilename,"rb");
39   if(exception_on_error) {
40     if(!fp)
41       throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
42   }
43   else
44     dbg.Error(!fp, "gdcmHeader::gdcmHeader cannot open file", InFilename);
45   ParseHeader();
46   LoadElements();
47   AddAndDefaultElements();
48 }
49
50
51 gdcmHeader::~gdcmHeader (void) {
52    //FIXME obviously there is much to be done here !
53    fclose(fp);
54    return;
55 }
56
57 void gdcmHeader::InitVRDict (void) {
58    if (dicom_vr) {
59       dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
60       return;
61    }
62    VRHT *vr = new VRHT;
63    (*vr)["AE"] = "Application Entity";       // At most 16 bytes
64    (*vr)["AS"] = "Age String";               // Exactly 4 bytes
65    (*vr)["AT"] = "Attribute Tag";            // 2 16-bit unsigned short integers
66    (*vr)["CS"] = "Code String";              // At most 16 bytes
67    (*vr)["DA"] = "Date";                     // Exactly 8 bytes
68    (*vr)["DS"] = "Decimal String";           // At most 16 bytes
69    (*vr)["DT"] = "Date Time";                // At most 26 bytes
70    (*vr)["FL"] = "Floating Point Single";    // 32-bit IEEE 754:1985 float
71    (*vr)["FD"] = "Floating Point Double";    // 64-bit IEEE 754:1985 double
72    (*vr)["IS"] = "Integer String";           // At most 12 bytes
73    (*vr)["LO"] = "Long String";              // At most 64 chars
74    (*vr)["LT"] = "Long Text";                // At most 10240 chars
75    (*vr)["OB"] = "Other Byte String";        // String of bytes (vr independant)
76    (*vr)["OW"] = "Other Word String";        // String of 16-bit words (vr dep)
77    (*vr)["PN"] = "Person Name";              // At most 64 chars
78    (*vr)["SH"] = "Short String";             // At most 16 chars
79    (*vr)["SL"] = "Signed Long";              // Exactly 4 bytes
80    (*vr)["SQ"] = "Sequence of Items";        // Not Applicable
81    (*vr)["SS"] = "Signed Short";             // Exactly 2 bytes
82    (*vr)["ST"] = "Short Text";               // At most 1024 chars
83    (*vr)["TM"] = "Time";                     // At most 16 bytes
84    (*vr)["UI"] = "Unique Identifier";        // At most 64 bytes
85    (*vr)["UL"] = "Unsigned Long ";           // Exactly 4 bytes
86    (*vr)["UN"] = "Unknown";                  // Any length of bytes
87    (*vr)["US"] = "Unsigned Short ";          // Exactly 2 bytes
88    (*vr)["UT"] = "Unlimited Text";           // At most 2^32 -1 chars
89    dicom_vr = vr; 
90 }
91
92 /**
93  * \ingroup gdcmHeader
94  * \brief   Discover what the swap code is (among little endian, big endian,
95  *          bad little endian, bad big endian).
96  *
97  */
98 void gdcmHeader::CheckSwap()
99 {
100    // The only guaranted way of finding the swap code is to find a
101    // group tag since we know it's length has to be of four bytes i.e.
102    // 0x00000004. Finding the swap code in then straigthforward. Trouble
103    // occurs when we can't find such group...
104    guint32  s;
105    guint32  x=4;  // x : pour ntohs
106    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
107     
108    int lgrLue;
109    char * entCur;
110    char deb[HEADER_LENGTH_TO_READ];
111     
112    // First, compare HostByteOrder and NetworkByteOrder in order to
113    // determine if we shall need to swap bytes (i.e. the Endian type).
114    if (x==ntohs(x))
115       net2host = true;
116    else
117       net2host = false;
118    
119    // The easiest case is the one of a DICOM header, since it possesses a
120    // file preamble where it suffice to look for the string "DICM".
121    lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
122    
123    entCur = deb + 128;
124    if(memcmp(entCur, "DICM", (size_t)4) == 0) {
125       filetype = TrueDicom;
126       dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
127    } else {
128       filetype = Unknown;
129       dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
130    }
131
132    if(filetype == TrueDicom) {
133       // Next, determine the value representation (VR). Let's skip to the
134       // first element (0002, 0000) and check there if we find "UL" 
135       // - or "OB" if the 1st one is (0002,0001) -,
136       // in which case we (almost) know it is explicit VR.
137       // WARNING: if it happens to be implicit VR then what we will read
138       // is the length of the group. If this ascii representation of this
139       // length happens to be "UL" then we shall believe it is explicit VR.
140       // FIXME: in order to fix the above warning, we could read the next
141       // element value (or a couple of elements values) in order to make
142       // sure we are not commiting a big mistake.
143       // We need to skip :
144       // * the 128 bytes of File Preamble (often padded with zeroes),
145       // * the 4 bytes of "DICM" string,
146       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
147       // i.e. a total of  136 bytes.
148       entCur = deb + 136;
149       if(  (memcmp(entCur, "UL", (size_t)2) == 0) ||
150            (memcmp(entCur, "OB", (size_t)2) == 0) )
151         {
152          filetype = ExplicitVR;
153          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
154                      "explicit Value Representation");
155       } else {
156          filetype = ImplicitVR;
157          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
158                      "not an explicit Value Representation");
159       }
160
161       if (net2host) {
162          sw = 4321;
163          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
164                         "HostByteOrder != NetworkByteOrder");
165       } else {
166          sw = 0;
167          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
168                         "HostByteOrder = NetworkByteOrder");
169       }
170       
171       // Position the file position indicator at first tag (i.e.
172       // after the file preamble and the "DICM" string).
173       rewind(fp);
174       fseek (fp, 132L, SEEK_SET);
175       return;
176    } // End of TrueDicom
177
178    // Alas, this is not a DicomV3 file and whatever happens there is no file
179    // preamble. We can reset the file position indicator to where the data
180    // is (i.e. the beginning of the file).
181    rewind(fp);
182
183    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
184    // By clean we mean that the length of the first tag is written down.
185    // If this is the case and since the length of the first group HAS to be
186    // four (bytes), then determining the proper swap code is straightforward.
187
188    entCur = deb + 4;
189    // We assume the array of char we are considering contains the binary
190    // representation of a 32 bits integer. Hence the following dirty
191    // trick :
192    s = *((guint32 *)(entCur));
193    
194    switch (s) {
195    case 0x00040000 :
196       sw = 3412;
197       filetype = ACR;
198       return;
199    case 0x04000000 :
200       sw = 4321;
201       filetype = ACR;
202       return;
203    case 0x00000400 :
204       sw = 2143;
205       filetype = ACR;
206       return;
207    case 0x00000004 :
208       sw = 0;
209       filetype = ACR;
210       return;
211    default :
212       dbg.Verbose(0, "gdcmHeader::CheckSwap:",
213                      "ACR/NEMA unfound swap info (time to raise bets)");
214    }
215
216    // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
217    // It is time for despaired wild guesses. So, let's assume this file
218    // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
219    // not present. Then the only info we have is the net2host one.
220    if (! net2host )
221       sw = 0;
222    else
223       sw = 4321;
224    return;
225 }
226
227 void gdcmHeader::SwitchSwapToBigEndian(void) {
228    dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
229                   "Switching to BigEndian mode.");
230    if ( sw == 0    ) {
231       sw = 4321;
232       return;
233    }
234    if ( sw == 4321 ) {
235       sw = 0;
236       return;
237    }
238    if ( sw == 3412 ) {
239       sw = 2143;
240       return;
241    }
242    if ( sw == 2143 )
243       sw = 3412;
244 }
245
246 void gdcmHeader::GetPixels(size_t lgrTotale, void* _Pixels) {
247    size_t pixelsOffset; 
248    pixelsOffset = GetPixelOffset();
249    fseek(fp, pixelsOffset, SEEK_SET);
250    if (IsJPEGLossless()) {
251         _Pixels=_IdDcmJpegRead(fp);  
252    } else {
253         fread(_Pixels, 1, lgrTotale, fp);
254    }
255 }
256
257
258
259 /**
260  * \ingroup   gdcmHeader
261  * \brief     Find the value representation of the current tag.
262  */
263 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
264    if (filetype != ExplicitVR)
265       return;
266
267    char VR[3];
268    string vr;
269    int lgrLue;
270    long PositionOnEntry = ftell(fp);
271    // Warning: we believe this is explicit VR (Value Representation) because
272    // we used a heuristic that found "UL" in the first tag. Alas this
273    // doesn't guarantee that all the tags will be in explicit VR. In some
274    // cases (see e-film filtered files) one finds implicit VR tags mixed
275    // within an explicit VR file. Hence we make sure the present tag
276    // is in explicit VR and try to fix things if it happens not to be
277    // the case.
278    bool RealExplicit = true;
279    
280    lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
281    VR[2]=0;
282    vr = string(VR);
283       
284    // Assume we are reading a falsely explicit VR file i.e. we reached
285    // a tag where we expect reading a VR but are in fact we read the
286    // first to bytes of the length. Then we will interogate (through find)
287    // the dicom_vr dictionary with oddities like "\004\0" which crashes
288    // both GCC and VC++ implementations of the STL map. Hence when the
289    // expected VR read happens to be non-ascii characters we consider
290    // we hit falsely explicit VR tag.
291
292    if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
293       RealExplicit = false;
294
295    // CLEANME searching the dicom_vr at each occurence is expensive.
296    // PostPone this test in an optional integrity check at the end
297    // of parsing or only in debug mode.
298    if ( RealExplicit && !dicom_vr->count(vr) )
299       RealExplicit= false;
300
301    if ( RealExplicit ) {
302       if ( ElVal->IsVrUnknown() ) {
303          // When not a dictionary entry, we can safely overwrite the vr.
304          ElVal->SetVR(vr);
305          return; 
306       }
307       if ( ElVal->GetVR() == vr ) {
308          // The vr we just read and the dictionary agree. Nothing to do.
309          return;
310       }
311       // The vr present in the file and the dictionary disagree. We assume
312       // the file writer knew best and use the vr of the file. Since it would
313       // be unwise to overwrite the vr of a dictionary (since it would
314       // compromise it's next user), we need to clone the actual DictEntry
315       // and change the vr for the read one.
316       gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
317                                  ElVal->GetElement(),
318                                  vr,
319                                  "FIXME",
320                                  ElVal->GetName());
321       ElVal->SetDictEntry(NewTag);
322       return; 
323    }
324    
325    // We thought this was explicit VR, but we end up with an
326    // implicit VR tag. Let's backtrack.
327    dbg.Verbose(1, "gdcmHeader::FindVR:", "Falsely explicit vr file");
328    fseek(fp, PositionOnEntry, SEEK_SET);
329    // When this element is known in the dictionary we shall use, e.g. for
330    // the semantics (see  the usage of IsAnInteger), the vr proposed by the
331    // dictionary entry. Still we have to flag the element as implicit since
332    // we know now our assumption on expliciteness is not furfilled.
333    // avoid  .
334    if ( ElVal->IsVrUnknown() )
335       ElVal->SetVR("Implicit");
336    ElVal->SetImplicitVr();
337 }
338
339 /**
340  * \ingroup gdcmHeader
341  * \brief   Determines if the Transfer Syntax was allready encountered
342  *          and if it corresponds to a ImplicitVRLittleEndian one.
343  *
344  * @return  True when ImplicitVRLittleEndian found. False in all other cases.
345  */
346 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
347    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
348    if ( !Element )
349       return false;
350    LoadElementValueSafe(Element);
351    string Transfer = Element->GetValue();
352    if ( Transfer == "1.2.840.10008.1.2" )
353       return true;
354    return false;
355 }
356
357 /**
358  * \ingroup gdcmHeader
359  * \brief   Determines if the Transfer Syntax was allready encountered
360  *          and if it corresponds to a ExplicitVRLittleEndian one.
361  *
362  * @return  True when ExplicitVRLittleEndian found. False in all other cases.
363  */
364 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
365    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
366    if ( !Element )
367       return false;
368    LoadElementValueSafe(Element);
369    string Transfer = Element->GetValue();
370    if ( Transfer == "1.2.840.10008.1.2.1" )
371       return true;
372    return false;
373 }
374
375 /**
376  * \ingroup gdcmHeader
377  * \brief   Determines if the Transfer Syntax was allready encountered
378  *          and if it corresponds to a DeflatedExplicitVRLittleEndian one.
379  *
380  * @return  True when DeflatedExplicitVRLittleEndian found. False in all other cases.
381  */
382 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
383    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
384    if ( !Element )
385       return false;
386    LoadElementValueSafe(Element);
387    string Transfer = Element->GetValue();
388    if ( Transfer == "1.2.840.10008.1.2.1.99" )
389       return true;
390    return false;
391 }
392
393 /**
394  * \ingroup gdcmHeader
395  * \brief   Determines if the Transfer Syntax was allready encountered
396  *          and if it corresponds to a Explicit VR Big Endian one.
397  *
398  * @return  True when big endian found. False in all other cases.
399  */
400 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
401    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
402    if ( !Element )
403       return false;
404    LoadElementValueSafe(Element);
405    string Transfer = Element->GetValue();
406    if ( Transfer == "1.2.840.10008.1.2.2" )  //1.2.2 ??? A verifier !
407       return true;
408    return false;
409 }
410
411 /**
412  * \ingroup gdcmHeader
413  * \brief   Determines if the Transfer Syntax was allready encountered
414  *          and if it corresponds to a JPEGBaseLineProcess1 one.
415  *
416  * @return  True when JPEGBaseLineProcess1found. False in all other cases.
417  */
418 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
419    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
420    if ( !Element )
421       return false;
422    LoadElementValueSafe(Element);
423    string Transfer = Element->GetValue();
424    if ( Transfer == "1.2.840.10008.1.2.4.50" )
425       return true;
426    return false;
427 }
428
429 // faire qq chose d'intelligent a la place de Ã§a
430
431 bool gdcmHeader::IsJPEGLossless(void) {
432    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
433    if ( !Element )
434       return false;
435    LoadElementValueSafe(Element);
436    const char * Transfert = Element->GetValue().c_str();
437    if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
438    if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
439    return false;
440 }
441
442
443 /**
444  * \ingroup gdcmHeader
445  * \brief   Determines if the Transfer Syntax was allready encountered
446  *          and if it corresponds to a JPEGExtendedProcess2-4 one.
447  *
448  * @return  True when JPEGExtendedProcess2-4 found. False in all other cases.
449  */
450 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
451    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
452    if ( !Element )
453       return false;
454    LoadElementValueSafe(Element);
455    string Transfer = Element->GetValue();
456    if ( Transfer == "1.2.840.10008.1.2.4.51" )
457       return true;
458    return false;
459 }
460
461 /**
462  * \ingroup gdcmHeader
463  * \brief   Determines if the Transfer Syntax was allready encountered
464  *          and if it corresponds to a JPEGExtendeProcess3-5 one.
465  *
466  * @return  True when JPEGExtendedProcess3-5 found. False in all other cases.
467  */
468 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
469    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
470    if ( !Element )
471       return false;
472    LoadElementValueSafe(Element);
473    string Transfer = Element->GetValue();
474    if ( Transfer == "1.2.840.10008.1.2.4.52" )
475       return true;
476    return false;
477 }
478
479 /**
480  * \ingroup gdcmHeader
481  * \brief   Determines if the Transfer Syntax was allready encountered
482  *          and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
483  *
484  * @return  True when JPEGSpectralSelectionProcess6-8 found. False in all
485  *          other cases.
486  */
487 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
488    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
489    if ( !Element )
490       return false;
491    LoadElementValueSafe(Element);
492    string Transfer = Element->GetValue();
493    if ( Transfer == "1.2.840.10008.1.2.4.53" )
494       return true;
495    return false;
496 }
497
498 /**
499  * \ingroup gdcmHeader
500  * \brief   When the length of an element value is obviously wrong (because
501  *          the parser went Jabberwocky) one can hope improving things by
502  *          applying this heuristic.
503  */
504 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
505    if ( FoundLength == 0xffffffff)
506       FoundLength = 0;
507    ElVal->SetLength(FoundLength);
508 }
509
510 guint32 gdcmHeader::FindLengthOB(void) {
511    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
512    guint16 g;
513    guint16 n; 
514    long PositionOnEntry = ftell(fp);
515    bool FoundSequenceDelimiter = false;
516    guint32 TotalLength = 0;
517    guint32 ItemLength;
518
519    while ( ! FoundSequenceDelimiter) {
520       g = ReadInt16();
521       n = ReadInt16();
522       if (errno == 1)
523          return 0;
524       TotalLength += 4;  // We even have to decount the group and element 
525       if ( g != 0xfffe ) {
526          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
527                      "wrong group for an item sequence.");
528          errno = 1;
529          return 0;
530       }
531       if ( n == 0xe0dd )
532          FoundSequenceDelimiter = true;
533       else if ( n != 0xe000) {
534          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
535                      "wrong element for an item sequence.");
536          errno = 1;
537          return 0;
538       }
539       ItemLength = ReadInt32();
540       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
541                                       // the ItemLength with ReadInt32
542       SkipBytes(ItemLength);
543    }
544    fseek(fp, PositionOnEntry, SEEK_SET);
545    return TotalLength;
546 }
547
548 void gdcmHeader::FindLength(gdcmElValue * ElVal) {
549    guint16 element = ElVal->GetElement();
550    string  vr      = ElVal->GetVR();
551    guint16 length16;
552    
553    if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
554
555       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
556          // The following reserved two bytes (see PS 3.5-2001, section
557          // 7.1.2 Data element structure with explicit vr p27) must be
558          // skipped before proceeding on reading the length on 4 bytes.
559          fseek(fp, 2L, SEEK_CUR);
560          guint32 length32 = ReadInt32();
561          if ( (vr == "OB") && (length32 == 0xffffffff) ) {
562             ElVal->SetLength(FindLengthOB());
563             return;
564          }
565          FixFoundLength(ElVal, length32);
566          return;
567       }
568
569       // Length is encoded on 2 bytes.
570       length16 = ReadInt16();
571       
572       // We can tell the current file is encoded in big endian (like
573       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
574       // and it's value is the one of the encoding of a big endian file.
575       // In order to deal with such big endian encoded files, we have
576       // (at least) two strategies:
577       // * when we load the "Transfer Syntax" tag with value of big endian
578       //   encoding, we raise the proper flags. Then we wait for the end
579       //   of the META group (0x0002) among which is "Transfer Syntax",
580       //   before switching the swap code to big endian. We have to postpone
581       //   the switching of the swap code since the META group is fully encoded
582       //   in little endian, and big endian coding only starts at the next
583       //   group. The corresponding code can be hard to analyse and adds
584       //   many additional unnecessary tests for regular tags.
585       // * the second strategy consists in waiting for trouble, that shall
586       //   appear when we find the first group with big endian encoding. This
587       //   is easy to detect since the length of a "Group Length" tag (the
588       //   ones with zero as element number) has to be of 4 (0x0004). When we
589       //   encouter 1024 (0x0400) chances are the encoding changed and we
590       //   found a group with big endian encoding.
591       // We shall use this second strategy. In order to make sure that we
592       // can interpret the presence of an apparently big endian encoded
593       // length of a "Group Length" without committing a big mistake, we
594       // add an additional check: we look in the allready parsed elements
595       // for the presence of a "Transfer Syntax" whose value has to be "big
596       // endian encoding". When this is the case, chances are we have got our
597       // hands on a big endian encoded file: we switch the swap code to
598       // big endian and proceed...
599       if ( (element  == 0x000) && (length16 == 0x0400) ) {
600          if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
601             dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
602             errno = 1;
603             return;
604          }
605          length16 = 4;
606          SwitchSwapToBigEndian();
607          // Restore the unproperly loaded values i.e. the group, the element
608          // and the dictionary entry depending on them.
609          guint16 CorrectGroup   = SwapShort(ElVal->GetGroup());
610          guint16 CorrectElem    = SwapShort(ElVal->GetElement());
611          gdcmDictEntry * NewTag = GetDictEntryByKey(CorrectGroup, CorrectElem);
612          if (!NewTag) {
613             // This correct tag is not in the dictionary. Create a new one.
614             NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
615          }
616          // FIXME this can create a memory leaks on the old entry that be
617          // left unreferenced.
618          ElVal->SetDictEntry(NewTag);
619       }
620        
621       // Heuristic: well some files are really ill-formed.
622       if ( length16 == 0xffff) {
623          length16 = 0;
624          dbg.Verbose(0, "gdcmHeader::FindLength",
625                      "Erroneous element length fixed.");
626       }
627       FixFoundLength(ElVal, (guint32)length16);
628       return;
629    }
630
631    // Either implicit VR or a non DICOM conformal (see not below) explicit
632    // VR that ommited the VR of (at least) this element. Farts happen.
633    // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
634    // on Data elements "Implicit and Explicit VR Data Elements shall
635    // not coexist in a Data Set and Data Sets nested within it".]
636    // Length is on 4 bytes.
637    FixFoundLength(ElVal, ReadInt32());
638 }
639
640 /**
641  * \ingroup gdcmHeader
642  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
643  *          processor order.
644  *
645  * @return  The suggested integer.
646  */
647 guint32 gdcmHeader::SwapLong(guint32 a) {
648    // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
649    switch (sw) {
650    case    0 :
651       break;
652    case 4321 :
653       a=(   ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000)    | 
654             ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
655       break;
656    
657    case 3412 :
658       a=(   ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
659       break;
660    
661    case 2143 :
662       a=(    ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
663       break;
664    default :
665       dbg.Error(" gdcmHeader::SwapLong : unset swap code");
666       a=0;
667    }
668    return(a);
669 }
670
671 /**
672  * \ingroup gdcmHeader
673  * \brief   Swaps the bytes so they agree with the processor order
674  * @return  The properly swaped 16 bits integer.
675  */
676 guint16 gdcmHeader::SwapShort(guint16 a) {
677    if ( (sw==4321)  || (sw==2143) )
678       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
679    return (a);
680 }
681
682 void gdcmHeader::SkipBytes(guint32 NBytes) {
683    //FIXME don't dump the returned value
684    (void)fseek(fp, (long)NBytes, SEEK_CUR);
685 }
686
687 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
688    SkipBytes(ElVal->GetLength());
689 }
690
691 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
692    if (NewSize < 0)
693       return;
694    if ((guint32)NewSize >= (guint32)0xffffffff) {
695       MaxSizeLoadElementValue = 0xffffffff;
696       return;
697    }
698    MaxSizeLoadElementValue = NewSize;
699 }
700
701 /**
702  * \ingroup       gdcmHeader
703  * \brief         Loads the element content if it's length is not bigger
704  *                than the value specified with
705  *                gdcmHeader::SetMaxSizeLoadElementValue()
706  */
707 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
708    size_t item_read;
709    guint16 group  = ElVal->GetGroup();
710    guint16 elem   = ElVal->GetElement();
711    string  vr     = ElVal->GetVR();
712    guint32 length = ElVal->GetLength();
713    bool SkipLoad  = false;
714
715    fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
716    
717    // FIXME Sequences not treated yet !
718    //
719    // Ne faudrait-il pas au contraire trouver immediatement
720    // une maniere 'propre' de traiter les sequences (vr = SQ)
721    // car commencer par les ignorer risque de conduire a qq chose
722    // qui pourrait ne pas etre generalisable
723    // Well, I'm expecting your code !!!
724     
725    if( vr == "SQ" )
726       SkipLoad = true;
727
728    // Heuristic : a sequence "contains" a set of tags (called items). It looks
729    // like the last tag of a sequence (the one that terminates the sequence)
730    // has a group of 0xfffe (with a dummy length).
731    if( group == 0xfffe )
732       SkipLoad = true;
733
734    if ( SkipLoad ) {
735       ElVal->SetLength(0);
736       ElVal->SetValue("gdcm::Skipped");
737       return;
738    }
739
740    // When the length is zero things are easy:
741    if ( length == 0 ) {
742       ElVal->SetValue("");
743       return;
744    }
745
746    // The elements whose length is bigger than the specified upper bound
747    // are not loaded. Instead we leave a short notice of the offset of
748    // the element content and it's length.
749    if (length > MaxSizeLoadElementValue) {
750       ostringstream s;
751       s << "gdcm::NotLoaded.";
752       s << " Address:" << (long)ElVal->GetOffset();
753       s << " Length:"  << ElVal->GetLength();
754       ElVal->SetValue(s.str());
755       return;
756    }
757    
758    // When an integer is expected, read and convert the following two or
759    // four bytes properly i.e. as an integer as opposed to a string.
760         
761         // pour les elements de Value Multiplicity > 1
762         // on aura en fait une serie d'entiers
763         
764         // on devrait pouvoir faire + compact (?)
765                 
766         if ( IsAnInteger(ElVal) ) {
767                 guint32 NewInt;
768                 ostringstream s;
769                 int nbInt;
770                 if (vr == "US" || vr == "SS") {
771                         nbInt = length / 2;
772                         NewInt = ReadInt16();
773                         s << NewInt;
774                         if (nbInt > 1) {
775                                 for (int i=1; i < nbInt; i++) {
776                                         s << '\\';
777                                         NewInt = ReadInt16();
778                                         s << NewInt;
779                                         //printf("%s\n", s.str().c_str());
780                                 }
781                         }
782                         
783                 } else if (vr == "UL" || vr == "SL") {
784                         nbInt = length / 4;
785                         NewInt = ReadInt32();
786                         s << NewInt;
787                         if (nbInt > 1) {
788                                 for (int i=1; i < nbInt; i++) {
789                                         s << '\\';
790                                         NewInt = ReadInt32();
791                                         s << NewInt;
792                                 }
793                         }
794                 }                                       
795                 ElVal->SetValue(s.str());
796                 return; 
797         }
798    
799    // FIXME The exact size should be length if we move to strings or whatever
800    char* NewValue = (char*)malloc(length+1);
801    if( !NewValue) {
802       dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
803       return;
804    }
805    NewValue[length]= 0;
806    
807    item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
808    if ( item_read != 1 ) {
809       free(NewValue);
810       dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
811       ElVal->SetValue("gdcm::UnRead");
812       return;
813    }
814    ElVal->SetValue(NewValue);
815 }
816
817 /**
818  * \ingroup       gdcmHeader
819  * \brief         Loads the element while preserving the current
820  *                underlying file position indicator as opposed to
821  *                to LoadElementValue that modifies it.
822  * @param ElVal   Element whose value shall be loaded. 
823  * @return  
824  */
825 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
826    long PositionOnEntry = ftell(fp);
827    LoadElementValue(ElVal);
828    fseek(fp, PositionOnEntry, SEEK_SET);
829 }
830
831
832 guint16 gdcmHeader::ReadInt16(void) {
833    guint16 g;
834    size_t item_read;
835    item_read = fread (&g, (size_t)2,(size_t)1, fp);
836    errno = 0;
837    if ( item_read != 1 ) {
838       dbg.Verbose(1, "gdcmHeader::ReadInt16", " File read error");
839       errno = 1;
840       return 0;
841    }
842    g = SwapShort(g);
843    return g;
844 }
845
846 guint32 gdcmHeader::ReadInt32(void) {
847    guint32 g;
848    size_t item_read;
849    item_read = fread (&g, (size_t)4,(size_t)1, fp);
850    errno = 0;
851    if ( item_read != 1 ) {
852       dbg.Verbose(1, "gdcmHeader::ReadInt32", " File read error");
853       errno = 1;
854       return 0;
855    }
856    g = SwapLong(g);
857    return g;
858 }
859
860 /**
861  * \ingroup gdcmHeader
862  * \brief   Build a new Element Value from all the low level arguments. 
863  *          Check for existence of dictionary entry, and build
864  *          a default one when absent.
865  * @param   Group group   of the underlying DictEntry
866  * @param   Elem  element of the underlying DictEntry
867  */
868 gdcmElValue* gdcmHeader::NewElValueByKey(guint16 Group, guint16 Elem) {
869    // Find out if the tag we encountered is in the dictionaries:
870    gdcmDictEntry * NewTag = GetDictEntryByKey(Group, Elem);
871    if (!NewTag)
872       NewTag = new gdcmDictEntry(Group, Elem);
873
874    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
875    if (!NewElVal) {
876       dbg.Verbose(1, "gdcmHeader::NewElValueByKey",
877                   "failed to allocate gdcmElValue");
878       return (gdcmElValue*)0;
879    }
880    return NewElVal;
881 }
882
883 /**
884  * \ingroup gdcmHeader
885  * \brief   TODO
886  * @param   
887  */
888 int gdcmHeader::ReplaceOrCreateByNumber(guint16 Group, guint16 Elem, string Value) {
889
890         gdcmElValue* nvElValue=NewElValueByKey(Group, Elem);
891         PubElValSet.Add(nvElValue);     
892         PubElValSet.SetElValueByNumber(Value, Group, Elem);
893         return(1);
894 }   
895
896
897 /**
898  * \ingroup gdcmHeader
899  * \brief   Build a new Element Value from all the low level arguments. 
900  *          Check for existence of dictionary entry, and build
901  *          a default one when absent.
902  * @param   Name    Name of the underlying DictEntry
903  */
904 gdcmElValue* gdcmHeader::NewElValueByName(string Name) {
905
906    gdcmDictEntry * NewTag = GetDictEntryByName(Name);
907    if (!NewTag)
908       NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
909
910    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
911    if (!NewElVal) {
912       dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
913                   "failed to allocate gdcmElValue");
914       return (gdcmElValue*)0;
915    }
916    return NewElVal;
917 }  
918
919 /**
920  * \ingroup gdcmHeader
921  * \brief   Read the next tag but WITHOUT loading it's value
922  * @return  On succes the newly created ElValue, NULL on failure.      
923  */
924 gdcmElValue * gdcmHeader::ReadNextElement(void) {
925   
926    guint16 g,n;
927    gdcmElValue * NewElVal;
928    
929    g = ReadInt16();
930    n = ReadInt16();
931    if (errno == 1)
932       // We reached the EOF (or an error occured) and header parsing
933       // has to be considered as finished.
934       return (gdcmElValue *)0;
935    
936    NewElVal = NewElValueByKey(g, n);
937    FindVR(NewElVal);
938    FindLength(NewElVal);
939    if (errno == 1)
940       // Call it quits
941       return (gdcmElValue *)0;
942    NewElVal->SetOffset(ftell(fp));
943    return NewElVal;
944 }
945
946 /**
947  * \ingroup gdcmHeader
948  * \brief   Apply some heuristics to predict wether the considered 
949  *          element value contains/represents an integer or not.
950  * @param   ElVal The element value on which to apply the predicate.
951  * @return  The result of the heuristical predicate.
952  */
953 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
954    guint16 group   = ElVal->GetGroup();
955    guint16 element = ElVal->GetElement();
956    string  vr      = ElVal->GetVR();
957    guint32 length  = ElVal->GetLength();
958
959    // When we have some semantics on the element we just read, and if we
960    // a priori know we are dealing with an integer, then we shall be
961    // able to swap it's element value properly.
962    if ( element == 0 )  {  // This is the group length of the group
963       if (length == 4)
964          return true;
965       else
966          dbg.Error("gdcmHeader::IsAnInteger",
967                    "Erroneous Group Length element length.");
968    }
969  
970    /*   
971    // on le traite tt de même (VR peut donner l'info)
972                 // faire qq chose + ruse (pas de test si pas de VR)  
973    if ( group % 2 != 0 )
974       // We only have some semantics on documented elements, which are
975       // the even ones.
976       return false; 
977     */
978    
979    /*
980    if ( (length != 4) && ( length != 2) )
981       // Swapping only make sense on integers which are 2 or 4 bytes long.
982                 
983                 // En fait, pour les entiers de 'Value Multiplicity' supérieur a 1
984                 // la longueur n'est pas forcement 2 ou 4 
985                 // ET il faudra swapper.
986       return false;
987     */
988    
989    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
990       return true;
991    
992    
993    // est-ce encore utile?
994    // mieux vaut modifier le source du Dicom Dictionnaty 
995    // et remplacer pour ces 2 cas  RET par US
996    
997    if ( (group == 0x0028) && (element == 0x0005) )
998       // The "Image Dimensions" tag is retained from ACR/NEMA and contains
999       // the number of dimensions of the contained object (1 for Signal,
1000       // 2 for Image, 3 for Volume, 4 for Sequence).
1001       return true;
1002    
1003    if ( (group == 0x0028) && (element == 0x0200) )
1004       // This tag is retained from ACR/NEMA
1005       return true;
1006    
1007    return false;
1008 }
1009
1010 /**
1011  * \ingroup gdcmHeader
1012  * \brief   Recover the offset (from the beginning of the file) of the pixels.
1013  */
1014 size_t gdcmHeader::GetPixelOffset(void) {
1015    // If this file complies with the norm we should encounter the
1016    // "Image Location" tag (0x0028,  0x0200). This tag contains the
1017    // the group that contains the pixel data (hence the "Pixel Data"
1018    // is found by indirection through the "Image Location").
1019    // Inside the group pointed by "Image Location" the searched element
1020    // is conventionally the element 0x0010 (when the norm is respected).
1021    //    When the "Image Location" is absent we default to group 0x7fe0.
1022    guint16 grPixel;
1023    guint16 numPixel;
1024    string ImageLocation = GetPubElValByName("Image Location");
1025    if ( ImageLocation == "gdcm::Unfound" ) {
1026       grPixel = 0x7fe0;
1027    } else {
1028       grPixel = (guint16) atoi( ImageLocation.c_str() );
1029    }
1030    if (grPixel != 0x7fe0)
1031       // FIXME is this still necessary ?
1032       // Now, this looks like an old dirty fix for Philips imager
1033       numPixel = 0x1010;
1034    else
1035       numPixel = 0x0010;
1036    gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel, numPixel);
1037    if (PixelElement)
1038       return PixelElement->GetOffset();
1039    else
1040       return 0;
1041 }
1042
1043 /**
1044  * \ingroup gdcmHeader
1045  * \brief   Searches both the public and the shadow dictionary (when they
1046  *          exist) for the presence of the DictEntry with given
1047  *          group and element. The public dictionary has precedence on the
1048  *          shadow one.
1049  * @param   group   group of the searched DictEntry
1050  * @param   element element of the searched DictEntry
1051  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1052  */
1053 gdcmDictEntry * gdcmHeader::GetDictEntryByKey(guint16 group, guint16 element) {
1054    gdcmDictEntry * found = (gdcmDictEntry*)0;
1055    if (!RefPubDict && !RefShaDict) {
1056       dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
1057                      "we SHOULD have a default dictionary");
1058    }
1059    if (RefPubDict) {
1060       found = RefPubDict->GetTagByKey(group, element);
1061       if (found)
1062          return found;
1063    }
1064    if (RefShaDict) {
1065       found = RefShaDict->GetTagByKey(group, element);
1066       if (found)
1067          return found;
1068    }
1069    return found;
1070 }
1071
1072 /**
1073  * \ingroup gdcmHeader
1074  * \brief   Searches both the public and the shadow dictionary (when they
1075  *          exist) for the presence of the DictEntry with given name.
1076  *          The public dictionary has precedence on the shadow one.
1077  * @param   Name name of the searched DictEntry
1078  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1079  */
1080 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1081    gdcmDictEntry * found = (gdcmDictEntry*)0;
1082    if (!RefPubDict && !RefShaDict) {
1083       dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
1084                      "we SHOULD have a default dictionary");
1085    }
1086    if (RefPubDict) {
1087       found = RefPubDict->GetTagByName(Name);
1088       if (found)
1089          return found;
1090    }
1091    if (RefShaDict) {
1092       found = RefShaDict->GetTagByName(Name);
1093       if (found)
1094          return found;
1095    }
1096    return found;
1097 }
1098
1099 /**
1100  * \ingroup gdcmHeader
1101  * \brief   Searches within the public dictionary for element value of
1102  *          a given tag.
1103  * @param   group Group of the researched tag.
1104  * @param   element Element of the researched tag.
1105  * @return  Corresponding element value when it exists, and the string
1106  *          "gdcm::Unfound" otherwise.
1107  */
1108 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1109    return PubElValSet.GetElValueByNumber(group, element);
1110 }
1111
1112 /**
1113  * \ingroup gdcmHeader
1114  * \brief   Searches within the public dictionary for element value
1115  *          representation of a given tag.
1116  *
1117  *          Obtaining the VR (Value Representation) might be needed by caller
1118  *          to convert the string typed content to caller's native type 
1119  *          (think of C++ vs Python). The VR is actually of a higher level
1120  *          of semantics than just the native C++ type.
1121  * @param   group Group of the researched tag.
1122  * @param   element Element of the researched tag.
1123  * @return  Corresponding element value representation when it exists,
1124  *          and the string "gdcm::Unfound" otherwise.
1125  */
1126 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1127    gdcmElValue* elem =  PubElValSet.GetElementByNumber(group, element);
1128    if ( !elem )
1129       return "gdcm::Unfound";
1130    return elem->GetVR();
1131 }
1132
1133 /**
1134  * \ingroup gdcmHeader
1135  * \brief   Searches within the public dictionary for element value of
1136  *          a given tag.
1137  * @param   TagName name of the researched element.
1138  * @return  Corresponding element value when it exists, and the string
1139  *          "gdcm::Unfound" otherwise.
1140  */
1141 string gdcmHeader::GetPubElValByName(string TagName) {
1142    return PubElValSet.GetElValueByName(TagName);
1143 }
1144
1145 /**
1146  * \ingroup gdcmHeader
1147  * \brief   Searches within the elements parsed with the public dictionary for
1148  *          the element value representation of a given tag.
1149  *
1150  *          Obtaining the VR (Value Representation) might be needed by caller
1151  *          to convert the string typed content to caller's native type 
1152  *          (think of C++ vs Python). The VR is actually of a higher level
1153  *          of semantics than just the native C++ type.
1154  * @param   TagName name of the researched element.
1155  * @return  Corresponding element value representation when it exists,
1156  *          and the string "gdcm::Unfound" otherwise.
1157  */
1158 string gdcmHeader::GetPubElValRepByName(string TagName) {
1159    gdcmElValue* elem =  PubElValSet.GetElementByName(TagName);
1160    if ( !elem )
1161       return "gdcm::Unfound";
1162    return elem->GetVR();
1163 }
1164
1165 /**
1166  * \ingroup gdcmHeader
1167  * \brief   Searches within elements parsed with the SHADOW dictionary 
1168  *          for the element value of a given tag.
1169  * @param   group Group of the researched tag.
1170  * @param   element Element of the researched tag.
1171  * @return  Corresponding element value representation when it exists,
1172  *          and the string "gdcm::Unfound" otherwise.
1173  */
1174 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1175    return ShaElValSet.GetElValueByNumber(group, element);
1176 }
1177
1178 /**
1179  * \ingroup gdcmHeader
1180  * \brief   Searches within the elements parsed with the SHADOW dictionary
1181  *          for the element value representation of a given tag.
1182  *
1183  *          Obtaining the VR (Value Representation) might be needed by caller
1184  *          to convert the string typed content to caller's native type 
1185  *          (think of C++ vs Python). The VR is actually of a higher level
1186  *          of semantics than just the native C++ type.
1187  * @param   group Group of the researched tag.
1188  * @param   element Element of the researched tag.
1189  * @return  Corresponding element value representation when it exists,
1190  *          and the string "gdcm::Unfound" otherwise.
1191  */
1192 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1193    gdcmElValue* elem =  ShaElValSet.GetElementByNumber(group, element);
1194    if ( !elem )
1195       return "gdcm::Unfound";
1196    return elem->GetVR();
1197 }
1198
1199 /**
1200  * \ingroup gdcmHeader
1201  * \brief   Searches within the elements parsed with the shadow dictionary
1202  *          for an element value of given tag.
1203  * @param   TagName name of the researched element.
1204  * @return  Corresponding element value when it exists, and the string
1205  *          "gdcm::Unfound" otherwise.
1206  */
1207 string gdcmHeader::GetShaElValByName(string TagName) {
1208    return ShaElValSet.GetElValueByName(TagName);
1209 }
1210
1211 /**
1212  * \ingroup gdcmHeader
1213  * \brief   Searches within the elements parsed with the shadow dictionary for
1214  *          the element value representation of a given tag.
1215  *
1216  *          Obtaining the VR (Value Representation) might be needed by caller
1217  *          to convert the string typed content to caller's native type 
1218  *          (think of C++ vs Python). The VR is actually of a higher level
1219  *          of semantics than just the native C++ type.
1220  * @param   TagName name of the researched element.
1221  * @return  Corresponding element value representation when it exists,
1222  *          and the string "gdcm::Unfound" otherwise.
1223  */
1224 string gdcmHeader::GetShaElValRepByName(string TagName) {
1225    gdcmElValue* elem =  ShaElValSet.GetElementByName(TagName);
1226    if ( !elem )
1227       return "gdcm::Unfound";
1228    return elem->GetVR();
1229 }
1230
1231 /**
1232  * \ingroup gdcmHeader
1233  * \brief   Searches within elements parsed with the public dictionary 
1234  *          and then within the elements parsed with the shadow dictionary
1235  *          for the element value of a given tag.
1236  * @param   group Group of the researched tag.
1237  * @param   element Element of the researched tag.
1238  * @return  Corresponding element value representation when it exists,
1239  *          and the string "gdcm::Unfound" otherwise.
1240  */
1241 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1242    string pub = GetPubElValByNumber(group, element);
1243    if (pub.length())
1244       return pub;
1245    return GetShaElValByNumber(group, element);
1246 }
1247
1248 /**
1249  * \ingroup gdcmHeader
1250  * \brief   Searches within elements parsed with the public dictionary 
1251  *          and then within the elements parsed with the shadow dictionary
1252  *          for the element value representation of a given tag.
1253  *
1254  *          Obtaining the VR (Value Representation) might be needed by caller
1255  *          to convert the string typed content to caller's native type 
1256  *          (think of C++ vs Python). The VR is actually of a higher level
1257  *          of semantics than just the native C++ type.
1258  * @param   group Group of the researched tag.
1259  * @param   element Element of the researched tag.
1260  * @return  Corresponding element value representation when it exists,
1261  *          and the string "gdcm::Unfound" otherwise.
1262  */
1263 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1264    string pub = GetPubElValRepByNumber(group, element);
1265    if (pub.length())
1266       return pub;
1267    return GetShaElValRepByNumber(group, element);
1268 }
1269
1270 /**
1271  * \ingroup gdcmHeader
1272  * \brief   Searches within elements parsed with the public dictionary 
1273  *          and then within the elements parsed with the shadow dictionary
1274  *          for the element value of a given tag.
1275  * @param   TagName name of the researched element.
1276  * @return  Corresponding element value when it exists,
1277  *          and the string "gdcm::Unfound" otherwise.
1278  */
1279 string gdcmHeader::GetElValByName(string TagName) {
1280    string pub = GetPubElValByName(TagName);
1281    if (pub.length())
1282       return pub;
1283    return GetShaElValByName(TagName);
1284 }
1285
1286 /**
1287  * \ingroup gdcmHeader
1288  * \brief   Searches within elements parsed with the public dictionary 
1289  *          and then within the elements parsed with the shadow dictionary
1290  *          for the element value representation of a given tag.
1291  *
1292  *          Obtaining the VR (Value Representation) might be needed by caller
1293  *          to convert the string typed content to caller's native type 
1294  *          (think of C++ vs Python). The VR is actually of a higher level
1295  *          of semantics than just the native C++ type.
1296  * @param   TagName name of the researched element.
1297  * @return  Corresponding element value representation when it exists,
1298  *          and the string "gdcm::Unfound" otherwise.
1299  */
1300 string gdcmHeader::GetElValRepByName(string TagName) {
1301    string pub = GetPubElValRepByName(TagName);
1302    if (pub.length())
1303       return pub;
1304    return GetShaElValRepByName(TagName);
1305 }
1306
1307 /**
1308  * \ingroup gdcmHeader
1309  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1310  *          through it's (group, element) and modifies it's content with
1311  *          the given value.
1312  * @param   content new value to substitute with
1313  * @param   group   group of the ElVal to modify
1314  * @param   element element of the ElVal to modify
1315  */
1316 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1317                                     guint16 element)
1318 {
1319    return (  PubElValSet.SetElValueByNumber (content, group, element) );
1320 }
1321
1322 /**
1323  * \ingroup gdcmHeader
1324  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1325  *          through tag name and modifies it's content with the given value.
1326  * @param   content new value to substitute with
1327  * @param   TagName name of the tag to be modified
1328  */
1329 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1330    return (  PubElValSet.SetElValueByName (content, TagName) );
1331 }
1332
1333 /**
1334  * \ingroup gdcmHeader
1335  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1336  *          through it's (group, element) and modifies it's length with
1337  *          the given value.
1338  * \warning Use with extreme caution.
1339  * @param   length new length to substitute with
1340  * @param   group   group of the ElVal to modify
1341  * @param   element element of the ElVal to modify
1342  * @return  1 on success, 0 otherwise.
1343  */
1344
1345 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1346                                     guint16 element) {
1347         return (  PubElValSet.SetElValueLengthByNumber (length, group, element) );
1348 }
1349
1350 /**
1351  * \ingroup gdcmHeader
1352  * \brief   Accesses an existing gdcmElValue in the ShaElValSet of this instance
1353  *          through it's (group, element) and modifies it's content with
1354  *          the given value.
1355  * @param   content new value to substitute with
1356  * @param   group   group of the ElVal to modify
1357  * @param   element element of the ElVal to modify
1358  * @return  1 on success, 0 otherwise.
1359  */
1360 int gdcmHeader::SetShaElValByNumber(string content,
1361                                     guint16 group, guint16 element) {
1362    return (  ShaElValSet.SetElValueByNumber (content, group, element) );
1363 }
1364
1365 /**
1366  * \ingroup gdcmHeader
1367  * \brief   Accesses an existing gdcmElValue in the ShaElValSet of this instance
1368  *          through tag name and modifies it's content with the given value.
1369  * @param   content new value to substitute with
1370  * @param   TagName name of the tag to be modified
1371  */
1372 int gdcmHeader::SetShaElValByName(string content, string TagName) {
1373    return (  ShaElValSet.SetElValueByName (content, TagName) );
1374 }
1375
1376 /**
1377  * \ingroup gdcmHeader
1378  * \brief   Parses the header of the file but WITHOUT loading element values.
1379  */
1380 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1381    gdcmElValue * newElValue = (gdcmElValue *)0;
1382    
1383    rewind(fp);
1384    CheckSwap();
1385    while ( (newElValue = ReadNextElement()) ) {
1386       SkipElementValue(newElValue);
1387       PubElValSet.Add(newElValue);
1388    }
1389 }
1390
1391 /**
1392  * \ingroup gdcmHeader
1393  * \brief   Once the header is parsed add some gdcm convenience/helper elements
1394  *          in the gdcmElValSet. For example add:
1395  *          - gdcmImageType which is an entry containing a short for the
1396  *            type of image and whose value ranges in 
1397  *               I8   (unsigned 8 bit image)
1398  *               I16  (unsigned 8 bit image)
1399  *               IS16 (signed 8 bit image)
1400  *          - gdcmXsize, gdcmYsize, gdcmZsize whose values are respectively
1401  *            the ones of the official DICOM fields Rows, Columns and Planes.
1402  */
1403 void gdcmHeader::AddAndDefaultElements(void) {
1404    gdcmElValue* NewElVal = (gdcmElValue*)0;
1405    string NewVal;
1406
1407    NewElVal = NewManualElValToPubDict("gdcmXSize", "US");
1408    if (!NewElVal) return;
1409    NewVal = GetElValByName("Rows");
1410    if (NewVal != "gdcm::Unfound")
1411       NewElVal->SetValue(NewVal);
1412    else 
1413       NewElVal->SetValue("0");
1414
1415    NewElVal = NewManualElValToPubDict("gdcmYSize", "US");
1416    if (!NewElVal) return;
1417    NewVal = GetElValByName("Columns");
1418    if (NewVal != "gdcm::Unfound")
1419       NewElVal->SetValue(NewVal);
1420    else
1421       NewElVal->SetValue("0");
1422
1423
1424    NewElVal = NewManualElValToPubDict("gdcmZSize", "US");
1425    if (!NewElVal) return;
1426    NewVal = GetElValByNumber(0x0028,0x0008); // 0028 0008 IS IMG Number of Frames (DICOM)
1427    if (NewVal == "gdcm::Unfound") {
1428         NewVal = GetElValByNumber(0x0028,0x0012); // 028 0012 US IMG Planes (ACR-NEMA)
1429         if (NewVal == "gdcm::Unfound") {          // Warning !!! : 6000 0012 US OLY Planes
1430                 NewElVal->SetValue("0");
1431         } else {
1432                 NewElVal->SetValue(NewVal);
1433         }               
1434    } else {
1435       NewElVal->SetValue(NewVal);
1436    }                                            // length is still wrong 
1437 }                                               // do we care about it?
1438
1439
1440 /**
1441  * \ingroup gdcmHeader
1442  * \brief  This predicate, based on hopefully reasonnable heuristics,
1443  *         decides whether or not the current gdcmHeader was properly parsed
1444  *         and contains the mandatory information for being considered as
1445  *         a well formed and usable image.
1446  * @return true when gdcmHeader is the one of a reasonable Dicom file,
1447  *         false otherwise. 
1448  */
1449 bool gdcmHeader::IsReadable(void) {
1450    if (   GetElValByName("Image Dimensions") != "gdcm::Unfound"
1451       && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1452       return false;
1453    }
1454    if (  GetElValByName("Bits Allocated") == "gdcm::Unfound" )
1455       return false;
1456    if (  GetElValByName("Bits Stored") == "gdcm::Unfound" )
1457       return false;
1458    if (  GetElValByName("High Bit") == "gdcm::Unfound" )
1459       return false;
1460    if (  GetElValByName("Pixel Representation") == "gdcm::Unfound" )
1461       return false;
1462    return true;
1463 }
1464
1465
1466 /**
1467  * \ingroup gdcmHeader
1468  * \brief   Small utility function that creates a new manually crafted
1469  *          (as opposed as read from the file) gdcmElValue with user
1470  *          specified name and adds it to the public tag hash table.
1471  *          Refer to gdcmHeader::AddAndDefaultElements for a typical usage.
1472  * \note    A fake TagKey is generated so the PubDict can keep it's coherence.
1473  * @param   NewTagName The name to be given to this new tag.
1474  * @param   VR The Value Representation to be given to this new tag.
1475  * @ return The newly hand crafted Element Value.
1476  */
1477 gdcmElValue* gdcmHeader::NewManualElValToPubDict(string NewTagName, string VR) {
1478    gdcmElValue* NewElVal = (gdcmElValue*)0;
1479    guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
1480    guint32 FreeElem = 0;
1481    gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1482
1483    FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1484    if (FreeElem == UINT32_MAX) {
1485       dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1486                      "Group 0xffff in Public Dict is full");
1487       return (gdcmElValue*)0;
1488    }
1489    NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1490                                 VR, "GDCM", NewTagName);
1491    NewElVal = new gdcmElValue(NewEntry);
1492    PubElValSet.Add(NewElVal);
1493    return NewElVal;
1494
1495 }
1496
1497 /**
1498  * \ingroup gdcmHeader
1499  * \brief   Loads the element values of all the elements present in the
1500  *          public tag based hash table.
1501  */
1502 void gdcmHeader::LoadElements(void) {
1503    rewind(fp);   
1504    TagElValueHT ht = PubElValSet.GetTagHt();
1505    for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1506       LoadElementValue(tag->second);
1507       }
1508 }
1509
1510 void gdcmHeader::PrintPubElVal(ostream & os) {
1511    PubElValSet.Print(os);
1512 }
1513
1514 void gdcmHeader::PrintPubDict(ostream & os) {
1515    RefPubDict->Print(os);
1516 }