]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
* python/demo/*.py load.py extracted from test.py. Added explore.py
[gdcm.git] / src / gdcmHeader.cxx
1 #include "gdcm.h"
2 #include <stdio.h>
3 // For nthos:
4 #ifdef _MSC_VER
5 #include <winsock.h>
6 #else
7 #include <netinet/in.h>
8 #endif
9 #include <cctype>               // for isalpha
10 #include <map>
11 #include <sstream>
12 #include "gdcmUtil.h"
13
14 #define HEADER_LENGHT_TO_READ 256 // on ne lit plus que le debut
15
16 namespace Error {
17         struct FileReadError {
18                 FileReadError(FILE* fp, const char* Mesg) {
19                         if (feof(fp))
20                                 dbg.Verbose(1, "EOF encountered :", Mesg);
21                         if (ferror(fp))
22                                 dbg.Verbose(1, "Error on reading :", Mesg);
23                 }
24         };
25 }
26
27 //FIXME: this looks dirty to me...
28 #define str2num(str, typeNum) *((typeNum *)(str))
29
30 VRHT * gdcmHeader::dicom_vr = (VRHT*)0;
31 gdcmDictSet* gdcmHeader::Dicts = new gdcmDictSet();
32
33 void gdcmHeader::Initialise(void) {
34         if (!gdcmHeader::dicom_vr)
35                 InitVRDict();
36         RefPubDict = gdcmHeader::Dicts->GetDefaultPublicDict();
37         RefShaDict = (gdcmDict*)0;
38 }
39
40 gdcmHeader::gdcmHeader (const char* InFilename) {
41         SetMaxSizeLoadElementValue(1024);
42         filename = InFilename;
43         Initialise();
44         fp=fopen(InFilename,"rw");
45         dbg.Error(!fp, "gdcmHeader::gdcmHeader cannot open file", InFilename);
46         ParseHeader();
47 }
48
49 gdcmHeader::~gdcmHeader (void) {
50         fclose(fp);
51         return;
52 }
53
54 void gdcmHeader::InitVRDict (void) {
55         if (dicom_vr) {
56                 dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
57                 return;
58         }
59         VRHT *vr = new VRHT;
60         (*vr)["AE"] = "Application Entity";       // At most 16 bytes
61         (*vr)["AS"] = "Age String";               // Exactly 4 bytes
62         (*vr)["AT"] = "Attribute Tag";            // 2 16-bit unsigned short integers
63         (*vr)["CS"] = "Code String";              // At most 16 bytes
64         (*vr)["DA"] = "Date";                     // Exactly 8 bytes
65         (*vr)["DS"] = "Decimal String";           // At most 16 bytes
66         (*vr)["DT"] = "Date Time";                // At most 26 bytes
67         (*vr)["FL"] = "Floating Point Single";    // 32-bit IEEE 754:1985 float
68         (*vr)["FD"] = "Floating Point Double";    // 64-bit IEEE 754:1985 double
69         (*vr)["IS"] = "Integer String";           // At most 12 bytes
70         (*vr)["LO"] = "Long String";              // At most 64 chars
71         (*vr)["LT"] = "Long Text";                // At most 10240 chars
72         (*vr)["OB"] = "Other Byte String";        // String of bytes (vr independant)
73         (*vr)["OW"] = "Other Word String";        // String of 16-bit words (vr dep)
74         (*vr)["PN"] = "Person Name";              // At most 64 chars
75         (*vr)["SH"] = "Short String";             // At most 16 chars
76         (*vr)["SL"] = "Signed Long";              // Exactly 4 bytes
77         (*vr)["SQ"] = "Sequence of Items";        // Not Applicable
78         (*vr)["SS"] = "Signed Short";             // Exactly 2 bytes
79         (*vr)["ST"] = "Short Text";               // At most 1024 chars
80         (*vr)["TM"] = "Time";                     // At most 16 bytes
81         (*vr)["UI"] = "Unique Identifier";        // At most 64 bytes
82         (*vr)["UL"] = "Unsigned Long ";           // Exactly 4 bytes
83         (*vr)["UN"] = "Unknown";                  // Any length of bytes
84         (*vr)["US"] = "Unsigned Short ";          // Exactly 2 bytes
85         (*vr)["UT"] = "Unlimited Text";           // At most 2^32 -1 chars
86    dicom_vr = vr;       
87 }
88
89 /**
90  * \ingroup gdcmHeader
91  * \brief   La seule maniere sure que l'on aie pour determiner 
92  *          si on est en   LITTLE_ENDIAN,       BIG-ENDIAN, 
93  *          BAD-LITTLE-ENDIAN, BAD-BIG-ENDIAN
94  *          est de trouver l'element qui donne la longueur d'un 'GROUP'
95  *          (on sait que la longueur de cet element vaut 0x00000004)
96  *          et de regarder comment cette longueur est codee en memoire  
97  *          
98  *          Le probleme vient de ce que parfois, il n'y en a pas ...
99  *          
100  *          On fait alors le pari qu'on a a faire a du LITTLE_ENDIAN propre.
101  *          (Ce qui est la norme -pas respectee- depuis ACR-NEMA)
102  *          Si ce n'est pas le cas, on ne peut rien faire.
103  *
104  *          (il faudrait avoir des fonctions auxquelles 
105  *          on passe le code Swap en parametre, pour faire des essais 'manuels')
106  */
107 void gdcmHeader::CheckSwap()
108 {
109         guint32  s;
110         guint32  x=4;  // x : pour ntohs
111         bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
112          
113         int lgrLue;
114         char * entCur;
115         char deb[HEADER_LENGHT_TO_READ];
116          
117         // First, compare HostByteOrder and NetworkByteOrder in order to
118         // determine if we shall need to swap bytes (i.e. the Endian type).
119         if (x==ntohs(x))
120                 net2host = true;
121         else
122                 net2host = false;
123         
124         // The easiest case is the one of a DICOM header, since it possesses a
125         // file preamble where it suffice to look for the sting "DICM".
126         lgrLue = fread(deb, 1, HEADER_LENGHT_TO_READ, fp);
127         
128         entCur = deb + 128;
129         if(memcmp(entCur, "DICM", (size_t)4) == 0) {
130                 filetype = TrueDicom;
131                 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
132         } else {
133                 filetype = Unknown;
134                 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
135         }
136
137         if(filetype == TrueDicom) {
138                 // Next, determine the value representation (VR). Let's skip to the
139                 // first element (0002, 0000) and check there if we find "UL", in
140                 // which case we (almost) know it is explicit VR.
141                 // WARNING: if it happens to be implicit VR then what we will read
142                 // is the length of the group. If this ascii representation of this
143                 // length happens to be "UL" then we shall believe it is explicit VR.
144                 // FIXME: in order to fix the above warning, we could read the next
145                 // element value (or a couple of elements values) in order to make
146                 // sure we are not commiting a big mistake.
147                 // We need to skip :
148                 // * the 128 bytes of File Preamble (often padded with zeroes),
149                 // * the 4 bytes of "DICM" string,
150                 // * the 4 bytes of the first tag (0002, 0000),
151                 // i.e. a total of  136 bytes.
152                 entCur = deb + 136;
153                 if(memcmp(entCur, "UL", (size_t)2) == 0) {
154                         filetype = ExplicitVR;
155                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
156                                     "explicit Value Representation");
157                 } else {
158                         filetype = ImplicitVR;
159                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
160                                     "not an explicit Value Representation");
161                 }
162
163                 if (net2host) {
164                         sw = 4321;
165                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
166                                        "HostByteOrder != NetworkByteOrder");
167                 } else {
168                         sw = 0;
169                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
170                                        "HostByteOrder = NetworkByteOrder");
171                 }
172                 
173                 // Position the file position indicator at first tag (i.e.
174                 // after the file preamble and the "DICM" string).
175                 rewind(fp);
176                 fseek (fp, 132L, SEEK_SET);
177                 return;
178         } // End of TrueDicom
179
180         // Alas, this is not a DicomV3 file and whatever happens there is no file
181         // preamble. We can reset the file position indicator to where the data
182         // is (i.e. the beginning of the file).
183         rewind(fp);
184
185         // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
186         // By clean we mean that the length of the first tag is written down.
187         // If this is the case and since the length of the first group HAS to be
188         // four (bytes), then determining the proper swap code is straightforward.
189
190         entCur = deb + 4;
191         s = str2num(entCur, guint32);
192         
193         switch (s) {
194         case 0x00040000 :
195                 sw = 3412;
196                 filetype = ACR;
197                 return;
198         case 0x04000000 :
199                 sw = 4321;
200                 filetype = ACR;
201                 return;
202         case 0x00000400 :
203                 sw = 2143;
204                 filetype = ACR;
205                 return;
206         case 0x00000004 :
207                 sw = 0;
208                 filetype = ACR;
209                 return;
210         default :
211                 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
212                                "ACE/NEMA unfound swap info (time to raise bets)");
213         }
214
215         // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
216         // It is time for despaired wild guesses. So, let's assume this file
217         // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
218         // not present. Then the only info we have is the net2host one.
219         //FIXME  Si c'est du RAW, ca degagera + tard
220         
221         if (! net2host )
222                 sw = 0;
223         else
224                 sw = 4321;
225         return;
226 }
227
228 void gdcmHeader::SwitchSwapToBigEndian(void) {
229         dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
230                        "Switching to BigEndian mode.");
231         if ( sw == 0    ) {
232                 sw = 4321;
233                 return;
234         }
235         if ( sw == 4321 ) {
236                 sw = 0;
237                 return;
238         }
239         if ( sw == 3412 ) {
240                 sw = 2143;
241                 return;
242         }
243         if ( sw == 2143 )
244                 sw = 3412;
245 }
246
247 /**
248  * \ingroup   gdcmHeader
249  * \brief     recupere la longueur d'un champ DICOM.
250  *            Preconditions:
251  *            1/ le fichier doit deja avoir ete ouvert,
252  *            2/ CheckSwap() doit avoir ete appele
253  *            3/ la  partie 'group'  ainsi que la  partie 'elem' 
254  *               de l'acr_element doivent avoir ete lues.
255  *
256  *            ACR-NEMA : we allways get
257  *                 GroupNumber   (2 Octets) 
258  *                 ElementNumber (2 Octets) 
259  *                 ElementSize   (4 Octets)
260  *            DICOM en implicit Value Representation :
261  *                 GroupNumber   (2 Octets) 
262  *                 ElementNumber (2 Octets) 
263  *                 ElementSize   (4 Octets)
264  *
265  *            DICOM en explicit Value Representation :
266  *                 GroupNumber         (2 Octets) 
267  *                 ElementNumber       (2 Octets) 
268  *                 ValueRepresentation (2 Octets) 
269  *                 ElementSize         (2 Octets)
270  *
271  *            ATTENTION : dans le cas ou ValueRepresentation = OB, OW, SQ, UN
272  *                 GroupNumber         (2 Octets) 
273  *                 ElementNumber       (2 Octets) 
274  *                 ValueRepresentation (2 Octets)
275  *                 zone reservee       (2 Octets) 
276  *                 ElementSize         (4 Octets)
277  *
278  * @param sw  code swap
279  * @param skippedLength  pointeur sur nombre d'octets que l'on a saute qd
280  *                       la lecture est finie
281  * @param longueurLue    pointeur sur longueur (en nombre d'octets) 
282  *                       effectivement lue
283  * @return               longueur retenue pour le champ 
284  */
285
286 void gdcmHeader::FindVR( ElValue *ElVal) {
287         if (filetype != ExplicitVR)
288                 return;
289
290         char VR[3];
291         string vr;
292         int lgrLue;
293         long PositionOnEntry = ftell(fp);
294         // Warning: we believe this is explicit VR (Value Representation) because
295         // we used a heuristic that found "UL" in the first tag. Alas this
296         // doesn't guarantee that all the tags will be in explicit VR. In some
297         // cases (see e-film filtered files) one finds implicit VR tags mixed
298         // within an explicit VR file. Hence we make sure the present tag
299         // is in explicit VR and try to fix things if it happens not to be
300         // the case.
301         bool RealExplicit = true;
302         
303         lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
304         VR[2]=0;
305         vr = string(VR);
306                 
307         // Assume we are reading a falsely explicit VR file i.e. we reached
308         // a tag where we expect reading a VR but are in fact we read the
309         // first to bytes of the length. Then we will interogate (through find)
310         // the dicom_vr dictionary with oddities like "\004\0" which crashes
311         // both GCC and VC++ implentations of the STL map. Hence when the
312         // expected VR read happens to be non-ascii characters we consider
313         // we hit falsely explicit VR tag.
314
315         if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
316                 RealExplicit = false;
317
318         // CLEANME searching the dicom_vr at each occurence is expensive.
319         // PostPone this test in an optional integrity check at the end
320         // of parsing or only in debug mode.
321         if ( RealExplicit && !dicom_vr->count(vr) )
322                 RealExplicit = false;
323
324         if ( RealExplicit ) {
325                 if ( ElVal->IsVrUnknown() ) {
326                         // When not a dictionary entry, we can safely overwrite the vr.
327                         ElVal->SetVR(vr);
328                         return; 
329                 }
330                 if ( ElVal->GetVR() == vr ) {
331                         // The vr we just read and the dictionary agree. Nothing to do.
332                         return;
333                 }
334                 // The vr present in the file and the dictionary disagree. We assume
335                 // the file writer knew best and use the vr of the file. Since it would
336                 // be unwise to overwrite the vr of a dictionary (since it would
337                 // compromise it's next user), we need to clone the actual DictEntry
338                 // and change the vr for the read one.
339                 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
340                                            ElVal->GetElement(),
341                                            vr,
342                                            "FIXME",
343                                            ElVal->GetName());
344                 ElVal->SetDictEntry(NewTag);
345                 return; 
346         }
347         
348         // We thought this was explicit VR, but we end up with an
349         // implicit VR tag. Let's backtrack.
350         dbg.Verbose(1, "gdcmHeader::FindVR:", "Falsely explicit vr file");
351         fseek(fp, PositionOnEntry, SEEK_SET);
352         // When this element is known in the dictionary we shall use, e.g. for
353         // the semantics (see  the usage of IsAnInteger), the vr proposed by the
354         // dictionary entry. Still we have to flag the element as implicit since
355         // we know now our assumption on expliciteness is not furfilled.
356         // avoid  .
357         if ( ElVal->IsVrUnknown() )
358                 ElVal->SetVR("Implicit");
359         ElVal->SetImplicitVr();
360 }
361
362 /**
363  * \ingroup gdcmHeader
364  * \brief   Determines if the Transfer Syntax was allready encountered
365  *          and if it corresponds to a Big Endian one.
366  *
367  * @return  True when big endian found. False in all other cases.
368  */
369 bool gdcmHeader::IsBigEndianTransferSyntax(void) {
370         ElValue* Element = PubElVals.GetElement(0x0002, 0x0010);
371         if ( !Element )
372                 return false;
373         LoadElementValueSafe(Element);
374         string Transfer = Element->GetValue();
375         if ( Transfer == "1.2.840.10008.1.2.2" )
376                 return true;
377         return false;
378 }
379
380 void gdcmHeader::FixFoundLength(ElValue * ElVal, guint32 FoudLength) {
381         // Heuristic: a final fix.
382         if ( FoudLength == 0xffffffff)
383                 FoudLength = 0;
384         ElVal->SetLength(FoudLength);
385 }
386
387 void gdcmHeader::FindLength( ElValue * ElVal) {
388         guint16 element = ElVal->GetElement();
389         string  vr      = ElVal->GetVR();
390         guint16 length16;
391         
392         if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
393
394                 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
395                         // The following reserved two bytes (see PS 3.5-2001, section
396                         // 7.1.2 Data element structure with explicit vr p27) must be
397                         // skipped before proceeding on reading the length on 4 bytes.
398                         fseek(fp, 2L, SEEK_CUR);
399                         FixFoundLength(ElVal, ReadInt32());
400                         return;
401                 }
402
403                 // Length is encoded on 2 bytes.
404                 length16 = ReadInt16();
405                 
406                 // We can tell the current file is encoded in big endian (like
407                 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
408                 // and it's value is the one of the encoding of a bie endian file.
409                 // In order to deal with such big endian encoded files, we have
410                 // (at least) two strategies:
411                 // * when we load the "Transfer Syntax" tag with value of big endian
412                 //   encoding, we raise the proper flags. Then we wait for the end
413                 //   of the META group (0x0002) among which is "Transfer Syntax",
414                 //   before switching the swap code to big endian. We have to postpone
415                 //   the switching of the swap code since the META group is fully encoded
416                 //   in little endian, and big endian coding only starts at the next
417                 //   group. The corresponding code can be hard to analyse and adds
418                 //   many additional unnecessary tests for regular tags.
419                 // * the second strategy consist to wait for trouble, that shall appear
420                 //   when we find the first group with big endian encoding. This is
421                 //   easy to detect since the length of a "Group Length" tag (the
422                 //   ones with zero as element number) has to be of 4 (0x0004). When we
423                 //   encouter 1024 (0x0400) chances are the encoding changed and we
424                 //   found a group with big endian encoding.
425                 // We shall use this second strategy. In order make sure that we
426                 // can interpret the presence of an apparently big endian encoded
427                 // length of a "Group Length" without committing a big mistake, we
428                 // add an additional check: we look in the allready parsed elements
429                 // for the presence of a "Transfer Syntax" whose value has to be "big
430                 // endian encoding". When this is the case, chances are we got our
431                 // hands on a big endian encoded file: we switch the swap code to
432                 // big endian and proceed...
433                 if ( (element  == 0) && (length16 == 1024) ) {
434                         if ( ! IsBigEndianTransferSyntax() )
435                                 throw Error::FileReadError(fp, "gdcmHeader::FindLength");
436                         length16 = 4;
437                         SwitchSwapToBigEndian();
438                         // Restore the unproperly loaded values i.e. the group, the element
439                         // and the dictionary entry depending on them.
440                         guint16 CorrectGroup   = SwapShort(ElVal->GetGroup());
441                         guint16 CorrectElem    = SwapShort(ElVal->GetElement());
442                         gdcmDictEntry * NewTag = IsInDicts(CorrectGroup, CorrectElem);
443                         if (!NewTag) {
444                                 // This correct tag is not in the dictionary. Create a new one.
445                                 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
446                         }
447                         // FIXME this can create a memory leaks on the old entry that be
448                         // left unreferenced.
449                         ElVal->SetDictEntry(NewTag);
450                 }
451                  
452                 // Heuristic: well some files are really ill-formed.
453                 if ( length16 == 0xffff) {
454                         length16 = 0;
455                         dbg.Verbose(0, "gdcmHeader::FindLength",
456                                     "Erroneous element length fixed.");
457                 }
458                 FixFoundLength(ElVal, (guint32)length16);
459                 return;
460         }
461
462         // Either implicit VR or a non DICOM conformal (see not below) explicit
463         // VR that ommited the VR of (at least) this element. Farts happen.
464         // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
465         // on Data elements "Implicit and Explicit VR Data Elements shall
466         // not coexist in a Data Set and Data Sets nested within it".]
467         // Length is on 4 bytes.
468         FixFoundLength(ElVal, ReadInt32());
469 }
470
471 /**
472  * \ingroup gdcmHeader
473  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
474  *          processor order.
475  *
476  * @return  The suggested integer.
477  */
478 guint32 gdcmHeader::SwapLong(guint32 a) {
479         // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
480         switch (sw) {
481         case    0 :
482                 break;
483         case 4321 :
484                 a=(   ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000)    | 
485                       ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
486                 break;
487         
488         case 3412 :
489                 a=(   ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
490                 break;
491         
492         case 2143 :
493                 a=(    ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
494                 break;
495         default :
496                 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
497                 a=0;
498         }
499         return(a);
500 }
501
502 /**
503  * \ingroup gdcmHeader
504  * \brief   Swaps the bytes so they agree with the processor order
505  * @return  The properly swaped 16 bits integer.
506  */
507 guint16 gdcmHeader::SwapShort(guint16 a) {
508         if ( (sw==4321)  || (sw==2143) )
509                 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
510         return (a);
511 }
512
513 void gdcmHeader::SkipElementValue(ElValue * ElVal) {
514         //FIXME don't dump the returned value
515         (void)fseek(fp, (long)ElVal->GetLength(), SEEK_CUR);
516 }
517
518 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
519         if (NewSize < 0)
520                 return;
521         if ((guint32)NewSize >= (guint32)0xffffffff) {
522                 MaxSizeLoadElementValue = 0xffffffff;
523                 return;
524         }
525         MaxSizeLoadElementValue = NewSize;
526 }
527
528 /**
529  * \ingroup       gdcmHeader
530  * \brief         Loads the element if it's size is not to big.
531  * @param ElVal   Element whose value shall be loaded. 
532  * @param MaxSize Size treshold above which the element value is not
533  *                loaded in memory. The element value is allways loaded
534  *                when MaxSize is equal to UINT32_MAX.
535  * @return  
536  */
537 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
538         size_t item_read;
539         guint16 group  = ElVal->GetGroup();
540         guint16 elem   = ElVal->GetElement();
541         string  vr     = ElVal->GetVR();
542         guint32 length = ElVal->GetLength();
543         bool SkipLoad  = false;
544
545         fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
546         
547         // Sequences not treated yet !
548         if( vr == "SQ" )
549                 SkipLoad = true;
550
551         // Heuristic : a sequence "contains" a set of tags (called items). It looks
552         // like the last tag of a sequence (the one that terminates the sequence)
553         // has a group of 0xfffe (with a dummy length).
554         if( group == 0xfffe )
555                 SkipLoad = true;
556
557         // The group length doesn't represent data to be loaded in memory, since
558         // each element of the group shall be loaded individualy.
559         if( elem == 0 )
560                 SkipLoad = true;
561
562         if ( SkipLoad ) {
563                           // FIXME the following skip is not necessary
564                 SkipElementValue(ElVal);
565                 ElVal->SetLength(0);
566                 ElVal->SetValue("gdcm::Skipped");
567                 return;
568         }
569
570         // When the length is zero things are easy:
571         if ( length == 0 ) {
572                 ElVal->SetValue("");
573                 return;
574         }
575
576         // Values bigger than specified are not loaded.
577         if (length > MaxSizeLoadElementValue) {
578                 ostringstream s;
579                 s << "gdcm::NotLoaded.";
580                 s << " Address:" << (long)ElVal->GetOffset();
581                 s << " Length:"  << ElVal->GetLength();
582                 //mesg += " Length:"  + ElVal->GetLength();
583                 ElVal->SetValue(s.str());
584                 return;
585         }
586         
587         // When an integer is expected, read and convert the following two or
588         // four bytes properly i.e. as an integer as opposed to a string.
589         if ( IsAnInteger(ElVal) ) {
590                 guint32 NewInt;
591                 if( length == 2 ) {
592                         NewInt = ReadInt16();
593                 } else if( length == 4 ) {
594                         NewInt = ReadInt32();
595                 } else
596                         dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
597                 
598                 //FIXME: make the following an util fonction
599                 ostringstream s;
600                 s << NewInt;
601                 ElVal->SetValue(s.str());
602                 return;
603         }
604         
605         // FIXME The exact size should be length if we move to strings or whatever
606         char* NewValue = (char*)g_malloc(length+1);
607         if( !NewValue) {
608                 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
609                 return;
610         }
611         NewValue[length]= 0;
612         
613         item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
614         if ( item_read != 1 ) {
615                 g_free(NewValue);
616                 Error::FileReadError(fp, "gdcmHeader::LoadElementValue");
617                 ElVal->SetValue("gdcm::UnRead");
618                 return;
619         }
620         ElVal->SetValue(NewValue);
621 }
622
623 /**
624  * \ingroup       gdcmHeader
625  * \brief         Loads the element while preserving the current
626  *                underlying file position indicator as opposed to
627  *                to LoadElementValue that modifies it.
628  * @param ElVal   Element whose value shall be loaded. 
629  * @return  
630  */
631 void gdcmHeader::LoadElementValueSafe(ElValue * ElVal) {
632         long PositionOnEntry = ftell(fp);
633         LoadElementValue(ElVal);
634         fseek(fp, PositionOnEntry, SEEK_SET);
635 }
636
637
638 guint16 gdcmHeader::ReadInt16(void) {
639         guint16 g;
640         size_t item_read;
641         item_read = fread (&g, (size_t)2,(size_t)1, fp);
642         if ( item_read != 1 )
643                 throw Error::FileReadError(fp, "gdcmHeader::ReadInt16");
644         g = SwapShort(g);
645         return g;
646 }
647
648 guint32 gdcmHeader::ReadInt32(void) {
649         guint32 g;
650         size_t item_read;
651         item_read = fread (&g, (size_t)4,(size_t)1, fp);
652         if ( item_read != 1 )
653                 throw Error::FileReadError(fp, "gdcmHeader::ReadInt32");
654         g = SwapLong(g);
655         return g;
656 }
657
658 /**
659  * \ingroup gdcmHeader
660  * \brief   Read the next tag without loading it's value
661  * @return  On succes the newly created ElValue, NULL on failure.      
662  */
663
664 ElValue * gdcmHeader::ReadNextElement(void) {
665         guint16 g;
666         guint16 n;
667         ElValue * NewElVal;
668         
669         try {
670                 g = ReadInt16();
671                 n = ReadInt16();
672         }
673         catch ( Error::FileReadError ) {
674                 // We reached the EOF (or an error occured) and header parsing
675                 // has to be considered as finished.
676                 return (ElValue *)0;
677         }
678
679         // Find out if the tag we encountered is in the dictionaries:
680         gdcmDictEntry * NewTag = IsInDicts(g, n);
681         if (!NewTag)
682                 NewTag = new gdcmDictEntry(g, n);
683
684         NewElVal = new ElValue(NewTag);
685         if (!NewElVal) {
686                 dbg.Verbose(1, "ReadNextElement: failed to allocate ElValue");
687                 return (ElValue*)0;
688         }
689
690         FindVR(NewElVal);
691         try { FindLength(NewElVal); }
692         catch ( Error::FileReadError ) { // Call it quits
693                 return (ElValue *)0;
694         }
695         NewElVal->SetOffset(ftell(fp));
696         return NewElVal;
697 }
698
699 bool gdcmHeader::IsAnInteger(ElValue * ElVal) {
700         guint16 group   = ElVal->GetGroup();
701         guint16 element = ElVal->GetElement();
702         string  vr      = ElVal->GetVR();
703         guint32 length  = ElVal->GetLength();
704
705         // When we have some semantics on the element we just read, and if we
706         // a priori know we are dealing with an integer, then we shall be
707         // able to swap it's element value properly.
708         if ( element == 0 )  {  // This is the group length of the group
709                 if (length == 4)
710                         return true;
711                 else
712                         dbg.Error("gdcmHeader::IsAnInteger",
713                                   "Erroneous Group Length element length.");
714         }
715         
716         if ( group % 2 != 0 )
717                 // We only have some semantics on documented elements, which are
718                 // the even ones.
719                 return false;
720         
721         if ( (length != 4) && ( length != 2) )
722                 // Swapping only make sense on integers which are 2 or 4 bytes long.
723                 return false;
724         
725         if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
726                 return true;
727         
728         if ( (group == 0x0028) && (element == 0x0005) )
729                 // This tag is retained from ACR/NEMA
730                 // CHECKME Why should "Image Dimensions" be a single integer ?
731                 return true;
732         
733         if ( (group == 0x0028) && (element == 0x0200) )
734                 // This tag is retained from ACR/NEMA
735                 return true;
736         
737         return false;
738 }
739
740 /**
741  * \ingroup gdcmHeader
742  * \brief   Recover the offset (from the beginning of the file) of the pixels.
743  */
744 size_t gdcmHeader::GetPixelOffset(void) {
745         // If this file complies with the norm we should encounter the
746         // "Image Location" tag (0x0028,  0x0200). This tag contains the
747         // the group that contains the pixel data (hence the "Pixel Data"
748         // is found by indirection through the "Image Location").
749         // Inside the group pointed by "Image Location" the searched element
750         // is conventionally the element 0x0010 (when the norm is respected).
751         //    When the "Image Location" is absent we default to group 0x7fe0.
752         guint16 grPixel;
753         guint16 numPixel;
754         string ImageLocation = GetPubElValByName("Image Location");
755         if ( ImageLocation == "UNFOUND" ) {
756                 grPixel = 0x7FE0;
757         } else {
758                 grPixel = (guint16) atoi( ImageLocation.c_str() );
759         }
760         if (grPixel != 0x7fe0)
761                 // FIXME is this still necessary ?
762                 // Now, this looks like an old dirty fix for Philips imager
763                 numPixel = 0x1010;
764         else
765                 numPixel = 0x0010;
766         ElValue* PixelElement = PubElVals.GetElement(grPixel, numPixel);
767         if (PixelElement)
768                 return PixelElement->GetOffset();
769         else
770                 return 0;
771 }
772
773 gdcmDictEntry * gdcmHeader::IsInDicts(guint32 group, guint32 element) {
774         gdcmDictEntry * found = (gdcmDictEntry*)0;
775         if (!RefPubDict && !RefShaDict) {
776                 //FIXME build a default dictionary !
777                 printf("FIXME in gdcmHeader::IsInDicts\n");
778         }
779         if (RefPubDict) {
780                 found = RefPubDict->GetTag(group, element);
781                 if (found)
782                         return found;
783         }
784         if (RefShaDict) {
785                 found = RefShaDict->GetTag(group, element);
786                 if (found)
787                         return found;
788         }
789         return found;
790 }
791
792 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
793         return PubElVals.GetElValue(group, element);
794 }
795
796 string gdcmHeader::GetPubElValByName(string TagName) {
797         return PubElVals.GetElValue(TagName);
798 }
799
800 /**
801  * \ingroup gdcmHeader
802  * \brief   Parses the header of the file but does NOT load element values.
803  */
804 void gdcmHeader::ParseHeader(void) {
805         ElValue * newElValue = (ElValue *)0;
806         
807         rewind(fp);
808         CheckSwap();
809         while ( (newElValue = ReadNextElement()) ) {
810                 SkipElementValue(newElValue);
811                 PubElVals.Add(newElValue);
812         }
813 }
814
815 /**
816  * \ingroup gdcmHeader
817  * \brief   Loads the element values of all the elements present in the
818  *          public tag based hash table.
819  */
820 void gdcmHeader::LoadElements(void) {
821         rewind(fp);    
822         TagElValueHT ht = PubElVals.GetTagHt();
823         for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag)
824                 LoadElementValue(tag->second);
825 }
826
827 void gdcmHeader::PrintPubElVal(ostream & os) {
828         PubElVals.Print(os);
829 }
830
831 void gdcmHeader::PrintPubDict(ostream & os) {
832         RefPubDict->Print(os);
833 }