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