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