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