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