]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
* More memmory link related corrections and documentation fixes.
[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    if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
432    if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
433    return false;
434 }
435
436
437 /**
438  * \ingroup gdcmHeader
439  * \brief   Determines if the Transfer Syntax was allready encountered
440  *          and if it corresponds to a JPEGExtendedProcess2-4 one.
441  *
442  * @return  True when JPEGExtendedProcess2-4 found. False in all other cases.
443  */
444 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
445    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
446    if ( !Element )
447       return false;
448    LoadElementValueSafe(Element);
449    string Transfer = Element->GetValue();
450    if ( Transfer == "1.2.840.10008.1.2.4.51" )
451       return true;
452    return false;
453 }
454
455 /**
456  * \ingroup gdcmHeader
457  * \brief   Determines if the Transfer Syntax was allready encountered
458  *          and if it corresponds to a JPEGExtendeProcess3-5 one.
459  *
460  * @return  True when JPEGExtendedProcess3-5 found. False in all other cases.
461  */
462 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
463    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
464    if ( !Element )
465       return false;
466    LoadElementValueSafe(Element);
467    string Transfer = Element->GetValue();
468    if ( Transfer == "1.2.840.10008.1.2.4.52" )
469       return true;
470    return false;
471 }
472
473 /**
474  * \ingroup gdcmHeader
475  * \brief   Determines if the Transfer Syntax was allready encountered
476  *          and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
477  *
478  * @return  True when JPEGSpectralSelectionProcess6-8 found. False in all
479  *          other cases.
480  */
481 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
482    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
483    if ( !Element )
484       return false;
485    LoadElementValueSafe(Element);
486    string Transfer = Element->GetValue();
487    if ( Transfer == "1.2.840.10008.1.2.4.53" )
488       return true;
489    return false;
490 }
491 /**
492  * \ingroup gdcmHeader
493  * \brief   Predicate for dicom version 3 file.
494  * @return  True when the file is a dicom version 3.
495  */
496 bool gdcmHeader::IsDicomV3(void) {
497    if (   (filetype == ExplicitVR)
498        || (filetype == ImplicitVR) )
499       return true;
500    return false;
501 }
502
503 /**
504  * \ingroup gdcmHeader
505  * \brief   When the length of an element value is obviously wrong (because
506  *          the parser went Jabberwocky) one can hope improving things by
507  *          applying this heuristic.
508  */
509 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
510    if ( FoundLength == 0xffffffff)
511       FoundLength = 0;
512    ElVal->SetLength(FoundLength);
513 }
514
515 guint32 gdcmHeader::FindLengthOB(void) {
516    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
517    guint16 g;
518    guint16 n; 
519    long PositionOnEntry = ftell(fp);
520    bool FoundSequenceDelimiter = false;
521    guint32 TotalLength = 0;
522    guint32 ItemLength;
523
524    while ( ! FoundSequenceDelimiter) {
525       g = ReadInt16();
526       n = ReadInt16();
527       if (errno == 1)
528          return 0;
529       TotalLength += 4;  // We even have to decount the group and element 
530       if ( g != 0xfffe ) {
531          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
532                      "wrong group for an item sequence.");
533          errno = 1;
534          return 0;
535       }
536       if ( n == 0xe0dd )
537          FoundSequenceDelimiter = true;
538       else if ( n != 0xe000) {
539          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
540                      "wrong element for an item sequence.");
541          errno = 1;
542          return 0;
543       }
544       ItemLength = ReadInt32();
545       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
546                                       // the ItemLength with ReadInt32
547       SkipBytes(ItemLength);
548    }
549    fseek(fp, PositionOnEntry, SEEK_SET);
550    return TotalLength;
551 }
552
553 void gdcmHeader::FindLength(gdcmElValue * ElVal) {
554    guint16 element = ElVal->GetElement();
555    string  vr      = ElVal->GetVR();
556    guint16 length16;
557    
558    if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
559
560       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
561          // The following reserved two bytes (see PS 3.5-2001, section
562          // 7.1.2 Data element structure with explicit vr p27) must be
563          // skipped before proceeding on reading the length on 4 bytes.
564          fseek(fp, 2L, SEEK_CUR);
565          guint32 length32 = ReadInt32();
566          if ( (vr == "OB") && (length32 == 0xffffffff) ) {
567             ElVal->SetLength(FindLengthOB());
568             return;
569          }
570          FixFoundLength(ElVal, length32);
571          return;
572       }
573
574       // Length is encoded on 2 bytes.
575       length16 = ReadInt16();
576       
577       // We can tell the current file is encoded in big endian (like
578       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
579       // and it's value is the one of the encoding of a big endian file.
580       // In order to deal with such big endian encoded files, we have
581       // (at least) two strategies:
582       // * when we load the "Transfer Syntax" tag with value of big endian
583       //   encoding, we raise the proper flags. Then we wait for the end
584       //   of the META group (0x0002) among which is "Transfer Syntax",
585       //   before switching the swap code to big endian. We have to postpone
586       //   the switching of the swap code since the META group is fully encoded
587       //   in little endian, and big endian coding only starts at the next
588       //   group. The corresponding code can be hard to analyse and adds
589       //   many additional unnecessary tests for regular tags.
590       // * the second strategy consists in waiting for trouble, that shall
591       //   appear when we find the first group with big endian encoding. This
592       //   is easy to detect since the length of a "Group Length" tag (the
593       //   ones with zero as element number) has to be of 4 (0x0004). When we
594       //   encouter 1024 (0x0400) chances are the encoding changed and we
595       //   found a group with big endian encoding.
596       // We shall use this second strategy. In order to make sure that we
597       // can interpret the presence of an apparently big endian encoded
598       // length of a "Group Length" without committing a big mistake, we
599       // add an additional check: we look in the allready parsed elements
600       // for the presence of a "Transfer Syntax" whose value has to be "big
601       // endian encoding". When this is the case, chances are we have got our
602       // hands on a big endian encoded file: we switch the swap code to
603       // big endian and proceed...
604       if ( (element  == 0x000) && (length16 == 0x0400) ) {
605          if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
606             dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
607             errno = 1;
608             return;
609          }
610          length16 = 4;
611          SwitchSwapToBigEndian();
612          // Restore the unproperly loaded values i.e. the group, the element
613          // and the dictionary entry depending on them.
614          guint16 CorrectGroup   = SwapShort(ElVal->GetGroup());
615          guint16 CorrectElem    = SwapShort(ElVal->GetElement());
616          gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
617                                                        CorrectElem);
618          if (!NewTag) {
619             // This correct tag is not in the dictionary. Create a new one.
620             NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
621          }
622          // FIXME this can create a memory leaks on the old entry that be
623          // left unreferenced.
624          ElVal->SetDictEntry(NewTag);
625       }
626        
627       // Heuristic: well some files are really ill-formed.
628       if ( length16 == 0xffff) {
629          length16 = 0;
630          dbg.Verbose(0, "gdcmHeader::FindLength",
631                      "Erroneous element length fixed.");
632       }
633       FixFoundLength(ElVal, (guint32)length16);
634       return;
635    }
636
637    // Either implicit VR or a non DICOM conformal (see not below) explicit
638    // VR that ommited the VR of (at least) this element. Farts happen.
639    // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
640    // on Data elements "Implicit and Explicit VR Data Elements shall
641    // not coexist in a Data Set and Data Sets nested within it".]
642    // Length is on 4 bytes.
643    FixFoundLength(ElVal, ReadInt32());
644 }
645
646 /**
647  * \ingroup gdcmHeader
648  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
649  *          processor order.
650  *
651  * @return  The suggested integer.
652  */
653 guint32 gdcmHeader::SwapLong(guint32 a) {
654    switch (sw) {
655    case    0 :
656       break;
657    case 4321 :
658       a=(   ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000)    | 
659             ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
660       break;
661    
662    case 3412 :
663       a=(   ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
664       break;
665    
666    case 2143 :
667       a=(    ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
668       break;
669    default :
670       dbg.Error(" gdcmHeader::SwapLong : unset swap code");
671       a=0;
672    }
673    return(a);
674 }
675
676 /**
677  * \ingroup gdcmHeader
678  * \brief   Swaps the bytes so they agree with the processor order
679  * @return  The properly swaped 16 bits integer.
680  */
681 guint16 gdcmHeader::SwapShort(guint16 a) {
682    if ( (sw==4321)  || (sw==2143) )
683       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
684    return (a);
685 }
686
687 void gdcmHeader::SkipBytes(guint32 NBytes) {
688    //FIXME don't dump the returned value
689    (void)fseek(fp, (long)NBytes, SEEK_CUR);
690 }
691
692 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
693    SkipBytes(ElVal->GetLength());
694 }
695
696 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
697    if (NewSize < 0)
698       return;
699    if ((guint32)NewSize >= (guint32)0xffffffff) {
700       MaxSizeLoadElementValue = 0xffffffff;
701       return;
702    }
703    MaxSizeLoadElementValue = NewSize;
704 }
705
706 /**
707  * \ingroup       gdcmHeader
708  * \brief         Loads the element content if it's length is not bigger
709  *                than the value specified with
710  *                gdcmHeader::SetMaxSizeLoadElementValue()
711  */
712 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
713    size_t item_read;
714    guint16 group  = ElVal->GetGroup();
715    guint16 elem   = ElVal->GetElement();
716    string  vr     = ElVal->GetVR();
717    guint32 length = ElVal->GetLength();
718    bool SkipLoad  = false;
719
720    fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
721    
722    // FIXME Sequences not treated yet !
723    //
724    // Ne faudrait-il pas au contraire trouver immediatement
725    // une maniere 'propre' de traiter les sequences (vr = SQ)
726    // car commencer par les ignorer risque de conduire a qq chose
727    // qui pourrait ne pas etre generalisable
728    // Well, I'm expecting your code !!!
729     
730    if( vr == "SQ" )
731       SkipLoad = true;
732
733    // Heuristic : a sequence "contains" a set of tags (called items). It looks
734    // like the last tag of a sequence (the one that terminates the sequence)
735    // has a group of 0xfffe (with a dummy length).
736    if( group == 0xfffe )
737       SkipLoad = true;
738
739    if ( SkipLoad ) {
740       ElVal->SetLength(0);
741       ElVal->SetValue("gdcm::Skipped");
742       return;
743    }
744
745    // When the length is zero things are easy:
746    if ( length == 0 ) {
747       ElVal->SetValue("");
748       return;
749    }
750
751    // The elements whose length is bigger than the specified upper bound
752    // are not loaded. Instead we leave a short notice of the offset of
753    // the element content and it's length.
754    if (length > MaxSizeLoadElementValue) {
755       ostringstream s;
756       s << "gdcm::NotLoaded.";
757       s << " Address:" << (long)ElVal->GetOffset();
758       s << " Length:"  << ElVal->GetLength();
759       ElVal->SetValue(s.str());
760       return;
761    }
762    
763    // When an integer is expected, read and convert the following two or
764    // four bytes properly i.e. as an integer as opposed to a string.
765         
766         // pour les elements de Value Multiplicity > 1
767         // on aura en fait une serie d'entiers
768         
769         // on devrait pouvoir faire + compact (?)
770                 
771         if ( IsAnInteger(ElVal) ) {
772                 guint32 NewInt;
773                 ostringstream s;
774                 int nbInt;
775                 if (vr == "US" || vr == "SS") {
776                         nbInt = length / 2;
777                         NewInt = ReadInt16();
778                         s << NewInt;
779                         if (nbInt > 1) {
780                                 for (int i=1; i < nbInt; i++) {
781                                         s << '\\';
782                                         NewInt = ReadInt16();
783                                         s << NewInt;
784                                 }
785                         }
786                         
787                 } else if (vr == "UL" || vr == "SL") {
788                         nbInt = length / 4;
789                         NewInt = ReadInt32();
790                         s << NewInt;
791                         if (nbInt > 1) {
792                                 for (int i=1; i < nbInt; i++) {
793                                         s << '\\';
794                                         NewInt = ReadInt32();
795                                         s << NewInt;
796                                 }
797                         }
798                 }                                       
799                 ElVal->SetValue(s.str());
800                 return; 
801         }
802    
803    // We need an additional byte for storing \0 that is not on disk
804    char* NewValue = (char*)malloc(length+1);
805    if( !NewValue) {
806       dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
807       return;
808    }
809    NewValue[length]= 0;
810    
811    item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
812    if ( item_read != 1 ) {
813       free(NewValue);
814       dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
815       ElVal->SetValue("gdcm::UnRead");
816       return;
817    }
818    ElVal->SetValue(NewValue);
819    free(NewValue);
820 }
821
822 /**
823  * \ingroup       gdcmHeader
824  * \brief         Loads the element while preserving the current
825  *                underlying file position indicator as opposed to
826  *                to LoadElementValue that modifies it.
827  * @param ElVal   Element whose value shall be loaded. 
828  * @return  
829  */
830 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
831    long PositionOnEntry = ftell(fp);
832    LoadElementValue(ElVal);
833    fseek(fp, PositionOnEntry, SEEK_SET);
834 }
835
836
837 guint16 gdcmHeader::ReadInt16(void) {
838    guint16 g;
839    size_t item_read;
840    item_read = fread (&g, (size_t)2,(size_t)1, fp);
841    errno = 0;
842    if ( item_read != 1 ) {
843       dbg.Verbose(1, "gdcmHeader::ReadInt16", " File read error");
844       errno = 1;
845       return 0;
846    }
847    g = SwapShort(g);
848    return g;
849 }
850
851 guint32 gdcmHeader::ReadInt32(void) {
852    guint32 g;
853    size_t item_read;
854    item_read = fread (&g, (size_t)4,(size_t)1, fp);
855    errno = 0;
856    if ( item_read != 1 ) {
857       dbg.Verbose(1, "gdcmHeader::ReadInt32", " File read error");
858       errno = 1;
859       return 0;
860    }
861    g = SwapLong(g);
862    return g;
863 }
864
865 /**
866  * \ingroup gdcmHeader
867  * \brief   Build a new Element Value from all the low level arguments. 
868  *          Check for existence of dictionary entry, and build
869  *          a default one when absent.
870  * @param   Group group   of the underlying DictEntry
871  * @param   Elem  element of the underlying DictEntry
872  */
873 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
874    // Find out if the tag we encountered is in the dictionaries:
875    gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
876    if (!NewTag)
877       NewTag = new gdcmDictEntry(Group, Elem);
878
879    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
880    if (!NewElVal) {
881       dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
882                   "failed to allocate gdcmElValue");
883       return (gdcmElValue*)0;
884    }
885    return NewElVal;
886 }
887
888 /**
889  * \ingroup gdcmHeader
890  * \brief   TODO
891  * @param   
892  */
893 int gdcmHeader::ReplaceOrCreateByNumber(string Value, guint16 Group, guint16 Elem ) {
894
895         gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
896         PubElValSet.Add(nvElValue);     
897         PubElValSet.SetElValueByNumber(Value, Group, Elem);
898         return(1);
899 }   
900
901
902 /**
903  * \ingroup gdcmHeader
904  * \brief   Build a new Element Value from all the low level arguments. 
905  *          Check for existence of dictionary entry, and build
906  *          a default one when absent.
907  * @param   Name    Name of the underlying DictEntry
908  */
909 gdcmElValue* gdcmHeader::NewElValueByName(string Name) {
910
911    gdcmDictEntry * NewTag = GetDictEntryByName(Name);
912    if (!NewTag)
913       NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
914
915    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
916    if (!NewElVal) {
917       dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
918                   "failed to allocate gdcmElValue");
919       return (gdcmElValue*)0;
920    }
921    return NewElVal;
922 }  
923
924 /**
925  * \ingroup gdcmHeader
926  * \brief   Read the next tag but WITHOUT loading it's value
927  * @return  On succes the newly created ElValue, NULL on failure.      
928  */
929 gdcmElValue * gdcmHeader::ReadNextElement(void) {
930   
931    guint16 g,n;
932    gdcmElValue * NewElVal;
933    
934    g = ReadInt16();
935    n = ReadInt16();
936    if (errno == 1)
937       // We reached the EOF (or an error occured) and header parsing
938       // has to be considered as finished.
939       return (gdcmElValue *)0;
940    
941    NewElVal = NewElValueByNumber(g, n);
942    FindVR(NewElVal);
943    FindLength(NewElVal);
944    if (errno == 1)
945       // Call it quits
946       return (gdcmElValue *)0;
947    NewElVal->SetOffset(ftell(fp));
948    return NewElVal;
949 }
950
951 /**
952  * \ingroup gdcmHeader
953  * \brief   Apply some heuristics to predict wether the considered 
954  *          element value contains/represents an integer or not.
955  * @param   ElVal The element value on which to apply the predicate.
956  * @return  The result of the heuristical predicate.
957  */
958 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
959    guint16 group   = ElVal->GetGroup();
960    guint16 element = ElVal->GetElement();
961    string  vr      = ElVal->GetVR();
962    guint32 length  = ElVal->GetLength();
963
964    // When we have some semantics on the element we just read, and if we
965    // a priori know we are dealing with an integer, then we shall be
966    // able to swap it's element value properly.
967    if ( element == 0 )  {  // This is the group length of the group
968       if (length == 4)
969          return true;
970       else {
971          printf("Erroneous Group Length element length %d\n",length);
972                     
973          dbg.Error("gdcmHeader::IsAnInteger",
974                    "Erroneous Group Length element length.");     
975       }
976    }
977  
978    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
979       return true;
980    
981    return false;
982 }
983
984 /**
985  * \ingroup gdcmHeader
986  * \brief   Recover the offset (from the beginning of the file) of the pixels.
987  */
988 size_t gdcmHeader::GetPixelOffset(void) {
989    // If this file complies with the norm we should encounter the
990    // "Image Location" tag (0x0028,  0x0200). This tag contains the
991    // the group that contains the pixel data (hence the "Pixel Data"
992    // is found by indirection through the "Image Location").
993    // Inside the group pointed by "Image Location" the searched element
994    // is conventionally the element 0x0010 (when the norm is respected).
995    // When the "Image Location" is absent we default to group 0x7fe0.
996    guint16 grPixel;
997    guint16 numPixel;
998    string ImageLocation = GetPubElValByName("Image Location");
999    if ( ImageLocation == "gdcm::Unfound" ) {
1000       grPixel = 0x7fe0;
1001    } else {
1002       grPixel = (guint16) atoi( ImageLocation.c_str() );
1003    }
1004    if (grPixel != 0x7fe0)
1005       // This is a kludge for old dirty Philips imager.
1006       numPixel = 0x1010;
1007    else
1008       numPixel = 0x0010;
1009    gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1010                                                               numPixel);
1011    if (PixelElement)
1012       return PixelElement->GetOffset();
1013    else
1014       return 0;
1015 }
1016
1017 /**
1018  * \ingroup gdcmHeader
1019  * \brief   Searches both the public and the shadow dictionary (when they
1020  *          exist) for the presence of the DictEntry with given
1021  *          group and element. The public dictionary has precedence on the
1022  *          shadow one.
1023  * @param   group   group of the searched DictEntry
1024  * @param   element element of the searched DictEntry
1025  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1026  */
1027 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1028                                                  guint16 element) {
1029    gdcmDictEntry * found = (gdcmDictEntry*)0;
1030    if (!RefPubDict && !RefShaDict) {
1031       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1032                      "we SHOULD have a default dictionary");
1033    }
1034    if (RefPubDict) {
1035       found = RefPubDict->GetTagByNumber(group, element);
1036       if (found)
1037          return found;
1038    }
1039    if (RefShaDict) {
1040       found = RefShaDict->GetTagByNumber(group, element);
1041       if (found)
1042          return found;
1043    }
1044    return found;
1045 }
1046
1047 /**
1048  * \ingroup gdcmHeader
1049  * \brief   Searches both the public and the shadow dictionary (when they
1050  *          exist) for the presence of the DictEntry with given name.
1051  *          The public dictionary has precedence on the shadow one.
1052  * @param   Name name of the searched DictEntry
1053  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1054  */
1055 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1056    gdcmDictEntry * found = (gdcmDictEntry*)0;
1057    if (!RefPubDict && !RefShaDict) {
1058       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1059                      "we SHOULD have a default dictionary");
1060    }
1061    if (RefPubDict) {
1062       found = RefPubDict->GetTagByName(Name);
1063       if (found)
1064          return found;
1065    }
1066    if (RefShaDict) {
1067       found = RefShaDict->GetTagByName(Name);
1068       if (found)
1069          return found;
1070    }
1071    return found;
1072 }
1073
1074 /**
1075  * \ingroup gdcmHeader
1076  * \brief   Searches within the public dictionary for element value of
1077  *          a given tag.
1078  * @param   group Group of the researched tag.
1079  * @param   element Element of the researched tag.
1080  * @return  Corresponding element value when it exists, and the string
1081  *          "gdcm::Unfound" otherwise.
1082  */
1083 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1084    return PubElValSet.GetElValueByNumber(group, element);
1085 }
1086
1087 /**
1088  * \ingroup gdcmHeader
1089  * \brief   Searches within the public dictionary for element value
1090  *          representation of a given tag.
1091  *
1092  *          Obtaining the VR (Value Representation) might be needed by caller
1093  *          to convert the string typed content to caller's native type 
1094  *          (think of C++ vs Python). The VR is actually of a higher level
1095  *          of semantics than just the native C++ type.
1096  * @param   group Group of the researched tag.
1097  * @param   element Element of the researched tag.
1098  * @return  Corresponding element value representation when it exists,
1099  *          and the string "gdcm::Unfound" otherwise.
1100  */
1101 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1102    gdcmElValue* elem =  PubElValSet.GetElementByNumber(group, element);
1103    if ( !elem )
1104       return "gdcm::Unfound";
1105    return elem->GetVR();
1106 }
1107
1108 /**
1109  * \ingroup gdcmHeader
1110  * \brief   Searches within the public dictionary for element value of
1111  *          a given tag.
1112  * @param   TagName name of the researched element.
1113  * @return  Corresponding element value when it exists, and the string
1114  *          "gdcm::Unfound" otherwise.
1115  */
1116 string gdcmHeader::GetPubElValByName(string TagName) {
1117    return PubElValSet.GetElValueByName(TagName);
1118 }
1119
1120 /**
1121  * \ingroup gdcmHeader
1122  * \brief   Searches within the elements parsed with the public dictionary for
1123  *          the element value representation of a given tag.
1124  *
1125  *          Obtaining the VR (Value Representation) might be needed by caller
1126  *          to convert the string typed content to caller's native type 
1127  *          (think of C++ vs Python). The VR is actually of a higher level
1128  *          of semantics than just the native C++ type.
1129  * @param   TagName name of the researched element.
1130  * @return  Corresponding element value representation when it exists,
1131  *          and the string "gdcm::Unfound" otherwise.
1132  */
1133 string gdcmHeader::GetPubElValRepByName(string TagName) {
1134    gdcmElValue* elem =  PubElValSet.GetElementByName(TagName);
1135    if ( !elem )
1136       return "gdcm::Unfound";
1137    return elem->GetVR();
1138 }
1139
1140 /**
1141  * \ingroup gdcmHeader
1142  * \brief   Searches within elements parsed with the SHADOW dictionary 
1143  *          for the element value of a given tag.
1144  * @param   group Group of the researched tag.
1145  * @param   element Element of the researched tag.
1146  * @return  Corresponding element value representation when it exists,
1147  *          and the string "gdcm::Unfound" otherwise.
1148  */
1149 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1150    return ShaElValSet.GetElValueByNumber(group, element);
1151 }
1152
1153 /**
1154  * \ingroup gdcmHeader
1155  * \brief   Searches within the elements parsed with the SHADOW dictionary
1156  *          for the element value representation of a given tag.
1157  *
1158  *          Obtaining the VR (Value Representation) might be needed by caller
1159  *          to convert the string typed content to caller's native type 
1160  *          (think of C++ vs Python). The VR is actually of a higher level
1161  *          of semantics than just the native C++ type.
1162  * @param   group Group of the researched tag.
1163  * @param   element Element of the researched tag.
1164  * @return  Corresponding element value representation when it exists,
1165  *          and the string "gdcm::Unfound" otherwise.
1166  */
1167 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1168    gdcmElValue* elem =  ShaElValSet.GetElementByNumber(group, element);
1169    if ( !elem )
1170       return "gdcm::Unfound";
1171    return elem->GetVR();
1172 }
1173
1174 /**
1175  * \ingroup gdcmHeader
1176  * \brief   Searches within the elements parsed with the shadow dictionary
1177  *          for an element value of given tag.
1178  * @param   TagName name of the researched element.
1179  * @return  Corresponding element value when it exists, and the string
1180  *          "gdcm::Unfound" otherwise.
1181  */
1182 string gdcmHeader::GetShaElValByName(string TagName) {
1183    return ShaElValSet.GetElValueByName(TagName);
1184 }
1185
1186 /**
1187  * \ingroup gdcmHeader
1188  * \brief   Searches within the elements parsed with the shadow dictionary for
1189  *          the element value representation of a given tag.
1190  *
1191  *          Obtaining the VR (Value Representation) might be needed by caller
1192  *          to convert the string typed content to caller's native type 
1193  *          (think of C++ vs Python). The VR is actually of a higher level
1194  *          of semantics than just the native C++ type.
1195  * @param   TagName name of the researched element.
1196  * @return  Corresponding element value representation when it exists,
1197  *          and the string "gdcm::Unfound" otherwise.
1198  */
1199 string gdcmHeader::GetShaElValRepByName(string TagName) {
1200    gdcmElValue* elem =  ShaElValSet.GetElementByName(TagName);
1201    if ( !elem )
1202       return "gdcm::Unfound";
1203    return elem->GetVR();
1204 }
1205
1206 /**
1207  * \ingroup gdcmHeader
1208  * \brief   Searches within elements parsed with the public dictionary 
1209  *          and then within the elements parsed with the shadow dictionary
1210  *          for the element value of a given tag.
1211  * @param   group Group of the researched tag.
1212  * @param   element Element of the researched tag.
1213  * @return  Corresponding element value representation when it exists,
1214  *          and the string "gdcm::Unfound" otherwise.
1215  */
1216 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1217    string pub = GetPubElValByNumber(group, element);
1218    if (pub.length())
1219       return pub;
1220    return GetShaElValByNumber(group, element);
1221 }
1222
1223 /**
1224  * \ingroup gdcmHeader
1225  * \brief   Searches within elements parsed with the public dictionary 
1226  *          and then within the elements parsed with the shadow dictionary
1227  *          for the element value representation of a given tag.
1228  *
1229  *          Obtaining the VR (Value Representation) might be needed by caller
1230  *          to convert the string typed content to caller's native type 
1231  *          (think of C++ vs Python). The VR is actually of a higher level
1232  *          of semantics than just the native C++ type.
1233  * @param   group Group of the researched tag.
1234  * @param   element Element of the researched tag.
1235  * @return  Corresponding element value representation when it exists,
1236  *          and the string "gdcm::Unfound" otherwise.
1237  */
1238 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1239    string pub = GetPubElValRepByNumber(group, element);
1240    if (pub.length())
1241       return pub;
1242    return GetShaElValRepByNumber(group, element);
1243 }
1244
1245 /**
1246  * \ingroup gdcmHeader
1247  * \brief   Searches within elements parsed with the public dictionary 
1248  *          and then within the elements parsed with the shadow dictionary
1249  *          for the element value of a given tag.
1250  * @param   TagName name of the researched element.
1251  * @return  Corresponding element value when it exists,
1252  *          and the string "gdcm::Unfound" otherwise.
1253  */
1254 string gdcmHeader::GetElValByName(string TagName) {
1255    string pub = GetPubElValByName(TagName);
1256    if (pub.length())
1257       return pub;
1258    return GetShaElValByName(TagName);
1259 }
1260
1261 /**
1262  * \ingroup gdcmHeader
1263  * \brief   Searches within elements parsed with the public dictionary 
1264  *          and then within the elements parsed with the shadow dictionary
1265  *          for the element value representation of a given tag.
1266  *
1267  *          Obtaining the VR (Value Representation) might be needed by caller
1268  *          to convert the string typed content to caller's native type 
1269  *          (think of C++ vs Python). The VR is actually of a higher level
1270  *          of semantics than just the native C++ type.
1271  * @param   TagName name of the researched element.
1272  * @return  Corresponding element value representation when it exists,
1273  *          and the string "gdcm::Unfound" otherwise.
1274  */
1275 string gdcmHeader::GetElValRepByName(string TagName) {
1276    string pub = GetPubElValRepByName(TagName);
1277    if (pub.length())
1278       return pub;
1279    return GetShaElValRepByName(TagName);
1280 }
1281
1282 /**
1283  * \ingroup gdcmHeader
1284  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1285  *          through it's (group, element) and modifies it's content with
1286  *          the given value.
1287  * @param   content new value to substitute with
1288  * @param   group   group of the ElVal to modify
1289  * @param   element element of the ElVal to modify
1290  */
1291 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1292                                     guint16 element)
1293 {
1294    return (  PubElValSet.SetElValueByNumber (content, group, element) );
1295 }
1296
1297 /**
1298  * \ingroup gdcmHeader
1299  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1300  *          through tag name and modifies it's content with the given value.
1301  * @param   content new value to substitute with
1302  * @param   TagName name of the tag to be modified
1303  */
1304 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1305    return (  PubElValSet.SetElValueByName (content, TagName) );
1306 }
1307
1308 /**
1309  * \ingroup gdcmHeader
1310  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1311  *          through it's (group, element) and modifies it's length with
1312  *          the given value.
1313  * \warning Use with extreme caution.
1314  * @param   length new length to substitute with
1315  * @param   group   group of the ElVal to modify
1316  * @param   element element of the ElVal to modify
1317  * @return  1 on success, 0 otherwise.
1318  */
1319
1320 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1321                                     guint16 element) {
1322         return (  PubElValSet.SetElValueLengthByNumber (length, group, element) );
1323 }
1324
1325 /**
1326  * \ingroup gdcmHeader
1327  * \brief   Accesses an existing gdcmElValue in the ShaElValSet of this instance
1328  *          through it's (group, element) and modifies it's content with
1329  *          the given value.
1330  * @param   content new value to substitute with
1331  * @param   group   group of the ElVal to modify
1332  * @param   element element of the ElVal to modify
1333  * @return  1 on success, 0 otherwise.
1334  */
1335 int gdcmHeader::SetShaElValByNumber(string content,
1336                                     guint16 group, guint16 element) {
1337    return (  ShaElValSet.SetElValueByNumber (content, group, element) );
1338 }
1339
1340 /**
1341  * \ingroup gdcmHeader
1342  * \brief   Accesses an existing gdcmElValue in the ShaElValSet of this instance
1343  *          through tag name and modifies it's content with the given value.
1344  * @param   content new value to substitute with
1345  * @param   TagName name of the tag to be modified
1346  */
1347 int gdcmHeader::SetShaElValByName(string content, string TagName) {
1348    return (  ShaElValSet.SetElValueByName (content, TagName) );
1349 }
1350
1351 /**
1352  * \ingroup gdcmHeader
1353  * \brief   Parses the header of the file but WITHOUT loading element values.
1354  */
1355 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1356    gdcmElValue * newElValue = (gdcmElValue *)0;
1357    
1358    rewind(fp);
1359    CheckSwap();
1360    while ( (newElValue = ReadNextElement()) ) {
1361       SkipElementValue(newElValue);
1362       PubElValSet.Add(newElValue);
1363    }
1364 }
1365
1366 /**
1367  * \ingroup gdcmHeader
1368  * \brief   Retrieve the number of columns of image.
1369  * @return  The encountered size when found, 0 by default.
1370  */
1371 int gdcmHeader::GetXSize(void) {
1372    // We cannot check for "Columns" because the "Columns" tag is present
1373    // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1374    string StrSize = GetPubElValByNumber(0x0028,0x0011);
1375    if (StrSize == "gdcm::Unfound")
1376       return 0;
1377    return atoi(StrSize.c_str());
1378 }
1379
1380 /**
1381  * \ingroup gdcmHeader
1382  * \brief   Retrieve the number of lines of image.
1383  * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1384  * @return  The encountered size when found, 1 by default.
1385  */
1386 int gdcmHeader::GetYSize(void) {
1387    // We cannot check for "Rows" because the "Rows" tag is present
1388    // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1389    string StrSize = GetPubElValByNumber(0x0028,0x0010);
1390    if (StrSize != "gdcm::Unfound")
1391       return atoi(StrSize.c_str());
1392    if ( IsDicomV3() )
1393       return 0;
1394    else
1395       // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1396       // hence be a signal (1d image). So we default to 1:
1397       return 1;
1398 }
1399
1400 /**
1401  * \ingroup gdcmHeader
1402  * \brief   Retrieve the number of planes of volume or the number
1403  *          of frames of a multiframe.
1404  * \warning When present we consider the "Number of Frames" as the third
1405  *          dimension. When absent we consider the third dimension as
1406  *          being the "Planes" tag content.
1407  * @return  The encountered size when found, 1 by default.
1408  */
1409 int gdcmHeader::GetZSize(void) {
1410    // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1411    // as the third dimension.
1412    string StrSize = GetPubElValByNumber(0x0028,0x0008);
1413    if (StrSize != "gdcm::Unfound")
1414       return atoi(StrSize.c_str());
1415
1416    // We then consider the "Planes" entry as the third dimension [we
1417    // cannot retrieve by name since "Planes tag is present both in
1418    // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary]. 
1419    StrSize = GetPubElValByNumber(0x0028,0x0012);
1420    if (StrSize != "gdcm::Unfound")
1421       return atoi(StrSize.c_str());
1422    return 1;
1423 }
1424
1425 /**
1426  * \ingroup gdcmHeader
1427  * \brief   Build the Pixel Type of the image.
1428  *          Possible values are:
1429  *          - U8  unsigned  8 bit,
1430  *          - S8    signed  8 bit,
1431  *          - U16 unsigned 16 bit,
1432  *          - S16   signed 16 bit,
1433  *          - U32 unsigned 32 bit,
1434  *          - S32   signed 32 bit,
1435  * \warning 12 bit images appear as 16 bit.
1436  * @return 
1437  */
1438 string gdcmHeader::GetPixelType(void) {
1439    string BitsAlloc;
1440    BitsAlloc = GetElValByName("Bits Allocated");
1441    if (BitsAlloc == "gdcm::Unfound") {
1442       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1443       BitsAlloc = string("16");
1444    }
1445    if (BitsAlloc == "12")
1446       BitsAlloc = string("16");
1447
1448    string Signed;
1449    Signed = GetElValByName("Pixel Representation");
1450    if (Signed == "gdcm::Unfound") {
1451       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1452       BitsAlloc = string("0");
1453    }
1454    if (Signed == "0")
1455       Signed = string("U");
1456    else
1457       Signed = string("S");
1458
1459    return( BitsAlloc + Signed);
1460 }
1461
1462 /**
1463  * \ingroup gdcmHeader
1464  * \brief  This predicate, based on hopefully reasonnable heuristics,
1465  *         decides whether or not the current gdcmHeader was properly parsed
1466  *         and contains the mandatory information for being considered as
1467  *         a well formed and usable image.
1468  * @return true when gdcmHeader is the one of a reasonable Dicom file,
1469  *         false otherwise. 
1470  */
1471 bool gdcmHeader::IsReadable(void) {
1472    if (   GetElValByName("Image Dimensions") != "gdcm::Unfound"
1473       && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1474       return false;
1475    }
1476    if (  GetElValByName("Bits Allocated") == "gdcm::Unfound" )
1477       return false;
1478    if (  GetElValByName("Bits Stored") == "gdcm::Unfound" )
1479       return false;
1480    if (  GetElValByName("High Bit") == "gdcm::Unfound" )
1481       return false;
1482    if (  GetElValByName("Pixel Representation") == "gdcm::Unfound" )
1483       return false;
1484    return true;
1485 }
1486
1487 /**
1488  * \ingroup gdcmHeader
1489  * \brief   Small utility function that creates a new manually crafted
1490  *          (as opposed as read from the file) gdcmElValue with user
1491  *          specified name and adds it to the public tag hash table.
1492  * \note    A fake TagKey is generated so the PubDict can keep it's coherence.
1493  * @param   NewTagName The name to be given to this new tag.
1494  * @param   VR The Value Representation to be given to this new tag.
1495  * @ return The newly hand crafted Element Value.
1496  */
1497 gdcmElValue* gdcmHeader::NewManualElValToPubDict(string NewTagName, string VR) {
1498    gdcmElValue* NewElVal = (gdcmElValue*)0;
1499    guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
1500    guint32 FreeElem = 0;
1501    gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1502
1503    FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1504    if (FreeElem == UINT32_MAX) {
1505       dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1506                      "Group 0xffff in Public Dict is full");
1507       return (gdcmElValue*)0;
1508    }
1509    NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1510                                 VR, "GDCM", NewTagName);
1511    NewElVal = new gdcmElValue(NewEntry);
1512    PubElValSet.Add(NewElVal);
1513    return NewElVal;
1514
1515 }
1516
1517 /**
1518  * \ingroup gdcmHeader
1519  * \brief   Loads the element values of all the elements present in the
1520  *          public tag based hash table.
1521  */
1522 void gdcmHeader::LoadElements(void) {
1523    rewind(fp);   
1524    TagElValueHT ht = PubElValSet.GetTagHt();
1525    for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1526       LoadElementValue(tag->second);
1527       }
1528 }
1529
1530 void gdcmHeader::PrintPubElVal(ostream & os) {
1531    PubElValSet.Print(os);
1532 }
1533
1534 void gdcmHeader::PrintPubDict(ostream & os) {
1535    RefPubDict->Print(os);
1536 }
1537
1538 int gdcmHeader::Write(FILE * fp, FileType type) {
1539    return PubElValSet.Write(fp, type);
1540 }