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