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