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