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