]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
6722b122dbcc787438b4893811e6721aa9200289
[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   Discover what the swap code is (among little endian, big endian, 
92  *          bad little endian, bad big endian).
93  */
94 void gdcmHeader::CheckSwap()
95 {
96         // The only guaranted way of finding the swap code is to find a
97         // group tag since we know it's length has to be of four bytes i.e.
98         // 0x00000004. Finding the swap code in then straigthforward. Trouble
99         // occurs when we can't find such group...
100         guint32  s;
101         guint32  x=4;  // x : pour ntohs
102         bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
103          
104         int lgrLue;
105         char * entCur;
106         char deb[HEADER_LENGHT_TO_READ];
107          
108         // First, compare HostByteOrder and NetworkByteOrder in order to
109         // determine if we shall need to swap bytes (i.e. the Endian type).
110         if (x==ntohs(x))
111                 net2host = true;
112         else
113                 net2host = false;
114         
115         // The easiest case is the one of a DICOM header, since it possesses a
116         // file preamble where it suffice to look for the sting "DICM".
117         lgrLue = fread(deb, 1, HEADER_LENGHT_TO_READ, fp);
118         
119         entCur = deb + 128;
120         if(memcmp(entCur, "DICM", (size_t)4) == 0) {
121                 filetype = TrueDicom;
122                 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
123         } else {
124                 filetype = Unknown;
125                 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
126         }
127
128         if(filetype == TrueDicom) {
129                 // Next, determine the value representation (VR). Let's skip to the
130                 // first element (0002, 0000) and check there if we find "UL", in
131                 // which case we (almost) know it is explicit VR.
132                 // WARNING: if it happens to be implicit VR then what we will read
133                 // is the length of the group. If this ascii representation of this
134                 // length happens to be "UL" then we shall believe it is explicit VR.
135                 // FIXME: in order to fix the above warning, we could read the next
136                 // element value (or a couple of elements values) in order to make
137                 // sure we are not commiting a big mistake.
138                 // We need to skip :
139                 // * the 128 bytes of File Preamble (often padded with zeroes),
140                 // * the 4 bytes of "DICM" string,
141                 // * the 4 bytes of the first tag (0002, 0000),
142                 // i.e. a total of  136 bytes.
143                 entCur = deb + 136;
144                 if(memcmp(entCur, "UL", (size_t)2) == 0) {
145                         filetype = ExplicitVR;
146                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
147                                     "explicit Value Representation");
148                 } else {
149                         filetype = ImplicitVR;
150                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
151                                     "not an explicit Value Representation");
152                 }
153
154                 if (net2host) {
155                         sw = 4321;
156                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
157                                        "HostByteOrder != NetworkByteOrder");
158                 } else {
159                         sw = 0;
160                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
161                                        "HostByteOrder = NetworkByteOrder");
162                 }
163                 
164                 // Position the file position indicator at first tag (i.e.
165                 // after the file preamble and the "DICM" string).
166                 rewind(fp);
167                 fseek (fp, 132L, SEEK_SET);
168                 return;
169         } // End of TrueDicom
170
171         // Alas, this is not a DicomV3 file and whatever happens there is no file
172         // preamble. We can reset the file position indicator to where the data
173         // is (i.e. the beginning of the file).
174         rewind(fp);
175
176         // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
177         // By clean we mean that the length of the first tag is written down.
178         // If this is the case and since the length of the first group HAS to be
179         // four (bytes), then determining the proper swap code is straightforward.
180
181         entCur = deb + 4;
182         s = str2num(entCur, guint32);
183         
184         switch (s) {
185         case 0x00040000 :
186                 sw = 3412;
187                 filetype = ACR;
188                 return;
189         case 0x04000000 :
190                 sw = 4321;
191                 filetype = ACR;
192                 return;
193         case 0x00000400 :
194                 sw = 2143;
195                 filetype = ACR;
196                 return;
197         case 0x00000004 :
198                 sw = 0;
199                 filetype = ACR;
200                 return;
201         default :
202                 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
203                                "ACE/NEMA unfound swap info (time to raise bets)");
204         }
205
206         // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
207         // It is time for despaired wild guesses. So, let's assume this file
208         // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
209         // not present. Then the only info we have is the net2host one.
210         if (! net2host )
211                 sw = 0;
212         else
213                 sw = 4321;
214         return;
215 }
216
217 void gdcmHeader::SwitchSwapToBigEndian(void) {
218         dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
219                        "Switching to BigEndian mode.");
220         if ( sw == 0    ) {
221                 sw = 4321;
222                 return;
223         }
224         if ( sw == 4321 ) {
225                 sw = 0;
226                 return;
227         }
228         if ( sw == 3412 ) {
229                 sw = 2143;
230                 return;
231         }
232         if ( sw == 2143 )
233                 sw = 3412;
234 }
235
236 /**
237  * \ingroup   gdcmHeader
238  * \brief     Find the value representation of the current tag.
239  *
240  * @param sw  code swap
241  * @param skippedLength  pointeur sur nombre d'octets que l'on a saute qd
242  *                       la lecture est finie
243  * @param longueurLue    pointeur sur longueur (en nombre d'octets) 
244  *                       effectivement lue
245  * @return               longueur retenue pour le champ 
246  */
247
248 void gdcmHeader::FindVR( ElValue *ElVal) {
249         if (filetype != ExplicitVR)
250                 return;
251
252         char VR[3];
253         string vr;
254         int lgrLue;
255         long PositionOnEntry = ftell(fp);
256         // Warning: we believe this is explicit VR (Value Representation) because
257         // we used a heuristic that found "UL" in the first tag. Alas this
258         // doesn't guarantee that all the tags will be in explicit VR. In some
259         // cases (see e-film filtered files) one finds implicit VR tags mixed
260         // within an explicit VR file. Hence we make sure the present tag
261         // is in explicit VR and try to fix things if it happens not to be
262         // the case.
263         bool RealExplicit = true;
264         
265         lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
266         VR[2]=0;
267         vr = string(VR);
268                 
269         // Assume we are reading a falsely explicit VR file i.e. we reached
270         // a tag where we expect reading a VR but are in fact we read the
271         // first to bytes of the length. Then we will interogate (through find)
272         // the dicom_vr dictionary with oddities like "\004\0" which crashes
273         // both GCC and VC++ implentations of the STL map. Hence when the
274         // expected VR read happens to be non-ascii characters we consider
275         // we hit falsely explicit VR tag.
276
277         if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
278                 RealExplicit = false;
279
280         // CLEANME searching the dicom_vr at each occurence is expensive.
281         // PostPone this test in an optional integrity check at the end
282         // of parsing or only in debug mode.
283         if ( RealExplicit && !dicom_vr->count(vr) )
284                 RealExplicit = false;
285
286         if ( RealExplicit ) {
287                 if ( ElVal->IsVrUnknown() ) {
288                         // When not a dictionary entry, we can safely overwrite the vr.
289                         ElVal->SetVR(vr);
290                         return; 
291                 }
292                 if ( ElVal->GetVR() == vr ) {
293                         // The vr we just read and the dictionary agree. Nothing to do.
294                         return;
295                 }
296                 // The vr present in the file and the dictionary disagree. We assume
297                 // the file writer knew best and use the vr of the file. Since it would
298                 // be unwise to overwrite the vr of a dictionary (since it would
299                 // compromise it's next user), we need to clone the actual DictEntry
300                 // and change the vr for the read one.
301                 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
302                                            ElVal->GetElement(),
303                                            vr,
304                                            "FIXME",
305                                            ElVal->GetName());
306                 ElVal->SetDictEntry(NewTag);
307                 return; 
308         }
309         
310         // We thought this was explicit VR, but we end up with an
311         // implicit VR tag. Let's backtrack.
312         dbg.Verbose(1, "gdcmHeader::FindVR:", "Falsely explicit vr file");
313         fseek(fp, PositionOnEntry, SEEK_SET);
314         // When this element is known in the dictionary we shall use, e.g. for
315         // the semantics (see  the usage of IsAnInteger), the vr proposed by the
316         // dictionary entry. Still we have to flag the element as implicit since
317         // we know now our assumption on expliciteness is not furfilled.
318         // avoid  .
319         if ( ElVal->IsVrUnknown() )
320                 ElVal->SetVR("Implicit");
321         ElVal->SetImplicitVr();
322 }
323
324 /**
325  * \ingroup gdcmHeader
326  * \brief   Determines if the Transfer Syntax was allready encountered
327  *          and if it corresponds to a Big Endian one.
328  *
329  * @return  True when big endian found. False in all other cases.
330  */
331 bool gdcmHeader::IsBigEndianTransferSyntax(void) {
332         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
333         if ( !Element )
334                 return false;
335         LoadElementValueSafe(Element);
336         string Transfer = Element->GetValue();
337         if ( Transfer == "1.2.840.10008.1.2.2" )
338                 return true;
339         return false;
340 }
341
342 void gdcmHeader::FixFoundLength(ElValue * ElVal, guint32 FoudLength) {
343         // Heuristic: a final fix.
344         if ( FoudLength == 0xffffffff)
345                 FoudLength = 0;
346         ElVal->SetLength(FoudLength);
347 }
348
349 guint32 gdcmHeader::FindLengthOB(void) {
350         // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
351         guint16 g;
352         guint16 n; 
353         long PositionOnEntry = ftell(fp);
354         bool FoundSequenceDelimiter = false;
355         guint32 TotalLength = 0;
356         guint32 ItemLength;
357
358         while ( ! FoundSequenceDelimiter) {
359                 g = ReadInt16();
360                 n = ReadInt16();
361                 TotalLength += 4;  // We even have to decount the group and element 
362                 if ( g != 0xfffe ) {
363                         dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
364                                     "wrong group for an item sequence.");
365                         throw Error::FileReadError(fp, "gdcmHeader::FindLengthOB");
366                 }
367                 if ( n == 0xe0dd )
368                         FoundSequenceDelimiter = true;
369                 else if ( n != 0xe000) {
370                         dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
371                                     "wrong element for an item sequence.");
372                         throw Error::FileReadError(fp, "gdcmHeader::FindLengthOB");
373                 }
374                 ItemLength = ReadInt32();
375                 TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
376                                                 // the ItemLength with ReadInt32
377                 SkipBytes(ItemLength);
378         }
379         fseek(fp, PositionOnEntry, SEEK_SET);
380         return TotalLength;
381 }
382
383 void gdcmHeader::FindLength(ElValue * ElVal) {
384         guint16 element = ElVal->GetElement();
385         string  vr      = ElVal->GetVR();
386         guint16 length16;
387         
388         if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
389
390                 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
391                         // The following reserved two bytes (see PS 3.5-2001, section
392                         // 7.1.2 Data element structure with explicit vr p27) must be
393                         // skipped before proceeding on reading the length on 4 bytes.
394                         fseek(fp, 2L, SEEK_CUR);
395                         guint32 length32 = ReadInt32();
396                         if ( (vr == "OB") && (length32 == 0xffffffff) ) {
397                                 ElVal->SetLength(FindLengthOB());
398                                 return;
399                         }
400                         FixFoundLength(ElVal, length32);
401                         return;
402                 }
403
404                 // Length is encoded on 2 bytes.
405                 length16 = ReadInt16();
406                 
407                 // We can tell the current file is encoded in big endian (like
408                 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
409                 // and it's value is the one of the encoding of a big endian file.
410                 // In order to deal with such big endian encoded files, we have
411                 // (at least) two strategies:
412                 // * when we load the "Transfer Syntax" tag with value of big endian
413                 //   encoding, we raise the proper flags. Then we wait for the end
414                 //   of the META group (0x0002) among which is "Transfer Syntax",
415                 //   before switching the swap code to big endian. We have to postpone
416                 //   the switching of the swap code since the META group is fully encoded
417                 //   in little endian, and big endian coding only starts at the next
418                 //   group. The corresponding code can be hard to analyse and adds
419                 //   many additional unnecessary tests for regular tags.
420                 // * the second strategy consist in waiting for trouble, that shall appear
421                 //   when we find the first group with big endian encoding. This is
422                 //   easy to detect since the length of a "Group Length" tag (the
423                 //   ones with zero as element number) has to be of 4 (0x0004). When we
424                 //   encouter 1024 (0x0400) chances are the encoding changed and we
425                 //   found a group with big endian encoding.
426                 // We shall use this second strategy. In order make sure that we
427                 // can interpret the presence of an apparently big endian encoded
428                 // length of a "Group Length" without committing a big mistake, we
429                 // add an additional check: we look in the allready parsed elements
430                 // for the presence of a "Transfer Syntax" whose value has to be "big
431                 // endian encoding". When this is the case, chances are we got our
432                 // hands on a big endian encoded file: we switch the swap code to
433                 // big endian and proceed...
434                 if ( (element  == 0) && (length16 == 1024) ) {
435                         if ( ! IsBigEndianTransferSyntax() )
436                                 throw Error::FileReadError(fp, "gdcmHeader::FindLength");
437                         length16 = 4;
438                         SwitchSwapToBigEndian();
439                         // Restore the unproperly loaded values i.e. the group, the element
440                         // and the dictionary entry depending on them.
441                         guint16 CorrectGroup   = SwapShort(ElVal->GetGroup());
442                         guint16 CorrectElem    = SwapShort(ElVal->GetElement());
443                         gdcmDictEntry * NewTag = IsInDicts(CorrectGroup, CorrectElem);
444                         if (!NewTag) {
445                                 // This correct tag is not in the dictionary. Create a new one.
446                                 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
447                         }
448                         // FIXME this can create a memory leaks on the old entry that be
449                         // left unreferenced.
450                         ElVal->SetDictEntry(NewTag);
451                 }
452                  
453                 // Heuristic: well some files are really ill-formed.
454                 if ( length16 == 0xffff) {
455                         length16 = 0;
456                         dbg.Verbose(0, "gdcmHeader::FindLength",
457                                     "Erroneous element length fixed.");
458                 }
459                 FixFoundLength(ElVal, (guint32)length16);
460                 return;
461         }
462
463         // Either implicit VR or a non DICOM conformal (see not below) explicit
464         // VR that ommited the VR of (at least) this element. Farts happen.
465         // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
466         // on Data elements "Implicit and Explicit VR Data Elements shall
467         // not coexist in a Data Set and Data Sets nested within it".]
468         // Length is on 4 bytes.
469         FixFoundLength(ElVal, ReadInt32());
470 }
471
472 /**
473  * \ingroup gdcmHeader
474  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
475  *          processor order.
476  *
477  * @return  The suggested integer.
478  */
479 guint32 gdcmHeader::SwapLong(guint32 a) {
480         // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
481         switch (sw) {
482         case    0 :
483                 break;
484         case 4321 :
485                 a=(   ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000)    | 
486                       ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
487                 break;
488         
489         case 3412 :
490                 a=(   ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
491                 break;
492         
493         case 2143 :
494                 a=(    ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
495                 break;
496         default :
497                 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
498                 a=0;
499         }
500         return(a);
501 }
502
503 /**
504  * \ingroup gdcmHeader
505  * \brief   Swaps the bytes so they agree with the processor order
506  * @return  The properly swaped 16 bits integer.
507  */
508 guint16 gdcmHeader::SwapShort(guint16 a) {
509         if ( (sw==4321)  || (sw==2143) )
510                 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
511         return (a);
512 }
513
514 void gdcmHeader::SkipBytes(guint32 NBytes) {
515         //FIXME don't dump the returned value
516         (void)fseek(fp, (long)NBytes, SEEK_CUR);
517 }
518
519 void gdcmHeader::SkipElementValue(ElValue * ElVal) {
520         SkipBytes(ElVal->GetLength());
521 }
522
523 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
524         if (NewSize < 0)
525                 return;
526         if ((guint32)NewSize >= (guint32)0xffffffff) {
527                 MaxSizeLoadElementValue = 0xffffffff;
528                 return;
529         }
530         MaxSizeLoadElementValue = NewSize;
531 }
532
533 /**
534  * \ingroup       gdcmHeader
535  * \brief         Loads the element if it's size is not to big.
536  * @param ElVal   Element whose value shall be loaded. 
537  * @param MaxSize Size treshold above which the element value is not
538  *                loaded in memory. The element value is allways loaded
539  *                when MaxSize is equal to UINT32_MAX.
540  * @return  
541  */
542 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
543         size_t item_read;
544         guint16 group  = ElVal->GetGroup();
545         guint16 elem   = ElVal->GetElement();
546         string  vr     = ElVal->GetVR();
547         guint32 length = ElVal->GetLength();
548         bool SkipLoad  = false;
549
550         fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
551         
552         // Sequences not treated yet !
553         if( vr == "SQ" )
554                 SkipLoad = true;
555
556         // Heuristic : a sequence "contains" a set of tags (called items). It looks
557         // like the last tag of a sequence (the one that terminates the sequence)
558         // has a group of 0xfffe (with a dummy length).
559         if( group == 0xfffe )
560                 SkipLoad = true;
561
562         // The group length doesn't represent data to be loaded in memory, since
563         // each element of the group shall be loaded individualy.
564         if( elem == 0 )
565                 SkipLoad = true;
566
567         if ( SkipLoad ) {
568                           // FIXME the following skip is not necessary
569                 SkipElementValue(ElVal);
570                 ElVal->SetLength(0);
571                 ElVal->SetValue("gdcm::Skipped");
572                 return;
573         }
574
575         // When the length is zero things are easy:
576         if ( length == 0 ) {
577                 ElVal->SetValue("");
578                 return;
579         }
580
581         // Values bigger than specified are not loaded.
582         if (length > MaxSizeLoadElementValue) {
583                 ostringstream s;
584                 s << "gdcm::NotLoaded.";
585                 s << " Address:" << (long)ElVal->GetOffset();
586                 s << " Length:"  << ElVal->GetLength();
587                 //mesg += " Length:"  + ElVal->GetLength();
588                 ElVal->SetValue(s.str());
589                 return;
590         }
591         
592         // When an integer is expected, read and convert the following two or
593         // four bytes properly i.e. as an integer as opposed to a string.
594         if ( IsAnInteger(ElVal) ) {
595                 guint32 NewInt;
596                 if( length == 2 ) {
597                         NewInt = ReadInt16();
598                 } else if( length == 4 ) {
599                         NewInt = ReadInt32();
600                 } else
601                         dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
602                 
603                 //FIXME: make the following an util fonction
604                 ostringstream s;
605                 s << NewInt;
606                 ElVal->SetValue(s.str());
607                 return;
608         }
609         
610         // FIXME The exact size should be length if we move to strings or whatever
611         char* NewValue = (char*)malloc(length+1);
612         if( !NewValue) {
613                 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
614                 return;
615         }
616         NewValue[length]= 0;
617         
618         item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
619         if ( item_read != 1 ) {
620                 free(NewValue);
621                 Error::FileReadError(fp, "gdcmHeader::LoadElementValue");
622                 ElVal->SetValue("gdcm::UnRead");
623                 return;
624         }
625         ElVal->SetValue(NewValue);
626 }
627
628 /**
629  * \ingroup       gdcmHeader
630  * \brief         Loads the element while preserving the current
631  *                underlying file position indicator as opposed to
632  *                to LoadElementValue that modifies it.
633  * @param ElVal   Element whose value shall be loaded. 
634  * @return  
635  */
636 void gdcmHeader::LoadElementValueSafe(ElValue * ElVal) {
637         long PositionOnEntry = ftell(fp);
638         LoadElementValue(ElVal);
639         fseek(fp, PositionOnEntry, SEEK_SET);
640 }
641
642
643 guint16 gdcmHeader::ReadInt16(void) {
644         guint16 g;
645         size_t item_read;
646         item_read = fread (&g, (size_t)2,(size_t)1, fp);
647         if ( item_read != 1 )
648                 throw Error::FileReadError(fp, "gdcmHeader::ReadInt16");
649         g = SwapShort(g);
650         return g;
651 }
652
653 guint32 gdcmHeader::ReadInt32(void) {
654         guint32 g;
655         size_t item_read;
656         item_read = fread (&g, (size_t)4,(size_t)1, fp);
657         if ( item_read != 1 )
658                 throw Error::FileReadError(fp, "gdcmHeader::ReadInt32");
659         g = SwapLong(g);
660         return g;
661 }
662
663 /**
664  * \ingroup gdcmHeader
665  * \brief   Read the next tag without loading it's value
666  * @return  On succes the newly created ElValue, NULL on failure.      
667  */
668
669 ElValue * gdcmHeader::ReadNextElement(void) {
670         guint16 g;
671         guint16 n;
672         ElValue * NewElVal;
673         
674         try {
675                 g = ReadInt16();
676                 n = ReadInt16();
677         }
678         catch ( Error::FileReadError ) {
679                 // We reached the EOF (or an error occured) and header parsing
680                 // has to be considered as finished.
681                 return (ElValue *)0;
682         }
683
684         // Find out if the tag we encountered is in the dictionaries:
685         gdcmDictEntry * NewTag = IsInDicts(g, n);
686         if (!NewTag)
687                 NewTag = new gdcmDictEntry(g, n);
688
689         NewElVal = new ElValue(NewTag);
690         if (!NewElVal) {
691                 dbg.Verbose(1, "ReadNextElement: failed to allocate ElValue");
692                 return (ElValue*)0;
693         }
694
695         FindVR(NewElVal);
696         try { FindLength(NewElVal); }
697         catch ( Error::FileReadError ) { // Call it quits
698                 return (ElValue *)0;
699         }
700         NewElVal->SetOffset(ftell(fp));
701         return NewElVal;
702 }
703
704 bool gdcmHeader::IsAnInteger(ElValue * ElVal) {
705         guint16 group   = ElVal->GetGroup();
706         guint16 element = ElVal->GetElement();
707         string  vr      = ElVal->GetVR();
708         guint32 length  = ElVal->GetLength();
709
710         // When we have some semantics on the element we just read, and if we
711         // a priori know we are dealing with an integer, then we shall be
712         // able to swap it's element value properly.
713         if ( element == 0 )  {  // This is the group length of the group
714                 if (length == 4)
715                         return true;
716                 else
717                         dbg.Error("gdcmHeader::IsAnInteger",
718                                   "Erroneous Group Length element length.");
719         }
720         
721         if ( group % 2 != 0 )
722                 // We only have some semantics on documented elements, which are
723                 // the even ones.
724                 return false;
725         
726         if ( (length != 4) && ( length != 2) )
727                 // Swapping only make sense on integers which are 2 or 4 bytes long.
728                 return false;
729         
730         if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
731                 return true;
732         
733         if ( (group == 0x0028) && (element == 0x0005) )
734                 // This tag is retained from ACR/NEMA
735                 // CHECKME Why should "Image Dimensions" be a single integer ?
736                 return true;
737         
738         if ( (group == 0x0028) && (element == 0x0200) )
739                 // This tag is retained from ACR/NEMA
740                 return true;
741         
742         return false;
743 }
744
745 /**
746  * \ingroup gdcmHeader
747  * \brief   Recover the offset (from the beginning of the file) of the pixels.
748  */
749 size_t gdcmHeader::GetPixelOffset(void) {
750         // If this file complies with the norm we should encounter the
751         // "Image Location" tag (0x0028,  0x0200). This tag contains the
752         // the group that contains the pixel data (hence the "Pixel Data"
753         // is found by indirection through the "Image Location").
754         // Inside the group pointed by "Image Location" the searched element
755         // is conventionally the element 0x0010 (when the norm is respected).
756         //    When the "Image Location" is absent we default to group 0x7fe0.
757         guint16 grPixel;
758         guint16 numPixel;
759         string ImageLocation = GetPubElValByName("Image Location");
760         if ( ImageLocation == "UNFOUND" ) {
761                 grPixel = 0x7fe0;
762         } else {
763                 grPixel = (guint16) atoi( ImageLocation.c_str() );
764         }
765         if (grPixel != 0x7fe0)
766                 // FIXME is this still necessary ?
767                 // Now, this looks like an old dirty fix for Philips imager
768                 numPixel = 0x1010;
769         else
770                 numPixel = 0x0010;
771         ElValue* PixelElement = PubElVals.GetElementByNumber(grPixel, numPixel);
772         if (PixelElement)
773                 return PixelElement->GetOffset();
774         else
775                 return 0;
776 }
777
778 gdcmDictEntry * gdcmHeader::IsInDicts(guint32 group, guint32 element) {
779         gdcmDictEntry * found = (gdcmDictEntry*)0;
780         if (!RefPubDict && !RefShaDict) {
781                 //FIXME build a default dictionary !
782                 printf("FIXME in gdcmHeader::IsInDicts\n");
783         }
784         if (RefPubDict) {
785                 found = RefPubDict->GetTag(group, element);
786                 if (found)
787                         return found;
788         }
789         if (RefShaDict) {
790                 found = RefShaDict->GetTag(group, element);
791                 if (found)
792                         return found;
793         }
794         return found;
795 }
796
797 list<string> * gdcmHeader::GetPubTagNames(void) {
798         list<string> * Result = new list<string>;
799         TagHT entries = RefPubDict->GetEntries();
800
801         for (TagHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
802       Result->push_back( tag->second->GetName() );
803         }
804         return Result;
805 }
806
807 map<string, list<string> > * gdcmHeader::GetPubTagNamesByCategory(void) {
808         map<string, list<string> > * Result = new map<string, list<string> >;
809         TagHT entries = RefPubDict->GetEntries();
810
811         for (TagHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
812                 (*Result)[tag->second->GetFourth()].push_back(tag->second->GetName());
813         }
814         return Result;
815 }
816
817 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
818         return PubElVals.GetElValueByNumber(group, element);
819 }
820
821 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
822         ElValue* elem =  PubElVals.GetElementByNumber(group, element);
823         if ( !elem )
824                 return "gdcm::Unfound";
825         return elem->GetVR();
826 }
827
828 string gdcmHeader::GetPubElValByName(string TagName) {
829         return PubElVals.GetElValueByName(TagName);
830 }
831
832 string gdcmHeader::GetPubElValRepByName(string TagName) {
833         ElValue* elem =  PubElVals.GetElementByName(TagName);
834         if ( !elem )
835                 return "gdcm::Unfound";
836         return elem->GetVR();
837 }
838
839 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
840         return ShaElVals.GetElValueByNumber(group, element);
841 }
842
843 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
844         ElValue* elem =  ShaElVals.GetElementByNumber(group, element);
845         if ( !elem )
846                 return "gdcm::Unfound";
847         return elem->GetVR();
848 }
849
850 string gdcmHeader::GetShaElValByName(string TagName) {
851         return ShaElVals.GetElValueByName(TagName);
852 }
853
854 string gdcmHeader::GetShaElValRepByName(string TagName) {
855         ElValue* elem =  ShaElVals.GetElementByName(TagName);
856         if ( !elem )
857                 return "gdcm::Unfound";
858         return elem->GetVR();
859 }
860
861
862 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
863         string pub = GetPubElValByNumber(group, element);
864         if (pub.length())
865                 return pub;
866         return GetShaElValByNumber(group, element);
867 }
868
869 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
870         string pub = GetPubElValRepByNumber(group, element);
871         if (pub.length())
872                 return pub;
873         return GetShaElValRepByNumber(group, element);
874 }
875
876 string gdcmHeader::GetElValByName(string TagName) {
877         string pub = GetPubElValByName(TagName);
878         if (pub.length())
879                 return pub;
880         return GetShaElValByName(TagName);
881 }
882
883 string gdcmHeader::GetElValRepByName(string TagName) {
884         string pub = GetPubElValRepByName(TagName);
885         if (pub.length())
886                 return pub;
887         return GetShaElValRepByName(TagName);
888 }
889
890 /**
891  * \ingroup gdcmHeader
892  * \brief   Parses the header of the file but does NOT load element values.
893  */
894 void gdcmHeader::ParseHeader(void) {
895         ElValue * newElValue = (ElValue *)0;
896         
897         rewind(fp);
898         CheckSwap();
899         while ( (newElValue = ReadNextElement()) ) {
900                 SkipElementValue(newElValue);
901                 PubElVals.Add(newElValue);
902         }
903 }
904
905 /**
906  * \ingroup gdcmHeader
907  * \brief   Loads the element values of all the elements present in the
908  *          public tag based hash table.
909  */
910 void gdcmHeader::LoadElements(void) {
911         rewind(fp);    
912         TagElValueHT ht = PubElVals.GetTagHt();
913         for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag)
914                 LoadElementValue(tag->second);
915 }
916
917 void gdcmHeader::PrintPubElVal(ostream & os) {
918         PubElVals.Print(os);
919 }
920
921 void gdcmHeader::PrintPubDict(ostream & os) {
922         RefPubDict->Print(os);
923 }