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