]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
a01595f8198d7034faebeb2bf1ed56f66e803ebc
[gdcm.git] / src / gdcmHeader.cxx
1 // gdcmHeader.cxx
2
3 #include <stdio.h>
4 #include <cerrno>
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 <sstream>
13 #include "gdcmUtil.h"
14 #include "gdcmHeader.h"
15
16 #define HEADER_LENGTH_TO_READ           256     // on ne lit plus que le debut
17 #define _MaxSizeLoadElementValue_       1024    // longueur au dela de laquelle on ne charge plus les valeurs 
18
19 //FIXME: this looks dirty to me...
20
21 #define str2num(str, typeNum) *((typeNum *)(str))
22
23 // str est un pointeur dans un tableau de caractères, qui doit contenir, 
24 // à cet endroit la, la représentation binaire d'un entier (16 ou 32 bits)
25 // je veux récupérer ça ... dans un entier.
26 // s'il y a une autre solution, évitant des cast et les indirections,
27 // je suis preneur
28
29 VRHT * gdcmHeader::dicom_vr = (VRHT*)0;
30
31 void gdcmHeader::Initialise(void) {
32         if (!gdcmHeader::dicom_vr)
33                 InitVRDict();
34         Dicts = new gdcmDictSet();
35         RefPubDict = Dicts->GetDefaultPubDict();
36         RefShaDict = (gdcmDict*)0;
37 }
38
39
40 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error) 
41   throw(gdcmFileError) {
42   SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
43   filename = InFilename;
44   Initialise();
45   fp=fopen(InFilename,"rb");
46   if(exception_on_error) {
47     if(!fp)
48       throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
49   }
50   else
51     dbg.Error(!fp, "gdcmHeader::gdcmHeader cannot open file", InFilename);
52   ParseHeader();
53   AddAndDefaultElements();
54 }
55
56
57 gdcmHeader::~gdcmHeader (void) {
58         fclose(fp);
59         return;
60 }
61
62 void gdcmHeader::InitVRDict (void) {
63         if (dicom_vr) {
64                 dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
65                 return;
66         }
67         VRHT *vr = new VRHT;
68         (*vr)["AE"] = "Application Entity";       // At most 16 bytes
69         (*vr)["AS"] = "Age String";               // Exactly 4 bytes
70         (*vr)["AT"] = "Attribute Tag";            // 2 16-bit unsigned short integers
71         (*vr)["CS"] = "Code String";              // At most 16 bytes
72         (*vr)["DA"] = "Date";                     // Exactly 8 bytes
73         (*vr)["DS"] = "Decimal String";           // At most 16 bytes
74         (*vr)["DT"] = "Date Time";                // At most 26 bytes
75         (*vr)["FL"] = "Floating Point Single";    // 32-bit IEEE 754:1985 float
76         (*vr)["FD"] = "Floating Point Double";    // 64-bit IEEE 754:1985 double
77         (*vr)["IS"] = "Integer String";           // At most 12 bytes
78         (*vr)["LO"] = "Long String";              // At most 64 chars
79         (*vr)["LT"] = "Long Text";                // At most 10240 chars
80         (*vr)["OB"] = "Other Byte String";        // String of bytes (vr independant)
81         (*vr)["OW"] = "Other Word String";        // String of 16-bit words (vr dep)
82         (*vr)["PN"] = "Person Name";              // At most 64 chars
83         (*vr)["SH"] = "Short String";             // At most 16 chars
84         (*vr)["SL"] = "Signed Long";              // Exactly 4 bytes
85         (*vr)["SQ"] = "Sequence of Items";        // Not Applicable
86         (*vr)["SS"] = "Signed Short";             // Exactly 2 bytes
87         (*vr)["ST"] = "Short Text";               // At most 1024 chars
88         (*vr)["TM"] = "Time";                     // At most 16 bytes
89         (*vr)["UI"] = "Unique Identifier";        // At most 64 bytes
90         (*vr)["UL"] = "Unsigned Long ";           // Exactly 4 bytes
91         (*vr)["UN"] = "Unknown";                  // Any length of bytes
92         (*vr)["US"] = "Unsigned Short ";          // Exactly 2 bytes
93         (*vr)["UT"] = "Unlimited Text";           // At most 2^32 -1 chars
94    dicom_vr = vr;       
95 }
96
97 /**
98  * \ingroup gdcmHeader
99  * \brief   Discover what the swap code is (among little endian, big endian,
100  *          bad little endian, bad big endian).
101  *
102  */
103 void gdcmHeader::CheckSwap()
104 {
105         // The only guaranted way of finding the swap code is to find a
106         // group tag since we know it's length has to be of four bytes i.e.
107         // 0x00000004. Finding the swap code in then straigthforward. Trouble
108         // occurs when we can't find such group...
109         guint32  s;
110         guint32  x=4;  // x : pour ntohs
111         bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
112          
113         int lgrLue;
114         char * entCur;
115         char deb[HEADER_LENGTH_TO_READ];
116          
117         // First, compare HostByteOrder and NetworkByteOrder in order to
118         // determine if we shall need to swap bytes (i.e. the Endian type).
119         if (x==ntohs(x))
120                 net2host = true;
121         else
122                 net2host = false;
123         
124         // The easiest case is the one of a DICOM header, since it possesses a
125         // file preamble where it suffice to look for the string "DICM".
126         lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
127         
128         entCur = deb + 128;
129         if(memcmp(entCur, "DICM", (size_t)4) == 0) {
130                 filetype = TrueDicom;
131                 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
132         } else {
133                 filetype = Unknown;
134                 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
135         }
136
137         if(filetype == TrueDicom) {
138                 // Next, determine the value representation (VR). Let's skip to the
139                 // first element (0002, 0000) and check there if we find "UL", in
140                 // which case we (almost) know it is explicit VR.
141                 // WARNING: if it happens to be implicit VR then what we will read
142                 // is the length of the group. If this ascii representation of this
143                 // length happens to be "UL" then we shall believe it is explicit VR.
144                 // FIXME: in order to fix the above warning, we could read the next
145                 // element value (or a couple of elements values) in order to make
146                 // sure we are not commiting a big mistake.
147                 // We need to skip :
148                 // * the 128 bytes of File Preamble (often padded with zeroes),
149                 // * the 4 bytes of "DICM" string,
150                 // * the 4 bytes of the first tag (0002, 0000),
151                 // i.e. a total of  136 bytes.
152                 entCur = deb + 136;
153                 if(memcmp(entCur, "UL", (size_t)2) == 0) {
154                         filetype = ExplicitVR;
155                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
156                                     "explicit Value Representation");
157                 } else {
158                         filetype = ImplicitVR;
159                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
160                                     "not an explicit Value Representation");
161                 }
162
163                 if (net2host) {
164                         sw = 4321;
165                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
166                                        "HostByteOrder != NetworkByteOrder");
167                 } else {
168                         sw = 0;
169                         dbg.Verbose(1, "gdcmHeader::CheckSwap:",
170                                        "HostByteOrder = NetworkByteOrder");
171                 }
172                 
173                 // Position the file position indicator at first tag (i.e.
174                 // after the file preamble and the "DICM" string).
175                 rewind(fp);
176                 fseek (fp, 132L, SEEK_SET);
177                 return;
178         } // End of TrueDicom
179
180         // Alas, this is not a DicomV3 file and whatever happens there is no file
181         // preamble. We can reset the file position indicator to where the data
182         // is (i.e. the beginning of the file).
183         rewind(fp);
184
185         // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
186         // By clean we mean that the length of the first tag is written down.
187         // If this is the case and since the length of the first group HAS to be
188         // four (bytes), then determining the proper swap code is straightforward.
189
190         entCur = deb + 4;
191         s = str2num(entCur, guint32);
192         
193         switch (s) {
194         case 0x00040000 :
195                 sw = 3412;
196                 filetype = ACR;
197                 return;
198         case 0x04000000 :
199                 sw = 4321;
200                 filetype = ACR;
201                 return;
202         case 0x00000400 :
203                 sw = 2143;
204                 filetype = ACR;
205                 return;
206         case 0x00000004 :
207                 sw = 0;
208                 filetype = ACR;
209                 return;
210         default :
211                 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
212                                "ACR/NEMA unfound swap info (time to raise bets)");
213         }
214
215         // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
216         // It is time for despaired wild guesses. So, let's assume this file
217         // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
218         // not present. Then the only info we have is the net2host one.
219         if (! net2host )
220                 sw = 0;
221         else
222                 sw = 4321;
223         return;
224 }
225
226 void gdcmHeader::SwitchSwapToBigEndian(void) {
227         dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
228                        "Switching to BigEndian mode.");
229         if ( sw == 0    ) {
230                 sw = 4321;
231                 return;
232         }
233         if ( sw == 4321 ) {
234                 sw = 0;
235                 return;
236         }
237         if ( sw == 3412 ) {
238                 sw = 2143;
239                 return;
240         }
241         if ( sw == 2143 )
242                 sw = 3412;
243 }
244
245 void gdcmHeader::GetPixels(size_t lgrTotale, void* _Pixels) {
246         size_t pixelsOffset; 
247         pixelsOffset = GetPixelOffset();
248         fseek(fp, pixelsOffset, SEEK_SET);
249         fread(_Pixels, 1, lgrTotale, fp);
250 }
251
252
253
254 /**
255  * \ingroup   gdcmHeader
256  * \brief     Find the value representation of the current tag.
257  */
258 void gdcmHeader::FindVR( ElValue *ElVal) {
259         if (filetype != ExplicitVR)
260                 return;
261
262         char VR[3];
263         string vr;
264         int lgrLue;
265         long PositionOnEntry = ftell(fp);
266         // Warning: we believe this is explicit VR (Value Representation) because
267         // we used a heuristic that found "UL" in the first tag. Alas this
268         // doesn't guarantee that all the tags will be in explicit VR. In some
269         // cases (see e-film filtered files) one finds implicit VR tags mixed
270         // within an explicit VR file. Hence we make sure the present tag
271         // is in explicit VR and try to fix things if it happens not to be
272         // the case.
273         bool RealExplicit = true;
274         
275         lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
276         VR[2]=0;
277         vr = string(VR);
278                 
279         // Assume we are reading a falsely explicit VR file i.e. we reached
280         // a tag where we expect reading a VR but are in fact we read the
281         // first to bytes of the length. Then we will interogate (through find)
282         // the dicom_vr dictionary with oddities like "\004\0" which crashes
283         // both GCC and VC++ implementations of the STL map. Hence when the
284         // expected VR read happens to be non-ascii characters we consider
285         // we hit falsely explicit VR tag.
286
287         if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
288                 RealExplicit = false;
289
290         // CLEANME searching the dicom_vr at each occurence is expensive.
291         // PostPone this test in an optional integrity check at the end
292         // of parsing or only in debug mode.
293         if ( RealExplicit && !dicom_vr->count(vr) )
294                 RealExplicit = false;
295
296         if ( RealExplicit ) {
297                 if ( ElVal->IsVrUnknown() ) {
298                         // When not a dictionary entry, we can safely overwrite the vr.
299                         ElVal->SetVR(vr);
300                         return; 
301                 }
302                 if ( ElVal->GetVR() == vr ) {
303                         // The vr we just read and the dictionary agree. Nothing to do.
304                         return;
305                 }
306                 // The vr present in the file and the dictionary disagree. We assume
307                 // the file writer knew best and use the vr of the file. Since it would
308                 // be unwise to overwrite the vr of a dictionary (since it would
309                 // compromise it's next user), we need to clone the actual DictEntry
310                 // and change the vr for the read one.
311                 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
312                                            ElVal->GetElement(),
313                                            vr,
314                                            "FIXME",
315                                            ElVal->GetName());
316                 ElVal->SetDictEntry(NewTag);
317                 return; 
318         }
319         
320         // We thought this was explicit VR, but we end up with an
321         // implicit VR tag. Let's backtrack.
322         dbg.Verbose(1, "gdcmHeader::FindVR:", "Falsely explicit vr file");
323         fseek(fp, PositionOnEntry, SEEK_SET);
324         // When this element is known in the dictionary we shall use, e.g. for
325         // the semantics (see  the usage of IsAnInteger), the vr proposed by the
326         // dictionary entry. Still we have to flag the element as implicit since
327         // we know now our assumption on expliciteness is not furfilled.
328         // avoid  .
329         if ( ElVal->IsVrUnknown() )
330                 ElVal->SetVR("Implicit");
331         ElVal->SetImplicitVr();
332 }
333
334 /**
335  * \ingroup gdcmHeader
336  * \brief   Determines if the Transfer Syntax was allready encountered
337  *          and if it corresponds to a ImplicitVRLittleEndian one.
338  *
339  * @return  True when ImplicitVRLittleEndian found. False in all other cases.
340  */
341 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
342         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
343         if ( !Element )
344                 return false;
345         LoadElementValueSafe(Element);
346         string Transfer = Element->GetValue();
347         if ( Transfer == "1.2.840.10008.1.2" )
348                 return true;
349         return false;
350 }
351
352 /**
353  * \ingroup gdcmHeader
354  * \brief   Determines if the Transfer Syntax was allready encountered
355  *          and if it corresponds to a ExplicitVRLittleEndian one.
356  *
357  * @return  True when ExplicitVRLittleEndian found. False in all other cases.
358  */
359 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
360         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
361         if ( !Element )
362                 return false;
363         LoadElementValueSafe(Element);
364         string Transfer = Element->GetValue();
365         if ( Transfer == "1.2.840.10008.1.2.1" )
366                 return true;
367         return false;
368 }
369
370 /**
371  * \ingroup gdcmHeader
372  * \brief   Determines if the Transfer Syntax was allready encountered
373  *          and if it corresponds to a DeflatedExplicitVRLittleEndian one.
374  *
375  * @return  True when DeflatedExplicitVRLittleEndian found. False in all other cases.
376  */
377 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
378         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
379         if ( !Element )
380                 return false;
381         LoadElementValueSafe(Element);
382         string Transfer = Element->GetValue();
383         if ( Transfer == "1.2.840.10008.1.2.1.99" )
384                 return true;
385         return false;
386 }
387
388
389 /**
390  * \ingroup gdcmHeader
391  * \brief   Determines if the Transfer Syntax was allready encountered
392  *          and if it corresponds to a Explicit VR Big Endian one.
393  *
394  * @return  True when big endian found. False in all other cases.
395  */
396 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
397         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
398         if ( !Element )
399                 return false;
400         LoadElementValueSafe(Element);
401         string Transfer = Element->GetValue();
402         if ( Transfer == "1.2.840.10008.1.2.2" )
403                 return true;
404         return false;
405 }
406
407
408 /**
409  * \ingroup gdcmHeader
410  * \brief   Determines if the Transfer Syntax was allready encountered
411  *          and if it corresponds to a JPEGBaseLineProcess1 one.
412  *
413  * @return  True when JPEGBaseLineProcess1found. False in all other cases.
414  */
415 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
416         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
417         if ( !Element )
418                 return false;
419         LoadElementValueSafe(Element);
420         string Transfer = Element->GetValue();
421         if ( Transfer == "1.2.840.10008.1.2.4.50" )
422                 return true;
423         return false;
424 }
425
426 /**
427  * \ingroup gdcmHeader
428  * \brief   Determines if the Transfer Syntax was allready encountered
429  *          and if it corresponds to a JPEGExtendedProcess2-4 one.
430  *
431  * @return  True when JPEGExtendedProcess2-4 found. False in all other cases.
432  */
433 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
434         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
435         if ( !Element )
436                 return false;
437         LoadElementValueSafe(Element);
438         string Transfer = Element->GetValue();
439         if ( Transfer == "1.2.840.10008.1.2.4.51" )
440                 return true;
441         return false;
442 }
443
444
445 /**
446  * \ingroup gdcmHeader
447  * \brief   Determines if the Transfer Syntax was allready encountered
448  *          and if it corresponds to a JPEGExtendeProcess3-5 one.
449  *
450  * @return  True when JPEGExtendedProcess3-5 found. False in all other cases.
451  */
452 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
453         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
454         if ( !Element )
455                 return false;
456         LoadElementValueSafe(Element);
457         string Transfer = Element->GetValue();
458         if ( Transfer == "1.2.840.10008.1.2.4.52" )
459                 return true;
460         return false;
461 }
462
463 /**
464  * \ingroup gdcmHeader
465  * \brief   Determines if the Transfer Syntax was allready encountered
466  *          and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
467  *
468  * @return  True when JPEGSpectralSelectionProcess6-8 found. False in all other cases.
469  */
470 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
471         ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
472         if ( !Element )
473                 return false;
474         LoadElementValueSafe(Element);
475         string Transfer = Element->GetValue();
476         if ( Transfer == "1.2.840.10008.1.2.4.53" )
477                 return true;
478         return false;
479 }
480
481 //
482 // Euhhhhhhh
483 // Il y en a encore DIX-SEPT, comme ça.
484 // Il faudrait trouver qq chose + rusé ...
485 //
486 // --> probablement TOUS les supprimer (Eric dixit)
487 //
488
489
490 void gdcmHeader::FixFoundLength(ElValue * ElVal, guint32 FoundLength) {
491         // Heuristic: a final fix.
492         if ( FoundLength == 0xffffffff)
493                 FoundLength = 0;
494         ElVal->SetLength(FoundLength);
495 }
496
497 guint32 gdcmHeader::FindLengthOB(void) {
498         // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
499         guint16 g;
500         guint16 n; 
501         long PositionOnEntry = ftell(fp);
502         bool FoundSequenceDelimiter = false;
503         guint32 TotalLength = 0;
504         guint32 ItemLength;
505
506         while ( ! FoundSequenceDelimiter) {
507                 g = ReadInt16();
508                 n = ReadInt16();
509                 if (errno == 1)
510                         return 0;
511                 TotalLength += 4;  // We even have to decount the group and element 
512                 if ( g != 0xfffe ) {
513                         dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
514                                     "wrong group for an item sequence.");
515                         errno = 1;
516                         return 0;
517                 }
518                 if ( n == 0xe0dd )
519                         FoundSequenceDelimiter = true;
520                 else if ( n != 0xe000) {
521                         dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
522                                     "wrong element for an item sequence.");
523                         errno = 1;
524                         return 0;
525                 }
526                 ItemLength = ReadInt32();
527                 TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
528                                                 // the ItemLength with ReadInt32
529                 SkipBytes(ItemLength);
530         }
531         fseek(fp, PositionOnEntry, SEEK_SET);
532         return TotalLength;
533 }
534
535 void gdcmHeader::FindLength(ElValue * ElVal) {
536         guint16 element = ElVal->GetElement();
537         string  vr      = ElVal->GetVR();
538         guint16 length16;
539         
540         if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
541
542                 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
543                         // The following reserved two bytes (see PS 3.5-2001, section
544                         // 7.1.2 Data element structure with explicit vr p27) must be
545                         // skipped before proceeding on reading the length on 4 bytes.
546                         fseek(fp, 2L, SEEK_CUR);
547                         guint32 length32 = ReadInt32();
548                         if ( (vr == "OB") && (length32 == 0xffffffff) ) {
549                                 ElVal->SetLength(FindLengthOB());
550                                 return;
551                         }
552                         FixFoundLength(ElVal, length32);
553                         return;
554                 }
555
556                 // Length is encoded on 2 bytes.
557                 length16 = ReadInt16();
558                 
559                 // We can tell the current file is encoded in big endian (like
560                 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
561                 // and it's value is the one of the encoding of a big endian file.
562                 // In order to deal with such big endian encoded files, we have
563                 // (at least) two strategies:
564                 // * when we load the "Transfer Syntax" tag with value of big endian
565                 //   encoding, we raise the proper flags. Then we wait for the end
566                 //   of the META group (0x0002) among which is "Transfer Syntax",
567                 //   before switching the swap code to big endian. We have to postpone
568                 //   the switching of the swap code since the META group is fully encoded
569                 //   in little endian, and big endian coding only starts at the next
570                 //   group. The corresponding code can be hard to analyse and adds
571                 //   many additional unnecessary tests for regular tags.
572                 // * the second strategy consists in waiting for trouble, that shall appear
573                 //   when we find the first group with big endian encoding. This is
574                 //   easy to detect since the length of a "Group Length" tag (the
575                 //   ones with zero as element number) has to be of 4 (0x0004). When we
576                 //   encouter 1024 (0x0400) chances are the encoding changed and we
577                 //   found a group with big endian encoding.
578                 // We shall use this second strategy. In order make sure that we
579                 // can interpret the presence of an apparently big endian encoded
580                 // length of a "Group Length" without committing a big mistake, we
581                 // add an additional check: we look in the allready parsed elements
582                 // for the presence of a "Transfer Syntax" whose value has to be "big
583                 // endian encoding". When this is the case, chances are we got our
584                 // hands on a big endian encoded file: we switch the swap code to
585                 // big endian and proceed...
586                 if ( (element  == 0x000) && (length16 == 0x0400) ) {
587                         if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
588                                 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
589                                 errno = 1;
590                                 return;
591                         }
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 = GetDictEntryByKey(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 content if it's length is not bigger
691  *                than the value specified with
692  *                gdcmHeader::SetMaxSizeLoadElementValue()
693  */
694 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
695         size_t item_read;
696         guint16 group  = ElVal->GetGroup();
697         guint16 elem   = ElVal->GetElement();
698         string  vr     = ElVal->GetVR();
699         guint32 length = ElVal->GetLength();
700         bool SkipLoad  = false;
701
702         fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
703         
704         // Sequences not treated yet !
705         //
706         // Ne faudrait-il pas au contraire trouver immediatement
707         // une maniere 'propre' de traiter les sequences (vr = SQ)
708         // car commencer par les ignorer risque de conduire a qq chose
709         // qui pourrait ne pas etre generalisable
710         //
711         if( vr == "SQ" )
712                 SkipLoad = true;
713
714         // Heuristic : a sequence "contains" a set of tags (called items). It looks
715         // like the last tag of a sequence (the one that terminates the sequence)
716         // has a group of 0xfffe (with a dummy length).
717         if( group == 0xfffe )
718                 SkipLoad = true;
719
720         // The group length doesn't represent data to be loaded in memory, since
721         // each element of the group shall be loaded individualy.
722         if( elem == 0 )
723                 //SkipLoad = true;              // modif sauvage JPR
724                                                                 // On charge la longueur du groupe
725                                                                 // quand l'element 0x0000 est présent !
726
727         if ( SkipLoad ) {
728                           // FIXME the following skip is not necessary
729                 SkipElementValue(ElVal);
730                 ElVal->SetLength(0);
731                 ElVal->SetValue("gdcm::Skipped");
732                 return;
733         }
734
735         // When the length is zero things are easy:
736         if ( length == 0 ) {
737                 ElVal->SetValue("");
738                 return;
739         }
740
741         // The elements whose length is bigger than the specified upper bound
742         // are not loaded. Instead we leave a short notice of the offset of
743         // the element content and it's length.
744         if (length > MaxSizeLoadElementValue) {
745                 ostringstream s;
746                 s << "gdcm::NotLoaded.";
747                 s << " Address:" << (long)ElVal->GetOffset();
748                 s << " Length:"  << ElVal->GetLength();
749                 ElVal->SetValue(s.str());
750                 return;
751         }
752         
753         // When an integer is expected, read and convert the following two or
754         // four bytes properly i.e. as an integer as opposed to a string.
755         if ( IsAnInteger(ElVal) ) {
756                 guint32 NewInt;
757                 if( length == 2 ) {
758                         NewInt = ReadInt16();
759                 } else if( length == 4 ) {
760                         NewInt = ReadInt32();
761                 } else
762                         dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
763                 
764                 //FIXME: make the following an util fonction
765                 ostringstream s;
766                 s << NewInt;
767                 ElVal->SetValue(s.str());
768                 return;
769         }
770         
771         // FIXME The exact size should be length if we move to strings or whatever
772         char* NewValue = (char*)malloc(length+1);
773         if( !NewValue) {
774                 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
775                 return;
776         }
777         NewValue[length]= 0;
778         
779         item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
780         if ( item_read != 1 ) {
781                 free(NewValue);
782                 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
783                 ElVal->SetValue("gdcm::UnRead");
784                 return;
785         }
786         ElVal->SetValue(NewValue);
787 }
788
789 /**
790  * \ingroup       gdcmHeader
791  * \brief         Loads the element while preserving the current
792  *                underlying file position indicator as opposed to
793  *                to LoadElementValue that modifies it.
794  * @param ElVal   Element whose value shall be loaded. 
795  * @return  
796  */
797 void gdcmHeader::LoadElementValueSafe(ElValue * ElVal) {
798         long PositionOnEntry = ftell(fp);
799         LoadElementValue(ElVal);
800         fseek(fp, PositionOnEntry, SEEK_SET);
801 }
802
803
804 guint16 gdcmHeader::ReadInt16(void) {
805         guint16 g;
806         size_t item_read;
807         item_read = fread (&g, (size_t)2,(size_t)1, fp);
808         errno = 0;
809         if ( item_read != 1 ) {
810                 dbg.Verbose(1, "gdcmHeader::ReadInt16", " File read error");
811                 errno = 1;
812                 return 0;
813         }
814         g = SwapShort(g);
815         return g;
816 }
817
818 guint32 gdcmHeader::ReadInt32(void) {
819         guint32 g;
820         size_t item_read;
821         item_read = fread (&g, (size_t)4,(size_t)1, fp);
822         errno = 0;
823         if ( item_read != 1 ) {
824                 dbg.Verbose(1, "gdcmHeader::ReadInt32", " File read error");
825                 errno = 1;
826                 return 0;
827         }
828         g = SwapLong(g);
829         return g;
830 }
831
832 /**
833  * \ingroup gdcmHeader
834  * \brief   Build a new Element Value from all the low level arguments. 
835  *          Check for existence of dictionary entry, and build
836  *          a default one when absent.
837  * @param   Group group   of the underlying DictEntry
838  * @param   Elem  element of the underlying DictEntry
839  */
840 ElValue* gdcmHeader::NewElValueByKey(guint16 Group, guint16 Elem) {
841         // Find out if the tag we encountered is in the dictionaries:
842         gdcmDictEntry * NewTag = GetDictEntryByKey(Group, Elem);
843         if (!NewTag)
844                 NewTag = new gdcmDictEntry(Group, Elem);
845
846         ElValue* NewElVal = new ElValue(NewTag);
847         if (!NewElVal) {
848                 dbg.Verbose(1, "gdcmHeader::NewElValueByKey",
849                             "failed to allocate ElValue");
850                 return (ElValue*)0;
851         }
852    return NewElVal;
853 }
854
855 /**
856  * \ingroup gdcmHeader
857  * \brief   Build a new Element Value from all the low level arguments. 
858  *          Check for existence of dictionary entry, and build
859  *          a default one when absent.
860  * @param   Name    Name of the underlying DictEntry
861  */
862 ElValue* gdcmHeader::NewElValueByName(string Name) {
863
864    gdcmDictEntry * NewTag = GetDictEntryByName(Name);
865    if (!NewTag)
866       NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
867
868    ElValue* NewElVal = new ElValue(NewTag);
869    if (!NewElVal) {
870       dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
871                   "failed to allocate ElValue");
872       return (ElValue*)0;
873    }
874    return NewElVal;
875 }  
876
877
878 /**
879  * \ingroup gdcmHeader
880  * \brief   Read the next tag without loading it's value
881  * @return  On succes the newly created ElValue, NULL on failure.      
882  */
883
884 ElValue * gdcmHeader::ReadNextElement(void) {
885         guint16 g;
886         guint16 n;
887         ElValue * NewElVal;
888         
889         g = ReadInt16();
890         n = ReadInt16();
891         if (errno == 1)
892                 // We reached the EOF (or an error occured) and header parsing
893                 // has to be considered as finished.
894                 return (ElValue *)0;
895         
896         NewElVal = NewElValueByKey(g, n);
897         FindVR(NewElVal);
898         FindLength(NewElVal);
899         if (errno == 1)
900                 // Call it quits
901                 return (ElValue *)0;
902         NewElVal->SetOffset(ftell(fp));
903         return NewElVal;
904 }
905
906 bool gdcmHeader::IsAnInteger(ElValue * ElVal) {
907         guint16 group   = ElVal->GetGroup();
908         guint16 element = ElVal->GetElement();
909         string  vr      = ElVal->GetVR();
910         guint32 length  = ElVal->GetLength();
911
912         // When we have some semantics on the element we just read, and if we
913         // a priori know we are dealing with an integer, then we shall be
914         // able to swap it's element value properly.
915         if ( element == 0 )  {  // This is the group length of the group
916                 if (length == 4)
917                         return true;
918                 else
919                         dbg.Error("gdcmHeader::IsAnInteger",
920                                   "Erroneous Group Length element length.");
921         }
922         
923         if ( group % 2 != 0 )
924                 // We only have some semantics on documented elements, which are
925                 // the even ones.
926                 return false;
927         
928         if ( (length != 4) && ( length != 2) )
929                 // Swapping only make sense on integers which are 2 or 4 bytes long.
930                 return false;
931         
932         if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
933                 return true;
934         
935         if ( (group == 0x0028) && (element == 0x0005) )
936                 // The "Image Dimensions" tag is retained from ACR/NEMA and contains
937                 // the number of dimensions of the contained object (1 for Signal,
938                 // 2 for Image, 3 for Volume, 4 for Sequence).
939                 return true;
940         
941         if ( (group == 0x0028) && (element == 0x0200) )
942                 // This tag is retained from ACR/NEMA
943                 return true;
944         
945         return false;
946 }
947
948 /**
949  * \ingroup gdcmHeader
950  * \brief   Recover the offset (from the beginning of the file) of the pixels.
951  */
952 size_t gdcmHeader::GetPixelOffset(void) {
953         // If this file complies with the norm we should encounter the
954         // "Image Location" tag (0x0028,  0x0200). This tag contains the
955         // the group that contains the pixel data (hence the "Pixel Data"
956         // is found by indirection through the "Image Location").
957         // Inside the group pointed by "Image Location" the searched element
958         // is conventionally the element 0x0010 (when the norm is respected).
959         //    When the "Image Location" is absent we default to group 0x7fe0.
960         guint16 grPixel;
961         guint16 numPixel;
962         string ImageLocation = GetPubElValByName("Image Location");
963         if ( ImageLocation == "gdcm::Unfound" ) {
964                 grPixel = 0x7fe0;
965         } else {
966                 grPixel = (guint16) atoi( ImageLocation.c_str() );
967         }
968         if (grPixel != 0x7fe0)
969                 // FIXME is this still necessary ?
970                 // Now, this looks like an old dirty fix for Philips imager
971                 numPixel = 0x1010;
972         else
973                 numPixel = 0x0010;
974         ElValue* PixelElement = PubElVals.GetElementByNumber(grPixel, numPixel);
975         if (PixelElement)
976                 return PixelElement->GetOffset();
977         else
978                 return 0;
979 }
980
981 /**
982  * \ingroup gdcmHeader
983  * \brief   Searches both the public and the shadow dictionary (when they
984  *          exist) for the presence of the DictEntry with given
985  *          group and element. The public dictionary has precedence on the
986  *          shadow one.
987  * @param   group   group of the searched DictEntry
988  * @param   element element of the searched DictEntry
989  * @return  Corresponding DictEntry when it exists, NULL otherwise.
990  */
991 gdcmDictEntry * gdcmHeader::GetDictEntryByKey(guint16 group, guint16 element) {
992         gdcmDictEntry * found = (gdcmDictEntry*)0;
993         if (!RefPubDict && !RefShaDict) {
994                 dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
995                      "we SHOULD have a default dictionary");
996         }
997         if (RefPubDict) {
998                 found = RefPubDict->GetTagByKey(group, element);
999                 if (found)
1000                         return found;
1001         }
1002         if (RefShaDict) {
1003                 found = RefShaDict->GetTagByKey(group, element);
1004                 if (found)
1005                         return found;
1006         }
1007         return found;
1008 }
1009
1010 /**
1011  * \ingroup gdcmHeader
1012  * \brief   Searches both the public and the shadow dictionary (when they
1013  *          exist) for the presence of the DictEntry with given name.
1014  *          The public dictionary has precedence on the shadow one.
1015  * @earam   Name name of the searched DictEntry
1016  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1017  */
1018 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1019         gdcmDictEntry * found = (gdcmDictEntry*)0;
1020         if (!RefPubDict && !RefShaDict) {
1021                 dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
1022                      "we SHOULD have a default dictionary");
1023         }
1024         if (RefPubDict) {
1025                 found = RefPubDict->GetTagByName(Name);
1026                 if (found)
1027                         return found;
1028         }
1029         if (RefShaDict) {
1030                 found = RefShaDict->GetTagByName(Name);
1031                 if (found)
1032                         return found;
1033         }
1034         return found;
1035 }
1036
1037 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1038         return PubElVals.GetElValueByNumber(group, element);
1039 }
1040
1041 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1042         ElValue* elem =  PubElVals.GetElementByNumber(group, element);
1043         if ( !elem )
1044                 return "gdcm::Unfound";
1045         return elem->GetVR();
1046 }
1047
1048 string gdcmHeader::GetPubElValByName(string TagName) {
1049         return PubElVals.GetElValueByName(TagName);
1050 }
1051
1052 string gdcmHeader::GetPubElValRepByName(string TagName) {
1053         ElValue* elem =  PubElVals.GetElementByName(TagName);
1054         if ( !elem )
1055                 return "gdcm::Unfound";
1056         return elem->GetVR();
1057 }
1058
1059 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1060         return ShaElVals.GetElValueByNumber(group, element);
1061 }
1062
1063 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1064         ElValue* elem =  ShaElVals.GetElementByNumber(group, element);
1065         if ( !elem )
1066                 return "gdcm::Unfound";
1067         return elem->GetVR();
1068 }
1069
1070 string gdcmHeader::GetShaElValByName(string TagName) {
1071         return ShaElVals.GetElValueByName(TagName);
1072 }
1073
1074 string gdcmHeader::GetShaElValRepByName(string TagName) {
1075         ElValue* elem =  ShaElVals.GetElementByName(TagName);
1076         if ( !elem )
1077                 return "gdcm::Unfound";
1078         return elem->GetVR();
1079 }
1080
1081 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1082         string pub = GetPubElValByNumber(group, element);
1083         if (pub.length())
1084                 return pub;
1085         return GetShaElValByNumber(group, element);
1086 }
1087
1088 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1089         string pub = GetPubElValRepByNumber(group, element);
1090         if (pub.length())
1091                 return pub;
1092         return GetShaElValRepByNumber(group, element);
1093 }
1094
1095 string gdcmHeader::GetElValByName(string TagName) {
1096         string pub = GetPubElValByName(TagName);
1097         if (pub.length())
1098                 return pub;
1099         return GetShaElValByName(TagName);
1100 }
1101
1102 string gdcmHeader::GetElValRepByName(string TagName) {
1103         string pub = GetPubElValRepByName(TagName);
1104         if (pub.length())
1105                 return pub;
1106         return GetShaElValRepByName(TagName);
1107 }
1108
1109 /**
1110  * \ingroup gdcmHeader
1111  * \brief   Accesses an existing ElValue in the PubElVals of this instance
1112  *          through it's (group, element) and modifies it's content with
1113  *          the given value.
1114  * @param   content new value to substitute with
1115  * @param   group   group of the ElVal to modify
1116  * @param   element element of the ElVal to modify
1117  */
1118 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1119                                     guint16 element)
1120 {
1121         //CLEANME TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1122         //CLEANME PubElVals.tagHt[key]->SetValue(content);
1123         return (  PubElVals.SetElValueByNumber (content, group, element) );
1124 }
1125
1126 /**
1127  * \ingroup gdcmHeader
1128  * \brief   Accesses an existing ElValue in the PubElVals of this instance
1129  *          through tag name and modifies it's content with the given value.
1130  * @param   content new value to substitute with
1131  * @param   TagName name of the tag to be modified
1132  */
1133 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1134         //CLEANME TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1135         //CLEANME PubElVals.tagHt[key]->SetValue(content);
1136         return (  PubElVals.SetElValueByName (content, TagName) );
1137 }
1138
1139 /**
1140  * \ingroup gdcmHeader
1141  * \brief   Accesses an existing ElValue in the ShaElVals of this instance
1142  *          through it's (group, element) and modifies it's content with
1143  *          the given value.
1144  * @param   content new value to substitute with
1145  * @param   group   group of the ElVal to modify
1146  * @param   element element of the ElVal to modify
1147  */
1148 int gdcmHeader::SetShaElValByNumber(string content,
1149                                     guint16 group, guint16 element)
1150 {
1151         return (  ShaElVals.SetElValueByNumber (content, group, element) );
1152 }
1153
1154 /**
1155  * \ingroup gdcmHeader
1156  * \brief   Accesses an existing ElValue in the ShaElVals of this instance
1157  *          through tag name and modifies it's content with the given value.
1158  * @param   content new value to substitute with
1159  * @param   TagName name of the tag to be modified
1160  */
1161 int gdcmHeader::SetShaElValByName(string content, string TagName) {
1162         return (  ShaElVals.SetElValueByName (content, TagName) );
1163 }
1164
1165 /**
1166  * \ingroup gdcmHeader
1167  * \brief   Parses the header of the file but WITHOUT loading element values.
1168  */
1169 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1170         ElValue * newElValue = (ElValue *)0;
1171         
1172         rewind(fp);
1173         CheckSwap();
1174         while ( (newElValue = ReadNextElement()) ) {
1175                 SkipElementValue(newElValue);
1176                 PubElVals.Add(newElValue);
1177         }
1178 }
1179
1180 /**
1181  * \ingroup gdcmHeader
1182  * \brief   Once the header is parsed add some gdcm convenience/helper elements
1183  *          in the ElValSet. For example add:
1184  *          - gdcmImageType which is an entry containing a short for the
1185  *            type of image and whose value ranges in 
1186  *               I8   (unsigned 8 bit image)
1187  *               I16  (unsigned 8 bit image)
1188  *               IS16 (signed 8 bit image)
1189  *          - gdcmXsize, gdcmYsize, gdcmZsize whose values are respectively
1190  *            the ones of the official DICOM fields Rows, Columns and Planes.
1191  */
1192 void gdcmHeader::AddAndDefaultElements(void) {
1193         ElValue* NewEntry = (ElValue*)0;
1194
1195         NewEntry = NewElValueByName("gdcmXSize");
1196         NewEntry->SetValue(GetElValByName("Rows"));
1197         PubElVals.Add(NewEntry);
1198
1199         NewEntry = NewElValueByName("gdcmYSize");
1200         NewEntry->SetValue(GetElValByName("Columns"));
1201         PubElVals.Add(NewEntry);
1202
1203         NewEntry = NewElValueByName("gdcmZSize");
1204         NewEntry->SetValue(GetElValByName("Planes"));
1205         PubElVals.Add(NewEntry);
1206 }
1207
1208 /**
1209  * \ingroup gdcmHeader
1210  * \brief   Loads the element values of all the elements present in the
1211  *          public tag based hash table.
1212  */
1213 void gdcmHeader::LoadElements(void) {
1214         rewind(fp);   
1215         TagElValueHT ht = PubElVals.GetTagHt();
1216         for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1217                 LoadElementValue(tag->second);
1218                 }
1219 }
1220
1221 void gdcmHeader::PrintPubElVal(ostream & os) {
1222         PubElVals.Print(os);
1223 }
1224
1225 void gdcmHeader::PrintPubDict(ostream & os) {
1226         RefPubDict->Print(os);
1227 }