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