]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
* src/gdcm.h and gdcmHeader.cxx gdcm no longer loads all the elements
[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::FindLength", "Switching to BigEndian mode.");
230         if ( sw == 0    ) {
231                 sw = 4321;
232                 return;
233         }
234         if ( sw == 4321 ) {
235                 sw = 0;
236                 return;
237         }
238         if ( sw == 3412 ) {
239                 sw = 2143;
240                 return;
241         }
242         if ( sw == 2143 )
243                 sw = 3412;
244 }
245
246 /**
247  * \ingroup   gdcmHeader
248  * \brief     recupere la longueur d'un champ DICOM.
249  *            Preconditions:
250  *            1/ le fichier doit deja avoir ete ouvert,
251  *            2/ CheckSwap() doit avoir ete appele
252  *            3/ la  partie 'group'  ainsi que la  partie 'elem' 
253  *               de l'acr_element doivent avoir ete lues.
254  *
255  *            ACR-NEMA : we allways get
256  *                 GroupNumber   (2 Octets) 
257  *                 ElementNumber (2 Octets) 
258  *                 ElementSize   (4 Octets)
259  *            DICOM en implicit Value Representation :
260  *                 GroupNumber   (2 Octets) 
261  *                 ElementNumber (2 Octets) 
262  *                 ElementSize   (4 Octets)
263  *
264  *            DICOM en explicit Value Representation :
265  *                 GroupNumber         (2 Octets) 
266  *                 ElementNumber       (2 Octets) 
267  *                 ValueRepresentation (2 Octets) 
268  *                 ElementSize         (2 Octets)
269  *
270  *            ATTENTION : dans le cas ou ValueRepresentation = OB, OW, SQ, UN
271  *                 GroupNumber         (2 Octets) 
272  *                 ElementNumber       (2 Octets) 
273  *                 ValueRepresentation (2 Octets)
274  *                 zone reservee       (2 Octets) 
275  *                 ElementSize         (4 Octets)
276  *
277  * @param sw  code swap
278  * @param skippedLength  pointeur sur nombre d'octets que l'on a saute qd
279  *                       la lecture est finie
280  * @param longueurLue    pointeur sur longueur (en nombre d'octets) 
281  *                       effectivement lue
282  * @return               longueur retenue pour le champ 
283  */
284
285 void gdcmHeader::FindVR( ElValue *ElVal) {
286         char VR[3];
287         string vr;
288         int lgrLue;
289         long PositionOnEntry = ftell(fp);
290         // Warning: we believe this is explicit VR (Value Representation) because
291         // we used a heuristic that found "UL" in the first tag. Alas this
292         // doesn't guarantee that all the tags will be in explicit VR. In some
293         // cases (see e-film filtered files) one finds implicit VR tags mixed
294         // within an explicit VR file. Hence we make sure the present tag
295         // is in explicit VR and try to fix things if it happens not to be
296         // the case.
297         bool RealExplicit = true;
298         
299         if (filetype != ExplicitVR)
300                 return;
301
302         lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
303         VR[2]=0;
304         vr = string(VR);
305                 
306         // Assume we are reading a falsely explicit VR file i.e. we reached
307         // a tag where we expect reading a VR but are in fact we read the
308         // first to bytes of the length. Then we will interogate (through find)
309         // the dicom_vr dictionary with oddities like "\004\0" which crashes
310         // both GCC and VC++ implentations of the STL map. Hence when the
311         // expected VR read happens to be non-ascii characters we consider
312         // we hit falsely explicit VR tag.
313
314         if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
315                 RealExplicit = false;
316
317         // CLEANME searching the dicom_vr at each occurence is expensive.
318         // PostPone this test in an optional integrity check at the end
319         // of parsing or only in debug mode.
320         if ( RealExplicit && !dicom_vr->count(vr) )
321                 RealExplicit = false;
322
323         if ( RealExplicit ) {
324                 if ( ElVal->IsVrUnknown() ) 
325                         ElVal->SetVR(vr);
326                 return; 
327         }
328         
329         // We thought this was explicit VR, but we end up with an
330         // implicit VR tag. Let's backtrack.
331         dbg.Verbose(1, "gdcmHeader::FindVR:", "Falsely explicit vr file");
332         fseek(fp, PositionOnEntry, SEEK_SET);
333         // When this element is known in the dictionary we shall use, e.g. for
334         // the semantics (see  the usage of IsAnInteger), the vr proposed by the
335         // dictionary entry. Still we have to flag the element as implicit since
336         // we know now our assumption on expliciteness is not furfilled.
337         // avoid  .
338         if ( ElVal->IsVrUnknown() )
339                 ElVal->SetVR("Implicit");
340         ElVal->SetImplicitVr();
341 }
342
343 /**
344  * \ingroup gdcmHeader
345  * \brief   Determines if the Transfer Syntax was allready encountered
346  *          and if it corresponds to a Big Endian one.
347  *
348  * @return  True when big endian found. False in all other cases.
349  */
350 bool gdcmHeader::IsBigEndianTransferSyntax(void) {
351         ElValue* Element = PubElVals.GetElement(0x0002, 0x0010);
352         if ( !Element )
353                 return false;
354         LoadElementValueSafe(Element);
355         string Transfer = Element->GetValue();
356         if ( Transfer == "1.2.840.10008.1.2.2" )
357                 return true;
358         return false;
359 }
360
361 void gdcmHeader::FixFoundLength(ElValue * ElVal, guint32 FoudLength) {
362         // Heuristic: a final fix.
363         if ( FoudLength == 0xffffffff)
364                 FoudLength = 0;
365         ElVal->SetLength(FoudLength);
366 }
367
368 void gdcmHeader::FindLength( ElValue * ElVal) {
369         guint16 element = ElVal->GetElement();
370         string  vr      = ElVal->GetVR();
371         guint16 length16;
372         
373         if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
374
375                 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
376                         // The following reserved two bytes (see PS 3.5-2001, section
377                         // 7.1.2 Data element structure with explicit vr p27) must be
378                         // skipped before proceeding on reading the length on 4 bytes.
379                         fseek(fp, 2L, SEEK_CUR);
380                         FixFoundLength(ElVal, ReadInt32());
381                         return;
382                 }
383
384                 // Length is encoded on 2 bytes.
385                 length16 = ReadInt16();
386                 
387                 // We can tell the current file is encoded in big endian (like
388                 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
389                 // and it's value is the one of the encoding of a bie endian file.
390                 // In order to deal with such big endian encoded files, we have
391                 // (at least) two strategies:
392                 // * when we load the "Transfer Syntax" tag with value of big endian
393                 //   encoding, we raise the proper flags. Then we wait for the end
394                 //   of the META group (0x0002) among which is "Transfer Syntax",
395                 //   before switching the swap code to big endian. We have to postpone
396                 //   the switching of the swap code since the META group is fully encoded
397                 //   in little endian, and big endian coding only starts at the next
398                 //   group. The corresponding code can be hard to analyse and adds
399                 //   many additional unnecessary tests for regular tags.
400                 // * the second strategy consist to wait for trouble, that shall appear
401                 //   when we find the first group with big endian encoding. This is
402                 //   easy to detect since the length of a "Group Length" tag (the
403                 //   ones with zero as element number) has to be of 4 (0x0004). When we
404                 //   encouter 1024 (0x0400) chances are the encoding changed and we
405                 //   found a group with big endian encoding.
406                 // We shall use this second strategy. In order make sure that we
407                 // can interpret the presence of an apparently big endian encoded
408                 // length of a "Group Length" without committing a big mistake, we
409                 // add an additional check: we look in the allready parsed elements
410                 // for the presence of a "Transfer Syntax" whose value has to be "big
411                 // endian encoding". When this is the case, chances are we got our
412                 // hands on a big endian encoded file: we switch the swap code to
413                 // big endian and proceed...
414                 if ( (element  == 0) && (length16 == 1024) ) {
415                         if ( ! IsBigEndianTransferSyntax() )
416                                 throw Error::FileReadError(fp, "gdcmHeader::FindLength");
417                         length16 = 4;
418                         SwitchSwapToBigEndian();
419                         // Restore the unproperly loaded values i.e. the group, the element
420                         // and the dictionary entry depending on them.
421                         guint16 CorrectGroup   = SwapShort(ElVal->GetGroup());
422                         guint16 CorrectElem    = SwapShort(ElVal->GetElement());
423                         gdcmDictEntry * NewTag = IsInDicts(CorrectGroup, CorrectElem);
424                         if (!NewTag) {
425                                 // This correct tag is not in the dictionary. Create a new one.
426                                 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
427                         }
428                         // FIXME this can create a memory leaks on the old entry that be
429                         // left unreferenced.
430                         ElVal->SetDictEntry(NewTag);
431                 }
432                  
433                 // Heuristic: well some files are really ill-formed.
434                 if ( length16 == 0xffff) {
435                         length16 = 0;
436                         dbg.Verbose(0, "gdcmHeader::FindLength",
437                                     "Erroneous element length fixed.");
438                 }
439                 FixFoundLength(ElVal, (guint32)length16);
440                 return;
441         }
442
443         // Either implicit VR or a non DICOM conformal (see not below) explicit
444         // VR that ommited the VR of (at least) this element. Farts happen.
445         // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
446         // on Data elements "Implicit and Explicit VR Data Elements shall
447         // not coexist in a Data Set and Data Sets nested within it".]
448         // Length is on 4 bytes.
449         FixFoundLength(ElVal, ReadInt32());
450 }
451
452 /**
453  * \ingroup gdcmHeader
454  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
455  *          processor order.
456  *
457  * @return  The suggested integer.
458  */
459 guint32 gdcmHeader::SwapLong(guint32 a) {
460         // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
461         switch (sw) {
462         case    0 :
463                 break;
464         case 4321 :
465                 a=(   ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000)    | 
466                       ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
467                 break;
468         
469         case 3412 :
470                 a=(   ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
471                 break;
472         
473         case 2143 :
474                 a=(    ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
475                 break;
476         default :
477                 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
478                 a=0;
479         }
480         return(a);
481 }
482
483 /**
484  * \ingroup gdcmHeader
485  * \brief   Swaps the bytes so they agree with the processor order
486  * @return  The properly swaped 16 bits integer.
487  */
488 guint16 gdcmHeader::SwapShort(guint16 a) {
489         if ( (sw==4321)  || (sw==2143) )
490                 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
491         return (a);
492 }
493
494 void gdcmHeader::SkipElementValue(ElValue * ElVal) {
495         //FIXME don't dump the returned value
496         (void)fseek(fp, (long)ElVal->GetLength(), SEEK_CUR);
497 }
498
499 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
500         if (NewSize < 0)
501                 return;
502         if ((guint32)NewSize >= (guint32)0xffffffff) {
503                 MaxSizeLoadElementValue = 0xffffffff;
504                 return;
505         }
506         MaxSizeLoadElementValue = NewSize;
507 }
508
509 /**
510  * \ingroup       gdcmHeader
511  * \brief         Loads the element if it's size is not to big.
512  * @param ElVal   Element whose value shall be loaded. 
513  * @param MaxSize Size treshold above which the element value is not
514  *                loaded in memory. The element value is allways loaded
515  *                when MaxSize is equal to UINT32_MAX.
516  * @return  
517  */
518 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
519         size_t item_read;
520         guint16 group  = ElVal->GetGroup();
521         guint16 elem   = ElVal->GetElement();
522         string  vr     = ElVal->GetVR();
523         guint32 length = ElVal->GetLength();
524         bool SkipLoad  = false;
525
526         fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
527         
528         // Sequences not treated yet !
529         if( vr == "SQ" )
530                 SkipLoad = true;
531
532         // Heuristic : a sequence "contains" a set of tags (called items). It looks
533         // like the last tag of a sequence (the one that terminates the sequence)
534         // has a group of 0xfffe (with a dummy length).
535         if( group == 0xfffe )
536                 SkipLoad = true;
537
538         // The group length doesn't represent data to be loaded in memory, since
539         // each element of the group shall be loaded individualy.
540         if( elem == 0 )
541                 SkipLoad = true;
542
543         if ( SkipLoad ) {
544                           // FIXME the following skip is not necessary
545                 SkipElementValue(ElVal);
546                 ElVal->SetLength(0);
547                 ElVal->SetValue("gdcm::Skipped");
548                 return;
549         }
550
551         // When the length is zero things are easy:
552         if ( length == 0 ) {
553                 ElVal->SetValue("");
554                 return;
555         }
556
557         // Values bigger than specified are not loaded.
558         if (length > MaxSizeLoadElementValue) {
559                 ostringstream s;
560                 s << "gdcm::NotLoaded.";
561                 s << " Address:" << (long)ElVal->GetOffset();
562                 s << " Length:"  << ElVal->GetLength();
563                 //mesg += " Length:"  + ElVal->GetLength();
564                 ElVal->SetValue(s.str());
565                 return;
566         }
567         
568         // When an integer is expected, read and convert the following two or
569         // four bytes properly i.e. as an integer as opposed to a string.
570         if ( IsAnInteger(ElVal) ) {
571                 guint32 NewInt;
572                 if( length == 2 ) {
573                         NewInt = ReadInt16();
574                 } else if( length == 4 ) {
575                         NewInt = ReadInt32();
576                 } else
577                         dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
578                 
579                 //FIXME: make the following an util fonction
580                 ostringstream s;
581                 s << NewInt;
582                 ElVal->SetValue(s.str());
583                 return;
584         }
585         
586         // FIXME The exact size should be length if we move to strings or whatever
587         char* NewValue = (char*)g_malloc(length+1);
588         if( !NewValue) {
589                 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
590                 return;
591         }
592         NewValue[length]= 0;
593         
594         item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
595         if ( item_read != 1 ) {
596                 g_free(NewValue);
597                 Error::FileReadError(fp, "gdcmHeader::LoadElementValue");
598                 ElVal->SetValue("gdcm::UnRead");
599                 return;
600         }
601         ElVal->SetValue(NewValue);
602 }
603
604 /**
605  * \ingroup       gdcmHeader
606  * \brief         Loads the element while preserving the current
607  *                underlying file position indicator as opposed to
608  *                to LoadElementValue that modifies it.
609  * @param ElVal   Element whose value shall be loaded. 
610  * @return  
611  */
612 void gdcmHeader::LoadElementValueSafe(ElValue * ElVal) {
613         long PositionOnEntry = ftell(fp);
614         LoadElementValue(ElVal);
615         fseek(fp, PositionOnEntry, SEEK_SET);
616 }
617
618
619 guint16 gdcmHeader::ReadInt16(void) {
620         guint16 g;
621         size_t item_read;
622         item_read = fread (&g, (size_t)2,(size_t)1, fp);
623         if ( item_read != 1 )
624                 throw Error::FileReadError(fp, "gdcmHeader::ReadInt16");
625         g = SwapShort(g);
626         return g;
627 }
628
629 guint32 gdcmHeader::ReadInt32(void) {
630         guint32 g;
631         size_t item_read;
632         item_read = fread (&g, (size_t)4,(size_t)1, fp);
633         if ( item_read != 1 )
634                 throw Error::FileReadError(fp, "gdcmHeader::ReadInt32");
635         g = SwapLong(g);
636         return g;
637 }
638
639 /**
640  * \ingroup gdcmHeader
641  * \brief   Read the next tag without loading it's value
642  * @return  On succes the newly created ElValue, NULL on failure.      
643  */
644
645 ElValue * gdcmHeader::ReadNextElement(void) {
646         guint16 g;
647         guint16 n;
648         ElValue * NewElVal;
649         
650         try {
651                 g = ReadInt16();
652                 n = ReadInt16();
653         }
654         catch ( Error::FileReadError ) {
655                 // We reached the EOF (or an error occured) and header parsing
656                 // has to be considered as finished.
657                 return (ElValue *)0;
658         }
659
660         // Find out if the tag we encountered is in the dictionaries:
661         gdcmDictEntry * NewTag = IsInDicts(g, n);
662         if (!NewTag)
663                 NewTag = new gdcmDictEntry(g, n);
664
665         NewElVal = new ElValue(NewTag);
666         if (!NewElVal) {
667                 dbg.Verbose(1, "ReadNextElement: failed to allocate ElValue");
668                 return (ElValue*)0;
669         }
670
671         FindVR(NewElVal);
672         try { FindLength(NewElVal); }
673         catch ( Error::FileReadError ) { // Call it quits
674                 return (ElValue *)0;
675         }
676         NewElVal->SetOffset(ftell(fp));
677         return NewElVal;
678 }
679
680 bool gdcmHeader::IsAnInteger(ElValue * ElVal) {
681         guint16 group   = ElVal->GetGroup();
682         guint16 element = ElVal->GetElement();
683         string  vr      = ElVal->GetVR();
684         guint32 length  = ElVal->GetLength();
685
686         // When we have some semantics on the element we just read, and if we
687         // a priori know we are dealing with an integer, then we shall be
688         // able to swap it's element value properly.
689         if ( element == 0 )  {  // This is the group length of the group
690                 if (length == 4)
691                         return true;
692                 else
693                         dbg.Error("gdcmHeader::IsAnInteger",
694                                   "Erroneous Group Length element length.");
695         }
696         
697         if ( group % 2 != 0 )
698                 // We only have some semantics on documented elements, which are
699                 // the even ones.
700                 return false;
701         
702         if ( (length != 4) && ( length != 2) )
703                 // Swapping only make sense on integers which are 2 or 4 bytes long.
704                 return false;
705         
706         if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
707                 return true;
708         
709         if ( (group == 0x0028) && (element == 0x0005) )
710                 // This tag is retained from ACR/NEMA
711                 // CHECKME Why should "Image Dimensions" be a single integer ?
712                 return true;
713         
714         if ( (group == 0x0028) && (element == 0x0200) )
715                 // This tag is retained from ACR/NEMA
716                 return true;
717         
718         return false;
719 }
720
721 /**
722  * \ingroup gdcmHeader
723  * \brief   Recover the offset (from the beginning of the file) of the pixels.
724  */
725 size_t gdcmHeader::GetPixelOffset(void) {
726         // If this file complies with the norm we should encounter the
727         // "Image Location" tag (0x0028,  0x0200). This tag contains the
728         // the group that contains the pixel data (hence the "Pixel Data"
729         // is found by indirection through the "Image Location").
730         // Inside the group pointed by "Image Location" the searched element
731         // is conventionally the element 0x0010 (when the norm is respected).
732         //    When the "Image Location" is absent we default to group 0x7fe0.
733         guint16 grPixel;
734         guint16 numPixel;
735         string ImageLocation = GetPubElValByName("Image Location");
736         if ( ImageLocation == "UNFOUND" ) {
737                 grPixel = 0x7FE0;
738         } else {
739                 grPixel = (guint16) atoi( ImageLocation.c_str() );
740         }
741         if (grPixel != 0x7fe0)
742                 // FIXME is this still necessary ?
743                 // Now, this looks like an old dirty fix for Philips imager
744                 numPixel = 0x1010;
745         else
746                 numPixel = 0x0010;
747         ElValue* PixelElement = PubElVals.GetElement(grPixel, numPixel);
748         if (PixelElement)
749                 return PixelElement->GetOffset();
750         else
751                 return 0;
752 }
753
754 gdcmDictEntry * gdcmHeader::IsInDicts(guint32 group, guint32 element) {
755         gdcmDictEntry * found = (gdcmDictEntry*)0;
756         if (!RefPubDict && !RefShaDict) {
757                 //FIXME build a default dictionary !
758                 printf("FIXME in gdcmHeader::IsInDicts\n");
759         }
760         if (RefPubDict) {
761                 found = RefPubDict->GetTag(group, element);
762                 if (found)
763                         return found;
764         }
765         if (RefShaDict) {
766                 found = RefShaDict->GetTag(group, element);
767                 if (found)
768                         return found;
769         }
770         return found;
771 }
772
773 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
774         return PubElVals.GetElValue(group, element);
775 }
776
777 string gdcmHeader::GetPubElValByName(string TagName) {
778         return PubElVals.GetElValue(TagName);
779 }
780
781 /**
782  * \ingroup gdcmHeader
783  * \brief   Parses the header of the file but does NOT load element values.
784  */
785 void gdcmHeader::ParseHeader(void) {
786         ElValue * newElValue = (ElValue *)0;
787         
788         rewind(fp);
789         CheckSwap();
790         while ( (newElValue = ReadNextElement()) ) {
791                 SkipElementValue(newElValue);
792                 PubElVals.Add(newElValue);
793         }
794 }
795
796 /**
797  * \ingroup gdcmHeader
798  * \brief   Loads the element values of all the elements present in the
799  *          public tag based hash table.
800  */
801 void gdcmHeader::LoadElements(void) {
802         rewind(fp);    
803         TagElValueHT ht = PubElVals.GetTagHt();
804         for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag)
805                 LoadElementValue(tag->second);
806 }
807
808 void gdcmHeader::PrintPubElVal(ostream & os) {
809         PubElVals.Print(os);
810 }
811
812 void gdcmHeader::PrintPubDict(ostream & os) {
813         RefPubDict->Print(os);
814 }