]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
ajout quelques fonctions gdcmFile
[gdcm.git] / src / gdcmHeader.cxx
1 // gdcmHeader.cxx
2
3 #include "gdcm.h"
4 #include <stdio.h>
5 // For nthos:
6 #ifdef _MSC_VER
7 #include <winsock.h>
8 #else
9 #include <netinet/in.h>
10 #endif
11 #include <cctype>               // for isalpha
12 #include <map>
13 #include <sstream>
14 #include "gdcmUtil.h"
15
16 #define HEADER_LENGTH_TO_READ 256 // on ne lit plus que le debut
17
18 #define DEBUG 1
19
20 namespace Error {
21         struct FileReadError {
22                 FileReadError(FILE* fp, const char* Mesg) {
23                         if (feof(fp))
24                                 dbg.Verbose(1, "EOF encountered :", Mesg);
25                         if (ferror(fp))
26                                 dbg.Verbose(1, "Error on reading :", Mesg);
27                 }
28         };
29 }
30
31 //FIXME: this looks dirty to me...
32 #define str2num(str, typeNum) *((typeNum *)(str))
33
34 VRHT * gdcmHeader::dicom_vr = (VRHT*)0;
35 gdcmDictSet* gdcmHeader::Dicts = new gdcmDictSet();
36
37 void gdcmHeader::Initialise(void) {
38         if (!gdcmHeader::dicom_vr)
39                 InitVRDict();
40         RefPubDict = gdcmHeader::Dicts->GetDefaultPublicDict();
41         RefShaDict = (gdcmDict*)0;
42 }
43
44 gdcmHeader::gdcmHeader (const char* InFilename) {
45         SetMaxSizeLoadElementValue(1024);
46         filename = InFilename;
47         Initialise();
48         fp=fopen(InFilename,"rw");
49         dbg.Error(!fp, "gdcmHeader::gdcmHeader cannot open file", InFilename);
50         ParseHeader();
51 }
52
53 gdcmHeader::~gdcmHeader (void) {
54         fclose(fp);
55         return;
56 }
57
58 void gdcmHeader::InitVRDict (void) {
59         if (dicom_vr) {
60                 dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
61                 return;
62         }
63         VRHT *vr = new VRHT;
64         (*vr)["AE"] = "Application Entity";       // At most 16 bytes
65         (*vr)["AS"] = "Age String";               // Exactly 4 bytes
66         (*vr)["AT"] = "Attribute Tag";            // 2 16-bit unsigned short integers
67         (*vr)["CS"] = "Code String";              // At most 16 bytes
68         (*vr)["DA"] = "Date";                     // Exactly 8 bytes
69         (*vr)["DS"] = "Decimal String";           // At most 16 bytes
70         (*vr)["DT"] = "Date Time";                // At most 26 bytes
71         (*vr)["FL"] = "Floating Point Single";    // 32-bit IEEE 754:1985 float
72         (*vr)["FD"] = "Floating Point Double";    // 64-bit IEEE 754:1985 double
73         (*vr)["IS"] = "Integer String";           // At most 12 bytes
74         (*vr)["LO"] = "Long String";              // At most 64 chars
75         (*vr)["LT"] = "Long Text";                // At most 10240 chars
76         (*vr)["OB"] = "Other Byte String";        // String of bytes (vr independant)
77         (*vr)["OW"] = "Other Word String";        // String of 16-bit words (vr dep)
78         (*vr)["PN"] = "Person Name";              // At most 64 chars
79         (*vr)["SH"] = "Short String";             // At most 16 chars
80         (*vr)["SL"] = "Signed Long";              // Exactly 4 bytes
81         (*vr)["SQ"] = "Sequence of Items";        // Not Applicable
82         (*vr)["SS"] = "Signed Short";             // Exactly 2 bytes
83         (*vr)["ST"] = "Short Text";               // At most 1024 chars
84         (*vr)["TM"] = "Time";                     // At most 16 bytes
85         (*vr)["UI"] = "Unique Identifier";        // At most 64 bytes
86         (*vr)["UL"] = "Unsigned Long ";           // Exactly 4 bytes
87         (*vr)["UN"] = "Unknown";                  // Any length of bytes
88         (*vr)["US"] = "Unsigned Short ";          // Exactly 2 bytes
89         (*vr)["UT"] = "Unlimited Text";           // At most 2^32 -1 chars
90    dicom_vr = vr;       
91 }
92
93 /**
94  * \ingroup gdcmHeader
95  * \brief   Discover what the swap code is (among little endian, big endian,
96  *          bad little endian, bad big endian).
97  *
98  */
99 void gdcmHeader::CheckSwap()
100 {
101         // The only guaranted way of finding the swap code is to find a
102         // group tag since we know it's length has to be of four bytes i.e.
103         // 0x00000004. Finding the swap code in then straigthforward. Trouble
104         // occurs when we can't find such group...
105         guint32  s;
106         guint32  x=4;  // x : pour ntohs
107         bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
108          
109         int lgrLue;
110         char * entCur;
111         char deb[HEADER_LENGTH_TO_READ];
112          
113         // First, compare HostByteOrder and NetworkByteOrder in order to
114         // determine if we shall need to swap bytes (i.e. the Endian type).
115         if (x==ntohs(x))
116                 net2host = true;
117         else
118                 net2host = false;
119         
120         // The easiest case is the one of a DICOM header, since it possesses a
121         // file preamble where it suffice to look for the sting "DICM".
122         lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
123         
124         entCur = deb + 128;
125         if(memcmp(entCur, "DICM", (size_t)4) == 0) {
126                 filetype = TrueDicom;
127                 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
128         } else {
129                 filetype = Unknown;
130                 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
131         }
132
133         if(filetype == TrueDicom) {
134                 // Next, determine the value representation (VR). Let's skip to the
135                 // first element (0002, 0000) and check there if we find "UL", in
136                 // which case we (almost) know it is explicit VR.
137                 // WARNING: if it happens to be implicit VR then what we will read
138                 // is the length of the group. If this ascii representation of this
139                 // length happens to be "UL" then we shall believe it is explicit VR.
140                 // FIXME: in order to fix the above warning, we could read the next
141                 // element value (or a couple of elements values) in order to make
142                 // sure we are not commiting a big mistake.
143                 // We need to skip :
144                 // * the 128 bytes of File Preamble (often padded with zeroes),
145                 // * the 4 bytes of "DICM" string,
146                 // * the 4 bytes of the first tag (0002, 0000),
147                 // i.e. a total of  136 bytes.
148                 entCur = deb + 136;
149                 if(memcmp(entCur, "UL", (size_t)2) == 0) {
150                         filetype = ExplicitVR;
151                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
152                                     "explicit Value Representation");
153                 } else {
154                         filetype = ImplicitVR;
155                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
156                                     "not an explicit Value Representation");
157                 }
158
159                 if (net2host) {
160                         sw = 4321;
161                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
162                                        "HostByteOrder != NetworkByteOrder");
163                 } else {
164                         sw = 0;
165                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
166                                        "HostByteOrder = NetworkByteOrder");
167                 }
168                 
169                 // Position the file position indicator at first tag (i.e.
170                 // after the file preamble and the "DICM" string).
171                 rewind(fp);
172                 fseek (fp, 132L, SEEK_SET);
173                 return;
174         } // End of TrueDicom
175
176         // Alas, this is not a DicomV3 file and whatever happens there is no file
177         // preamble. We can reset the file position indicator to where the data
178         // is (i.e. the beginning of the file).
179         rewind(fp);
180
181         // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
182         // By clean we mean that the length of the first tag is written down.
183         // If this is the case and since the length of the first group HAS to be
184         // four (bytes), then determining the proper swap code is straightforward.
185
186         entCur = deb + 4;
187         s = str2num(entCur, guint32);
188         
189         switch (s) {
190         case 0x00040000 :
191                 sw = 3412;
192                 filetype = ACR;
193                 return;
194         case 0x04000000 :
195                 sw = 4321;
196                 filetype = ACR;
197                 return;
198         case 0x00000400 :
199                 sw = 2143;
200                 filetype = ACR;
201                 return;
202         case 0x00000004 :
203                 sw = 0;
204                 filetype = ACR;
205                 return;
206         default :
207                 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
208                                "ACR/NEMA unfound swap info (time to raise bets)");
209         }
210
211         // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
212         // It is time for despaired wild guesses. So, let's assume this file
213         // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
214         // not present. Then the only info we have is the net2host one.
215         if (! net2host )
216                 sw = 0;
217         else
218                 sw = 4321;
219         return;
220 }
221
222 void gdcmHeader::SwitchSwapToBigEndian(void) {
223         dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
224                        "Switching to BigEndian mode.");
225         if ( sw == 0    ) {
226                 sw = 4321;
227                 return;
228         }
229         if ( sw == 4321 ) {
230                 sw = 0;
231                 return;
232         }
233         if ( sw == 3412 ) {
234                 sw = 2143;
235                 return;
236         }
237         if ( sw == 2143 )
238                 sw = 3412;
239 }
240
241 void gdcmHeader::GetPixels(size_t lgrTotale, void* Pixels) {
242         size_t pixelsOffset; 
243         pixelsOffset = GetPixelOffset();
244         fseek(fp, pixelsOffset, SEEK_SET);
245         fread(Pixels, 1, lgrTotale, fp);
246 }
247
248
249
250 /**
251  * \ingroup   gdcmHeader
252  * \brief     Find the value representation of the current tag.
253  *
254  * @param sw  code swap
255  * @param skippedLength  pointeur sur nombre d'octets que l'on a saute qd
256  *                       la lecture est finie
257  * @param longueurLue    pointeur sur longueur (en nombre d'octets) 
258  *                       effectivement lue
259  * @return               longueur retenue pour le champ 
260  */
261  
262 // -->
263 // --> Oops
264 // --> C'etait la description de quoi, ca?
265 // -->
266
267 void gdcmHeader::FindVR( ElValue *ElVal) {
268         if (filetype != ExplicitVR)
269                 return;
270
271         char VR[3];
272         string vr;
273         int lgrLue;
274         long PositionOnEntry = ftell(fp);
275         // Warning: we believe this is explicit VR (Value Representation) because
276         // we used a heuristic that found "UL" in the first tag. Alas this
277         // doesn't guarantee that all the tags will be in explicit VR. In some
278         // cases (see e-film filtered files) one finds implicit VR tags mixed
279         // within an explicit VR file. Hence we make sure the present tag
280         // is in explicit VR and try to fix things if it happens not to be
281         // the case.
282         bool RealExplicit = true;
283         
284         lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
285         VR[2]=0;
286         vr = string(VR);
287                 
288         // Assume we are reading a falsely explicit VR file i.e. we reached
289         // a tag where we expect reading a VR but are in fact we read the
290         // first to bytes of the length. Then we will interogate (through find)
291         // the dicom_vr dictionary with oddities like "\004\0" which crashes
292         // both GCC and VC++ implementations of the STL map. Hence when the
293         // expected VR read happens to be non-ascii characters we consider
294         // we hit falsely explicit VR tag.
295
296         if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
297                 RealExplicit = false;
298
299         // CLEANME searching the dicom_vr at each occurence is expensive.
300         // PostPone this test in an optional integrity check at the end
301         // of parsing or only in debug mode.
302         if ( RealExplicit && !dicom_vr->count(vr) )
303                 RealExplicit = false;
304
305         if ( RealExplicit ) {
306                 if ( ElVal->IsVrUnknown() ) {
307                         // When not a dictionary entry, we can safely overwrite the vr.
308                         ElVal->SetVR(vr);
309                         return; 
310                 }
311                 if ( ElVal->GetVR() == vr ) {
312                         // The vr we just read and the dictionary agree. Nothing to do.
313                         return;
314                 }
315                 // The vr present in the file and the dictionary disagree. We assume
316                 // the file writer knew best and use the vr of the file. Since it would
317                 // be unwise to overwrite the vr of a dictionary (since it would
318                 // compromise it's next user), we need to clone the actual DictEntry
319                 // and change the vr for the read one.
320                 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
321                                            ElVal->GetElement(),
322                                            vr,
323                                            "FIXME",
324                                            ElVal->GetName());
325                 ElVal->SetDictEntry(NewTag);
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 ImplicitVRLittleEndian one.
347  *
348  * @return  True when ImplicitVRLittleEndian found. False in all other cases.
349  */
350 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
351         ElValue* Element = PubElVals.GetElementByNumber(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" )
357                 return true;
358         return false;
359 }
360
361 /**
362  * \ingroup gdcmHeader
363  * \brief   Determines if the Transfer Syntax was allready encountered
364  *          and if it corresponds to a ExplicitVRLittleEndian one.
365  *
366  * @return  True when ExplicitVRLittleEndian found. False in all other cases.
367  */
368 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
369         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
370         if ( !Element )
371                 return false;
372         LoadElementValueSafe(Element);
373         string Transfer = Element->GetValue();
374         if ( Transfer == "1.2.840.10008.1.2.1" )
375                 return true;
376         return false;
377 }
378
379 /**
380  * \ingroup gdcmHeader
381  * \brief   Determines if the Transfer Syntax was allready encountered
382  *          and if it corresponds to a DeflatedExplicitVRLittleEndian one.
383  *
384  * @return  True when DeflatedExplicitVRLittleEndian found. False in all other cases.
385  */
386 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
387         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
388         if ( !Element )
389                 return false;
390         LoadElementValueSafe(Element);
391         string Transfer = Element->GetValue();
392         if ( Transfer == "1.2.840.10008.1.2.1.99" )
393                 return true;
394         return false;
395 }
396
397
398 /**
399  * \ingroup gdcmHeader
400  * \brief   Determines if the Transfer Syntax was allready encountered
401  *          and if it corresponds to a Explicit VR Big Endian one.
402  *
403  * @return  True when big endian found. False in all other cases.
404  */
405 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
406         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
407         if ( !Element )
408                 return false;
409         LoadElementValueSafe(Element);
410         string Transfer = Element->GetValue();
411         if ( Transfer == "1.2.840.10008.1.2.2" )
412                 return true;
413         return false;
414 }
415
416
417 /**
418  * \ingroup gdcmHeader
419  * \brief   Determines if the Transfer Syntax was allready encountered
420  *          and if it corresponds to a JPEGBaseLineProcess1 one.
421  *
422  * @return  True when JPEGBaseLineProcess1found. False in all other cases.
423  */
424 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
425         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
426         if ( !Element )
427                 return false;
428         LoadElementValueSafe(Element);
429         string Transfer = Element->GetValue();
430         if ( Transfer == "1.2.840.10008.1.2.4.50" )
431                 return true;
432         return false;
433 }
434
435 /**
436  * \ingroup gdcmHeader
437  * \brief   Determines if the Transfer Syntax was allready encountered
438  *          and if it corresponds to a JPEGExtendedProcess2-4 one.
439  *
440  * @return  True when JPEGExtendedProcess2-4 found. False in all other cases.
441  */
442 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
443         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
444         if ( !Element )
445                 return false;
446         LoadElementValueSafe(Element);
447         string Transfer = Element->GetValue();
448         if ( Transfer == "1.2.840.10008.1.2.4.51" )
449                 return true;
450         return false;
451 }
452
453
454 /**
455  * \ingroup gdcmHeader
456  * \brief   Determines if the Transfer Syntax was allready encountered
457  *          and if it corresponds to a JPEGExtendeProcess3-5 one.
458  *
459  * @return  True when JPEGExtendedProcess3-5 found. False in all other cases.
460  */
461 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
462         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
463         if ( !Element )
464                 return false;
465         LoadElementValueSafe(Element);
466         string Transfer = Element->GetValue();
467         if ( Transfer == "1.2.840.10008.1.2.4.52" )
468                 return true;
469         return false;
470 }
471
472 /**
473  * \ingroup gdcmHeader
474  * \brief   Determines if the Transfer Syntax was allready encountered
475  *          and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
476  *
477  * @return  True when JPEGSpectralSelectionProcess6-8 found. False in all other cases.
478  */
479 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
480         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
481         if ( !Element )
482                 return false;
483         LoadElementValueSafe(Element);
484         string Transfer = Element->GetValue();
485         if ( Transfer == "1.2.840.10008.1.2.4.53" )
486                 return true;
487         return false;
488 }
489
490 //
491 // Euhhhhhhh
492 // Il y en a encore DIX-SEPT, comme ça.
493 // Il faudrait trouver qq chose + rusé ...
494 //
495
496
497 void gdcmHeader::FixFoundLength(ElValue * ElVal, guint32 FoundLength) {
498         // Heuristic: a final fix.
499         if ( FoundLength == 0xffffffff)
500                 FoundLength = 0;
501         ElVal->SetLength(FoundLength);
502 }
503
504 guint32 gdcmHeader::FindLengthOB(void) {
505         // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
506         guint16 g;
507         guint16 n; 
508         long PositionOnEntry = ftell(fp);
509         bool FoundSequenceDelimiter = false;
510         guint32 TotalLength = 0;
511         guint32 ItemLength;
512
513         while ( ! FoundSequenceDelimiter) {
514                 g = ReadInt16();
515                 n = ReadInt16();
516                 TotalLength += 4;  // We even have to decount the group and element 
517                 if ( g != 0xfffe ) {
518                         dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
519                                     "wrong group for an item sequence.");
520                         throw Error::FileReadError(fp, "gdcmHeader::FindLengthOB");
521                 }
522                 if ( n == 0xe0dd )
523                         FoundSequenceDelimiter = true;
524                 else if ( n != 0xe000) {
525                         dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
526                                     "wrong element for an item sequence.");
527                         throw Error::FileReadError(fp, "gdcmHeader::FindLengthOB");
528                 }
529                 ItemLength = ReadInt32();
530                 TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
531                                                 // the ItemLength with ReadInt32
532                 SkipBytes(ItemLength);
533         }
534         fseek(fp, PositionOnEntry, SEEK_SET);
535         return TotalLength;
536 }
537
538 void gdcmHeader::FindLength(ElValue * ElVal) {
539         guint16 element = ElVal->GetElement();
540         string  vr      = ElVal->GetVR();
541         guint16 length16;
542         
543         if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
544
545                 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
546                         // The following reserved two bytes (see PS 3.5-2001, section
547                         // 7.1.2 Data element structure with explicit vr p27) must be
548                         // skipped before proceeding on reading the length on 4 bytes.
549                         fseek(fp, 2L, SEEK_CUR);
550                         guint32 length32 = ReadInt32();
551                         if ( (vr == "OB") && (length32 == 0xffffffff) ) {
552                                 ElVal->SetLength(FindLengthOB());
553                                 return;
554                         }
555                         FixFoundLength(ElVal, length32);
556                         return;
557                 }
558
559                 // Length is encoded on 2 bytes.
560                 length16 = ReadInt16();
561                 
562                 // We can tell the current file is encoded in big endian (like
563                 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
564                 // and it's value is the one of the encoding of a big endian file.
565                 // In order to deal with such big endian encoded files, we have
566                 // (at least) two strategies:
567                 // * when we load the "Transfer Syntax" tag with value of big endian
568                 //   encoding, we raise the proper flags. Then we wait for the end
569                 //   of the META group (0x0002) among which is "Transfer Syntax",
570                 //   before switching the swap code to big endian. We have to postpone
571                 //   the switching of the swap code since the META group is fully encoded
572                 //   in little endian, and big endian coding only starts at the next
573                 //   group. The corresponding code can be hard to analyse and adds
574                 //   many additional unnecessary tests for regular tags.
575                 // * the second strategy consist in waiting for trouble, that shall appear
576                 //   when we find the first group with big endian encoding. This is
577                 //   easy to detect since the length of a "Group Length" tag (the
578                 //   ones with zero as element number) has to be of 4 (0x0004). When we
579                 //   encouter 1024 (0x0400) chances are the encoding changed and we
580                 //   found a group with big endian encoding.
581                 // We shall use this second strategy. In order make sure that we
582                 // can interpret the presence of an apparently big endian encoded
583                 // length of a "Group Length" without committing a big mistake, we
584                 // add an additional check: we look in the allready parsed elements
585                 // for the presence of a "Transfer Syntax" whose value has to be "big
586                 // endian encoding". When this is the case, chances are we got our
587                 // hands on a big endian encoded file: we switch the swap code to
588                 // big endian and proceed...
589                 if ( (element  == 0x000) && (length16 == 0x0400) ) {
590                         if ( ! IsExplicitVRBigEndianTransferSyntax() )
591                                 throw Error::FileReadError(fp, "gdcmHeader::FindLength");
592                         length16 = 4;
593                         SwitchSwapToBigEndian();
594                         // Restore the unproperly loaded values i.e. the group, the element
595                         // and the dictionary entry depending on them.
596                         guint16 CorrectGroup   = SwapShort(ElVal->GetGroup());
597                         guint16 CorrectElem    = SwapShort(ElVal->GetElement());
598                         gdcmDictEntry * NewTag = IsInDicts(CorrectGroup, CorrectElem);
599                         if (!NewTag) {
600                                 // This correct tag is not in the dictionary. Create a new one.
601                                 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
602                         }
603                         // FIXME this can create a memory leaks on the old entry that be
604                         // left unreferenced.
605                         ElVal->SetDictEntry(NewTag);
606                 }
607                  
608                 // Heuristic: well some files are really ill-formed.
609                 if ( length16 == 0xffff) {
610                         length16 = 0;
611                         dbg.Verbose(0, "gdcmHeader::FindLength",
612                                     "Erroneous element length fixed.");
613                 }
614                 FixFoundLength(ElVal, (guint32)length16);
615                 return;
616         }
617
618         // Either implicit VR or a non DICOM conformal (see not below) explicit
619         // VR that ommited the VR of (at least) this element. Farts happen.
620         // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
621         // on Data elements "Implicit and Explicit VR Data Elements shall
622         // not coexist in a Data Set and Data Sets nested within it".]
623         // Length is on 4 bytes.
624         FixFoundLength(ElVal, ReadInt32());
625 }
626
627 /**
628  * \ingroup gdcmHeader
629  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
630  *          processor order.
631  *
632  * @return  The suggested integer.
633  */
634 guint32 gdcmHeader::SwapLong(guint32 a) {
635         // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
636         switch (sw) {
637         case    0 :
638                 break;
639         case 4321 :
640                 a=(   ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000)    | 
641                       ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
642                 break;
643         
644         case 3412 :
645                 a=(   ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
646                 break;
647         
648         case 2143 :
649                 a=(    ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
650                 break;
651         default :
652                 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
653                 a=0;
654         }
655         return(a);
656 }
657
658 /**
659  * \ingroup gdcmHeader
660  * \brief   Swaps the bytes so they agree with the processor order
661  * @return  The properly swaped 16 bits integer.
662  */
663 guint16 gdcmHeader::SwapShort(guint16 a) {
664         if ( (sw==4321)  || (sw==2143) )
665                 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
666         return (a);
667 }
668
669 void gdcmHeader::SkipBytes(guint32 NBytes) {
670         //FIXME don't dump the returned value
671         (void)fseek(fp, (long)NBytes, SEEK_CUR);
672 }
673
674 void gdcmHeader::SkipElementValue(ElValue * ElVal) {
675         SkipBytes(ElVal->GetLength());
676 }
677
678 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
679         if (NewSize < 0)
680                 return;
681         if ((guint32)NewSize >= (guint32)0xffffffff) {
682                 MaxSizeLoadElementValue = 0xffffffff;
683                 return;
684         }
685         MaxSizeLoadElementValue = NewSize;
686 }
687
688 /**
689  * \ingroup       gdcmHeader
690  * \brief         Loads the element if it's size is not to big.
691  * @param ElVal   Element whose value shall be loaded. 
692  * @param MaxSize Size treshold above which the element value is not
693  *                loaded in memory. The element value is allways loaded
694  *                when MaxSize is equal to UINT32_MAX.
695  * @return  
696  */
697 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
698         size_t item_read;
699         guint16 group  = ElVal->GetGroup();
700         guint16 elem   = ElVal->GetElement();
701         string  vr     = ElVal->GetVR();
702         guint32 length = ElVal->GetLength();
703         bool SkipLoad  = false;
704
705         fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
706         
707         // Sequences not treated yet !
708         //
709         // Ne faudrait-il pas au contraire trouver immediatement
710         // une maniere 'propre' de traiter les sequences (vr = SQ)
711         // car commencer par les ignorer risque de conduire a qq chose
712         // qui pourrait ne pas etre generalisable
713         //
714         if( vr == "SQ" )
715                 SkipLoad = true;
716
717         // Heuristic : a sequence "contains" a set of tags (called items). It looks
718         // like the last tag of a sequence (the one that terminates the sequence)
719         // has a group of 0xfffe (with a dummy length).
720         if( group == 0xfffe )
721                 SkipLoad = true;
722
723         // The group length doesn't represent data to be loaded in memory, since
724         // each element of the group shall be loaded individualy.
725         if( elem == 0 )
726                 SkipLoad = true;
727
728         if ( SkipLoad ) {
729                           // FIXME the following skip is not necessary
730                 SkipElementValue(ElVal);
731                 ElVal->SetLength(0);
732                 ElVal->SetValue("gdcm::Skipped");
733                 return;
734         }
735
736         // When the length is zero things are easy:
737         if ( length == 0 ) {
738                 ElVal->SetValue("");
739                 return;
740         }
741
742         // Values bigger than specified are not loaded.
743         //
744         // En fait, c'est les elements dont la longueur est superieure 
745         // a celle fixee qui ne sont pas charges
746         //
747         if (length > MaxSizeLoadElementValue) {
748                 ostringstream s;
749                 s << "gdcm::NotLoaded.";
750                 s << " Address:" << (long)ElVal->GetOffset();
751                 s << " Length:"  << ElVal->GetLength();
752                 //mesg += " Length:"  + ElVal->GetLength();
753                 ElVal->SetValue(s.str());
754                 return;
755         }
756         
757         // When an integer is expected, read and convert the following two or
758         // four bytes properly i.e. as an integer as opposed to a string.
759         if ( IsAnInteger(ElVal) ) {
760                 guint32 NewInt;
761                 if( length == 2 ) {
762                         NewInt = ReadInt16();
763                 } else if( length == 4 ) {
764                         NewInt = ReadInt32();
765                 } else
766                         dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
767                 
768                 //FIXME: make the following an util fonction
769                 ostringstream s;
770                 s << NewInt;
771                 ElVal->SetValue(s.str());
772                 return;
773         }
774         
775         // FIXME The exact size should be length if we move to strings or whatever
776         
777         //
778         // QUESTION : y a-t-il une raison pour ne pas utiliser g_malloc ici ?
779         //
780         
781         char* NewValue = (char*)malloc(length+1);
782         if( !NewValue) {
783                 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
784                 return;
785         }
786         NewValue[length]= 0;
787         
788         item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
789         if ( item_read != 1 ) {
790                 free(NewValue);
791                 Error::FileReadError(fp, "gdcmHeader::LoadElementValue");
792                 ElVal->SetValue("gdcm::UnRead");
793                 return;
794         }
795         ElVal->SetValue(NewValue);
796 }
797
798 /**
799  * \ingroup       gdcmHeader
800  * \brief         Loads the element while preserving the current
801  *                underlying file position indicator as opposed to
802  *                to LoadElementValue that modifies it.
803  * @param ElVal   Element whose value shall be loaded. 
804  * @return  
805  */
806 void gdcmHeader::LoadElementValueSafe(ElValue * ElVal) {
807         long PositionOnEntry = ftell(fp);
808         LoadElementValue(ElVal);
809         fseek(fp, PositionOnEntry, SEEK_SET);
810 }
811
812
813 guint16 gdcmHeader::ReadInt16(void) {
814         guint16 g;
815         size_t item_read;
816         item_read = fread (&g, (size_t)2,(size_t)1, fp);
817         if ( item_read != 1 )
818                 throw Error::FileReadError(fp, "gdcmHeader::ReadInt16");
819         g = SwapShort(g);
820         return g;
821 }
822
823 guint32 gdcmHeader::ReadInt32(void) {
824         guint32 g;
825         size_t item_read;
826         item_read = fread (&g, (size_t)4,(size_t)1, fp);
827         if ( item_read != 1 )
828                 throw Error::FileReadError(fp, "gdcmHeader::ReadInt32");
829         g = SwapLong(g);
830         return g;
831 }
832
833 /**
834  * \ingroup gdcmHeader
835  * \brief   Read the next tag without loading it's value
836  * @return  On succes the newly created ElValue, NULL on failure.      
837  */
838
839 ElValue * gdcmHeader::ReadNextElement(void) {
840         guint16 g;
841         guint16 n;
842         ElValue * NewElVal;
843         
844         try {
845                 g = ReadInt16();
846                 n = ReadInt16();
847         }
848         catch ( Error::FileReadError ) {
849                 // We reached the EOF (or an error occured) and header parsing
850                 // has to be considered as finished.
851                 return (ElValue *)0;
852         }
853
854         // Find out if the tag we encountered is in the dictionaries:
855         gdcmDictEntry * NewTag = IsInDicts(g, n);
856         if (!NewTag)
857                 NewTag = new gdcmDictEntry(g, n);
858
859         NewElVal = new ElValue(NewTag);
860         if (!NewElVal) {
861                 dbg.Verbose(1, "ReadNextElement: failed to allocate ElValue");
862                 return (ElValue*)0;
863         }
864
865         FindVR(NewElVal);
866         try { FindLength(NewElVal); }
867         catch ( Error::FileReadError ) { // Call it quits
868                 return (ElValue *)0;
869         }
870         NewElVal->SetOffset(ftell(fp));
871         return NewElVal;
872 }
873
874 bool gdcmHeader::IsAnInteger(ElValue * ElVal) {
875         guint16 group   = ElVal->GetGroup();
876         guint16 element = ElVal->GetElement();
877         string  vr      = ElVal->GetVR();
878         guint32 length  = ElVal->GetLength();
879
880         // When we have some semantics on the element we just read, and if we
881         // a priori know we are dealing with an integer, then we shall be
882         // able to swap it's element value properly.
883         if ( element == 0 )  {  // This is the group length of the group
884                 if (length == 4)
885                         return true;
886                 else
887                         dbg.Error("gdcmHeader::IsAnInteger",
888                                   "Erroneous Group Length element length.");
889         }
890         
891         if ( group % 2 != 0 )
892                 // We only have some semantics on documented elements, which are
893                 // the even ones.
894                 return false;
895         
896         if ( (length != 4) && ( length != 2) )
897                 // Swapping only make sense on integers which are 2 or 4 bytes long.
898                 return false;
899         
900         if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
901                 return true;
902         
903         if ( (group == 0x0028) && (element == 0x0005) )
904                 // This tag is retained from ACR/NEMA
905                 // CHECKME Why should "Image Dimensions" be a single integer ?
906                 //
907                 // "Image Dimensions", c'est en fait le 'nombre de dimensions'
908                 // de l'objet ACR-NEMA stocké
909                 // 1 : Signal
910                 // 2 : Image
911                 // 3 : Volume
912                 // 4 : Sequence
913                 //
914                 // DICOM V3 ne retient pas cette information
915                 // Par defaut, tout est 'Image',
916                 // C'est a l'utilisateur d'explorer l'ensemble des entetes
917                 // pour savoir à quoi il a a faire
918                 //
919                 // Le Dicom Multiframe peut etre utilise pour stocker,
920                 // dans un seul fichier, une serie temporelle (cardio vasculaire GE, p.ex)
921                 // ou un volume (medecine Nucleaire, p.ex)
922                 //
923                 return true;
924         
925         if ( (group == 0x0028) && (element == 0x0200) )
926                 // This tag is retained from ACR/NEMA
927                 return true;
928         
929         return false;
930 }
931
932 /**
933  * \ingroup gdcmHeader
934  * \brief   Recover the offset (from the beginning of the file) of the pixels.
935  */
936 size_t gdcmHeader::GetPixelOffset(void) {
937         // If this file complies with the norm we should encounter the
938         // "Image Location" tag (0x0028,  0x0200). This tag contains the
939         // the group that contains the pixel data (hence the "Pixel Data"
940         // is found by indirection through the "Image Location").
941         // Inside the group pointed by "Image Location" the searched element
942         // is conventionally the element 0x0010 (when the norm is respected).
943         //    When the "Image Location" is absent we default to group 0x7fe0.
944         guint16 grPixel;
945         guint16 numPixel;
946         string ImageLocation = GetPubElValByName("Image Location");
947         if ( ImageLocation == "UNFOUND" ) {
948                 grPixel = 0x7fe0;
949         } else {
950                 grPixel = (guint16) atoi( ImageLocation.c_str() );
951         }
952         if (grPixel != 0x7fe0)
953                 // FIXME is this still necessary ?
954                 // Now, this looks like an old dirty fix for Philips imager
955                 numPixel = 0x1010;
956         else
957                 numPixel = 0x0010;
958         ElValue* PixelElement = PubElVals.GetElementByNumber(grPixel, numPixel);
959         if (PixelElement)
960                 return PixelElement->GetOffset();
961         else
962                 return 0;
963 }
964
965 gdcmDictEntry * gdcmHeader::IsInDicts(guint32 group, guint32 element) {
966         //
967         // Y a-t-il une raison de lui passer des guint32
968         // alors que group et element sont des guint16?
969         //
970         gdcmDictEntry * found = (gdcmDictEntry*)0;
971         if (!RefPubDict && !RefShaDict) {
972                 //FIXME build a default dictionary !
973                 printf("FIXME in gdcmHeader::IsInDicts\n");
974         }
975         if (RefPubDict) {
976                 found = RefPubDict->GetTag(group, element);
977                 if (found)
978                         return found;
979         }
980         if (RefShaDict) {
981                 found = RefShaDict->GetTag(group, element);
982                 if (found)
983                         return found;
984         }
985         return found;
986 }
987
988 list<string> * gdcmHeader::GetPubTagNames(void) {
989         list<string> * Result = new list<string>;
990         TagHT entries = RefPubDict->GetEntries();
991
992         for (TagHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
993       Result->push_back( tag->second->GetName() );
994         }
995         return Result;
996 }
997
998 map<string, list<string> > * gdcmHeader::GetPubTagNamesByCategory(void) {
999         map<string, list<string> > * Result = new map<string, list<string> >;
1000         TagHT entries = RefPubDict->GetEntries();
1001
1002         for (TagHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
1003                 (*Result)[tag->second->GetFourth()].push_back(tag->second->GetName());
1004         }
1005         return Result;
1006 }
1007
1008 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1009         return PubElVals.GetElValueByNumber(group, element);
1010 }
1011
1012 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1013         ElValue* elem =  PubElVals.GetElementByNumber(group, element);
1014         if ( !elem )
1015                 return "gdcm::Unfound";
1016         return elem->GetVR();
1017 }
1018
1019 string gdcmHeader::GetPubElValByName(string TagName) {
1020         return PubElVals.GetElValueByName(TagName);
1021 }
1022
1023 string gdcmHeader::GetPubElValRepByName(string TagName) {
1024         ElValue* elem =  PubElVals.GetElementByName(TagName);
1025         if ( !elem )
1026                 return "gdcm::Unfound";
1027         return elem->GetVR();
1028 }
1029
1030 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1031         return ShaElVals.GetElValueByNumber(group, element);
1032 }
1033
1034 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1035         ElValue* elem =  ShaElVals.GetElementByNumber(group, element);
1036         if ( !elem )
1037                 return "gdcm::Unfound";
1038         return elem->GetVR();
1039 }
1040
1041 string gdcmHeader::GetShaElValByName(string TagName) {
1042         return ShaElVals.GetElValueByName(TagName);
1043 }
1044
1045 string gdcmHeader::GetShaElValRepByName(string TagName) {
1046         ElValue* elem =  ShaElVals.GetElementByName(TagName);
1047         if ( !elem )
1048                 return "gdcm::Unfound";
1049         return elem->GetVR();
1050 }
1051
1052
1053 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1054         string pub = GetPubElValByNumber(group, element);
1055         if (pub.length())
1056                 return pub;
1057         return GetShaElValByNumber(group, element);
1058 }
1059
1060 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1061         string pub = GetPubElValRepByNumber(group, element);
1062         if (pub.length())
1063                 return pub;
1064         return GetShaElValRepByNumber(group, element);
1065 }
1066
1067 string gdcmHeader::GetElValByName(string TagName) {
1068         string pub = GetPubElValByName(TagName);
1069         if (pub.length())
1070                 return pub;
1071         return GetShaElValByName(TagName);
1072 }
1073
1074 string gdcmHeader::GetElValRepByName(string TagName) {
1075         string pub = GetPubElValRepByName(TagName);
1076         if (pub.length())
1077                 return pub;
1078         return GetShaElValRepByName(TagName);
1079 }
1080
1081 /**
1082  * \ingroup gdcmHeader
1083  * \brief   Parses the header of the file but does NOT load element values.
1084  */
1085 void gdcmHeader::ParseHeader(void) {
1086         ElValue * newElValue = (ElValue *)0;
1087         
1088         rewind(fp);
1089         CheckSwap();
1090         while ( (newElValue = ReadNextElement()) ) {
1091                 SkipElementValue(newElValue);
1092                 PubElVals.Add(newElValue);
1093         }
1094 }
1095
1096 /**
1097  * \ingroup gdcmHeader
1098  * \brief   Loads the element values of all the elements present in the
1099  *          public tag based hash table.
1100  */
1101 void gdcmHeader::LoadElements(void) {
1102
1103         if (DEBUG) printf("LoadElements : Entree\n");
1104
1105         rewind(fp);   
1106         if (DEBUG) printf("LoadElements : rewind\n");
1107
1108         TagElValueHT ht = PubElVals.GetTagHt();
1109         
1110         if (DEBUG) printf("LoadElements : GetTagHt\n");
1111
1112         for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1113                 LoadElementValue(tag->second);
1114                 }
1115 }
1116
1117 void gdcmHeader::PrintPubElVal(ostream & os) {
1118         PubElVals.Print(os);
1119 }
1120
1121 void gdcmHeader::PrintPubDict(ostream & os) {
1122         RefPubDict->Print(os);
1123 }