]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
*FIX: Use carnaught table to reduce boolean expr !
[gdcm.git] / src / gdcmHeader.cxx
1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.120 2003/11/18 09:23:16 malaterre Exp $
2
3 #include "gdcmHeader.h"
4
5 #include <stdio.h>
6 #include <cerrno>
7 // For nthos:
8 #ifdef _MSC_VER
9 #include <winsock.h>
10 #else
11 #include <netinet/in.h>
12 #endif
13 #include <cctype>    // for isalpha
14
15 #ifdef GDCM_NO_ANSI_STRING_STREAM
16 #  include <strstream>
17 #  define  ostringstream ostrstream
18 # else
19 #  include <sstream>
20 #endif
21
22 #include "gdcmUtil.h"
23 #include "gdcmTS.h"
24
25 // Refer to gdcmHeader::CheckSwap()
26 #define HEADER_LENGTH_TO_READ       256
27 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
28 //#define _MaxSizeLoadElementValue_   1024
29 #define _MaxSizeLoadElementValue_   4096
30 /**
31  * \ingroup gdcmHeader
32  * \brief   
33  */
34 void gdcmHeader::Initialise(void) {
35    dicom_vr = gdcmGlobal::GetVR();
36    dicom_ts = gdcmGlobal::GetTS();
37    Dicts    = gdcmGlobal::GetDicts();
38    RefPubDict = Dicts->GetDefaultPubDict();
39    RefShaDict = (gdcmDict*)0;
40 }
41
42 /**
43  * \ingroup gdcmHeader
44  * \brief   
45  * @param   InFilename
46  * @param   exception_on_error
47  */
48 gdcmHeader::gdcmHeader(const char *InFilename, 
49                        bool exception_on_error,
50                        bool  enable_sequences ) {
51    if (enable_sequences)
52       enableSequences = 1;
53    else
54       enableSequences = 0;
55    
56    SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
57    filename = InFilename;
58    Initialise();
59    if ( !OpenFile(exception_on_error))
60       return;
61    ParseHeader();
62    LoadElements();
63    CloseFile();
64 }
65
66 /**
67  * \ingroup gdcmHeader
68  * \brief   
69  * @param   exception_on_error
70  */
71 gdcmHeader::gdcmHeader(bool exception_on_error) {
72   SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
73   Initialise();
74 }
75
76 /**
77  * \ingroup gdcmHeader
78  * \brief   
79  * @param   exception_on_error
80  * @return  
81  */
82  bool gdcmHeader::OpenFile(bool exception_on_error)
83   throw(gdcmFileError) {
84   fp=fopen(filename.c_str(),"rb");
85   if(exception_on_error) {
86     if(!fp)
87       throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
88   }
89
90   if ( fp ) {
91      guint16 zero;
92      fread(&zero,  (size_t)2, (size_t)1, fp);
93
94     //ACR -- or DICOM with no Preamble
95     if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
96        return true;
97     //DICOM
98     fseek(fp, 126L, SEEK_CUR);
99     char dicm[4];
100     fread(dicm,  (size_t)4, (size_t)1, fp);
101     if( memcmp(dicm, "DICM", 4) == 0 )
102        return true;
103     fclose(fp);
104     dbg.Verbose(0, "gdcmHeader::gdcmHeader not DICOM/ACR", filename.c_str());
105   }
106   else {
107     dbg.Verbose(0, "gdcmHeader::gdcmHeader cannot open file", filename.c_str());
108   }
109   return false;
110 }
111
112 /**
113  * \ingroup gdcmHeader
114  * \brief   
115  * @return  TRUE if the close was successfull 
116  */
117 bool gdcmHeader::CloseFile(void) {
118   int closed = fclose(fp);
119   fp = (FILE *)0;
120   if (! closed)
121      return false;
122   return true;
123 }
124
125 /**
126  * \ingroup gdcmHeader
127  * \brief   Canonical destructor.
128  */
129 gdcmHeader::~gdcmHeader (void) {
130   dicom_vr =   (gdcmVR*)0; 
131   Dicts    =   (gdcmDictSet*)0;
132   RefPubDict = (gdcmDict*)0;
133   RefShaDict = (gdcmDict*)0;
134   return;
135 }
136
137 // Fourth semantics:
138 //
139 // ---> Warning : This fourth field is NOT part 
140 //                of the 'official' Dicom Dictionnary
141 //                and should NOT be used.
142 //                (Not defined for all the groups
143 //                 may be removed in a future release)
144 //
145 // CMD      Command        
146 // META     Meta Information 
147 // DIR      Directory
148 // ID
149 // PAT      Patient
150 // ACQ      Acquisition
151 // REL      Related
152 // IMG      Image
153 // SDY      Study
154 // VIS      Visit 
155 // WAV      Waveform
156 // PRC
157 // DEV      Device
158 // NMI      Nuclear Medicine
159 // MED
160 // BFS      Basic Film Session
161 // BFB      Basic Film Box
162 // BIB      Basic Image Box
163 // BAB
164 // IOB
165 // PJ
166 // PRINTER
167 // RT       Radio Therapy
168 // DVH   
169 // SSET
170 // RES      Results
171 // CRV      Curve
172 // OLY      Overlays
173 // PXL      Pixels
174 // DL       Delimiters
175 //
176
177 /**
178  * \ingroup gdcmHeader
179  * \brief   Discover what the swap code is (among little endian, big endian,
180  *          bad little endian, bad big endian).
181  *
182  */
183 void gdcmHeader::CheckSwap()
184 {
185    // The only guaranted way of finding the swap code is to find a
186    // group tag since we know it's length has to be of four bytes i.e.
187    // 0x00000004. Finding the swap code in then straigthforward. Trouble
188    // occurs when we can't find such group...
189    guint32  s;
190    guint32  x=4;  // x : for ntohs
191    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
192     
193    int lgrLue;
194    char * entCur;
195    char deb[HEADER_LENGTH_TO_READ];
196     
197    // First, compare HostByteOrder and NetworkByteOrder in order to
198    // determine if we shall need to swap bytes (i.e. the Endian type).
199    if (x==ntohs(x))
200       net2host = true;
201    else
202       net2host = false;
203    
204    // The easiest case is the one of a DICOM header, since it possesses a
205    // file preamble where it suffice to look for the string "DICM".
206    lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
207    
208    entCur = deb + 128;
209    if(memcmp(entCur, "DICM", (size_t)4) == 0) {
210       dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
211       // Next, determine the value representation (VR). Let's skip to the
212       // first element (0002, 0000) and check there if we find "UL" 
213       // - or "OB" if the 1st one is (0002,0001) -,
214       // in which case we (almost) know it is explicit VR.
215       // WARNING: if it happens to be implicit VR then what we will read
216       // is the length of the group. If this ascii representation of this
217       // length happens to be "UL" then we shall believe it is explicit VR.
218       // FIXME: in order to fix the above warning, we could read the next
219       // element value (or a couple of elements values) in order to make
220       // sure we are not commiting a big mistake.
221       // We need to skip :
222       // * the 128 bytes of File Preamble (often padded with zeroes),
223       // * the 4 bytes of "DICM" string,
224       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
225       // i.e. a total of  136 bytes.
226       entCur = deb + 136;
227       // FIXME
228       // Use gdcmHeader::dicom_vr to test all the possibilities
229       // instead of just checking for UL, OB and UI !?
230       if(  (memcmp(entCur, "UL", (size_t)2) == 0) ||
231            (memcmp(entCur, "OB", (size_t)2) == 0) ||
232            (memcmp(entCur, "UI", (size_t)2) == 0) )   
233       {
234          filetype = ExplicitVR;
235          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
236                      "explicit Value Representation");
237       } else {
238          filetype = ImplicitVR;
239          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
240                      "not an explicit Value Representation");
241       }
242       if (net2host) {
243          sw = 4321;
244          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
245                         "HostByteOrder != NetworkByteOrder");
246       } else {
247          sw = 0;
248          dbg.Verbose(1, "gdcmHeader::CheckSwap:",
249                         "HostByteOrder = NetworkByteOrder");
250       }
251       
252       // Position the file position indicator at first tag (i.e.
253       // after the file preamble and the "DICM" string).
254       rewind(fp);
255       fseek (fp, 132L, SEEK_SET);
256       return;
257    } // End of DicomV3
258
259    // Alas, this is not a DicomV3 file and whatever happens there is no file
260    // preamble. We can reset the file position indicator to where the data
261    // is (i.e. the beginning of the file).
262     dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
263    rewind(fp);
264
265    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
266    // By clean we mean that the length of the first tag is written down.
267    // If this is the case and since the length of the first group HAS to be
268    // four (bytes), then determining the proper swap code is straightforward.
269
270    entCur = deb + 4;
271    // We assume the array of char we are considering contains the binary
272    // representation of a 32 bits integer. Hence the following dirty
273    // trick :
274    s = *((guint32 *)(entCur));
275    
276    switch (s) {
277    case 0x00040000 :
278       sw = 3412;
279       filetype = ACR;
280       return;
281    case 0x04000000 :
282       sw = 4321;
283       filetype = ACR;
284       return;
285    case 0x00000400 :
286       sw = 2143;
287       filetype = ACR;
288       return;
289    case 0x00000004 :
290       sw = 0;
291       filetype = ACR;
292       return;
293    default :
294       dbg.Verbose(0, "gdcmHeader::CheckSwap:",
295                      "ACR/NEMA unfound swap info (time to raise bets)");
296    }
297
298    // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
299    // It is time for despaired wild guesses. So, let's assume this file
300    // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
301    // not present. Then the only info we have is the net2host one.
302    filetype = Unknown;
303    if (! net2host )
304       sw = 0;
305    else
306       sw = 4321;
307    return;
308 }
309
310 /**
311  * \ingroup gdcmHeader
312  * \brief   
313  */
314 void gdcmHeader::SwitchSwapToBigEndian(void) {
315    dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
316                   "Switching to BigEndian mode.");
317    if ( sw == 0    ) {
318       sw = 4321;
319       return;
320    }
321    if ( sw == 4321 ) {
322       sw = 0;
323       return;
324    }
325    if ( sw == 3412 ) {
326       sw = 2143;
327       return;
328    }
329    if ( sw == 2143 )
330       sw = 3412;
331 }
332
333 /**
334  * \ingroup   gdcmHeader
335  * \brief     Find the value representation of the current tag.
336  * @param ElVal
337  */
338 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
339    if (filetype != ExplicitVR)
340       return;
341
342    char VR[3];
343    std::string vr;
344    int lgrLue;
345    char msg[100]; // for sprintf. Sorry
346
347    long PositionOnEntry = ftell(fp);
348    // Warning: we believe this is explicit VR (Value Representation) because
349    // we used a heuristic that found "UL" in the first tag. Alas this
350    // doesn't guarantee that all the tags will be in explicit VR. In some
351    // cases (see e-film filtered files) one finds implicit VR tags mixed
352    // within an explicit VR file. Hence we make sure the present tag
353    // is in explicit VR and try to fix things if it happens not to be
354    // the case.
355    bool RealExplicit = true;
356    
357    lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
358    VR[2]=0;
359    vr = std::string(VR);
360       
361    // Assume we are reading a falsely explicit VR file i.e. we reached
362    // a tag where we expect reading a VR but are in fact we read the
363    // first to bytes of the length. Then we will interogate (through find)
364    // the dicom_vr dictionary with oddities like "\004\0" which crashes
365    // both GCC and VC++ implementations of the STL map. Hence when the
366    // expected VR read happens to be non-ascii characters we consider
367    // we hit falsely explicit VR tag.
368
369    if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
370       RealExplicit = false;
371
372    // CLEANME searching the dicom_vr at each occurence is expensive.
373    // PostPone this test in an optional integrity check at the end
374    // of parsing or only in debug mode.
375    if ( RealExplicit && !dicom_vr->Count(vr) )
376       RealExplicit= false;
377
378    if ( RealExplicit ) {
379       if ( ElVal->IsVrUnknown() ) {
380          // When not a dictionary entry, we can safely overwrite the vr.
381          ElVal->SetVR(vr);
382          return; 
383       }
384       if ( ElVal->GetVR() == vr ) {
385          // The vr we just read and the dictionary agree. Nothing to do.
386          return;
387       }
388       // The vr present in the file and the dictionary disagree. We assume
389       // the file writer knew best and use the vr of the file. Since it would
390       // be unwise to overwrite the vr of a dictionary (since it would
391       // compromise it's next user), we need to clone the actual DictEntry
392       // and change the vr for the read one.
393       gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
394                                  ElVal->GetElement(),
395                                  vr,
396                                  "FIXME",
397                                  ElVal->GetName());
398       ElVal->SetDictEntry(NewTag);
399       return; 
400    }
401    
402    // We thought this was explicit VR, but we end up with an
403    // implicit VR tag. Let's backtrack.   
404    
405       sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", 
406                    ElVal->GetGroup(),ElVal->GetElement());
407       dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
408    
409    fseek(fp, PositionOnEntry, SEEK_SET);
410    // When this element is known in the dictionary we shall use, e.g. for
411    // the semantics (see the usage of IsAnInteger), the vr proposed by the
412    // dictionary entry. Still we have to flag the element as implicit since
413    // we know now our assumption on expliciteness is not furfilled.
414    // avoid  .
415    if ( ElVal->IsVrUnknown() )
416       ElVal->SetVR("Implicit");
417    ElVal->SetImplicitVr();
418 }
419
420 /**
421  * \ingroup gdcmHeader
422  * \brief   Determines if the Transfer Syntax was already encountered
423  *          and if it corresponds to a ImplicitVRLittleEndian one.
424  *
425  * @return  True when ImplicitVRLittleEndian found. False in all other cases.
426  */
427 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
428    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
429    if ( !Element )
430       return false;
431    LoadElementValueSafe(Element);
432    std::string Transfer = Element->GetValue();
433    if ( Transfer == "1.2.840.10008.1.2" )
434       return true;
435    return false;
436 }
437
438 /**
439  * \ingroup gdcmHeader
440  * \brief   Determines if the Transfer Syntax was already encountered
441  *          and if it corresponds to a ExplicitVRLittleEndian one.
442  *
443  * @return  True when ExplicitVRLittleEndian found. False in all other cases.
444  */
445 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
446    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
447    if ( !Element )
448       return false;
449    LoadElementValueSafe(Element);
450    std::string Transfer = Element->GetValue();
451    if ( Transfer == "1.2.840.10008.1.2.1" )
452       return true;
453    return false;
454 }
455
456 /**
457  * \ingroup gdcmHeader
458  * \brief   Determines if the Transfer Syntax was already encountered
459  *          and if it corresponds to a DeflatedExplicitVRLittleEndian one.
460  *
461  * @return  True when DeflatedExplicitVRLittleEndian found. False in all other cases.
462  */
463 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
464    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
465    if ( !Element )
466       return false;
467    LoadElementValueSafe(Element);
468    std::string Transfer = Element->GetValue();
469    if ( Transfer == "1.2.840.10008.1.2.1.99" )
470       return true;
471    return false;
472 }
473
474 /**
475  * \ingroup gdcmHeader
476  * \brief   Determines if the Transfer Syntax was already encountered
477  *          and if it corresponds to a Explicit VR Big Endian one.
478  *
479  * @return  True when big endian found. False in all other cases.
480  */
481 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
482    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
483    if ( !Element )
484       return false;
485    LoadElementValueSafe(Element);
486    std::string Transfer = Element->GetValue();
487    if ( Transfer == "1.2.840.10008.1.2.2" )  //1.2.2 ??? A verifier !
488       return true;
489    return false;
490 }
491
492 /**
493  * \ingroup gdcmHeader
494  * \brief   Determines if the Transfer Syntax was already encountered
495  *          and if it corresponds to a JPEGBaseLineProcess1 one.
496  *
497  * @return  True when JPEGBaseLineProcess1found. False in all other cases.
498  */
499 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
500    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
501    if ( !Element )
502       return false;
503    LoadElementValueSafe(Element);
504    std::string Transfer = Element->GetValue();
505    if ( Transfer == "1.2.840.10008.1.2.4.50" )
506       return true;
507    return false;
508 }
509
510 /**
511  * \ingroup gdcmHeader
512  * \brief   
513  *
514  * @return 
515  */
516 bool gdcmHeader::IsJPEGLossless(void) {
517    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
518     // faire qq chose d'intelligent a la place de Ã§a
519    if ( !Element )
520       return false;
521    LoadElementValueSafe(Element);
522    const char * Transfert = Element->GetValue().c_str();
523    if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
524    if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
525    if (Element->GetValue() == "1.2.840.10008.1.2.4.57")   return true;
526
527    return false;
528 }
529
530
531 /**
532  * \ingroup gdcmHeader
533  * \brief   Determines if the Transfer Syntax was already encountered
534  *          and if it corresponds to a JPEGExtendedProcess2-4 one.
535  *
536  * @return  True when JPEGExtendedProcess2-4 found. False in all other cases.
537  */
538 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
539    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
540    if ( !Element )
541       return false;
542    LoadElementValueSafe(Element);
543    std::string Transfer = Element->GetValue();
544    if ( Transfer == "1.2.840.10008.1.2.4.51" )
545       return true;
546    return false;
547 }
548
549 /**
550  * \ingroup gdcmHeader
551  * \brief   Determines if the Transfer Syntax was already encountered
552  *          and if it corresponds to a JPEGExtendeProcess3-5 one.
553  *
554  * @return  True when JPEGExtendedProcess3-5 found. False in all other cases.
555  */
556 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
557    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
558    if ( !Element )
559       return false;
560    LoadElementValueSafe(Element);
561    std::string Transfer = Element->GetValue();
562    if ( Transfer == "1.2.840.10008.1.2.4.52" )
563       return true;
564    return false;
565 }
566
567 /**
568  * \ingroup gdcmHeader
569  * \brief   Determines if the Transfer Syntax was already encountered
570  *          and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
571  *
572  * @return  True when JPEGSpectralSelectionProcess6-8 found. False in all
573  *          other cases.
574  */
575 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
576    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
577    if ( !Element )
578       return false;
579    LoadElementValueSafe(Element);
580    std::string Transfer = Element->GetValue();
581    if ( Transfer == "1.2.840.10008.1.2.4.53" )
582       return true;
583    return false;
584 }
585
586 /**
587  * \ingroup gdcmHeader
588  * \brief   Determines if the Transfer Syntax was already encountered
589  *          and if it corresponds to a RLE Lossless one.
590  *
591  * @return  True when RLE Lossless found. False in all
592  *          other cases.
593  */
594 bool gdcmHeader::IsRLELossLessTransferSyntax(void) {
595    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
596    if ( !Element )
597       return false;
598    LoadElementValueSafe(Element);
599    std::string Transfer = Element->GetValue();
600    if ( Transfer == "1.2.840.10008.1.2.5" )
601       return true;
602    return false;
603 }
604
605 /**
606  * \ingroup gdcmHeader
607  * \brief   Determines if the Transfer Syntax was already encountered
608  *          and if it corresponds to a JPEG200 one.0
609  *
610  * @return  True when JPEG2000 (Lossly or LossLess) found. False in all
611  *          other cases.
612  */
613 bool gdcmHeader::IsJPEG2000(void) {
614    gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
615    if ( !Element )
616       return false;
617    LoadElementValueSafe(Element);
618    std::string Transfer = Element->GetValue();
619    if (    (Transfer == "1.2.840.10008.1.2.4.90") 
620         || (Transfer == "1.2.840.10008.1.2.4.91") )
621       return true;
622    return false;
623 }
624
625 /**
626  * \ingroup gdcmHeader
627  * \brief   Predicate for dicom version 3 file.
628  * @return  True when the file is a dicom version 3.
629  */
630 bool gdcmHeader::IsDicomV3(void) {
631    if (   (filetype == ExplicitVR)
632        || (filetype == ImplicitVR) )
633       return true;
634    return false;
635 }
636
637 /**
638  * \ingroup gdcmHeader
639  * \brief   When the length of an element value is obviously wrong (because
640  *          the parser went Jabberwocky) one can hope improving things by
641  *          applying this heuristic.
642  */
643 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
644
645    ElVal->SetReadLength(FoundLength); // will be updated only if a bug is found
646                      
647    if ( FoundLength == 0xffffffff) {  
648       FoundLength = 0;
649    }
650       
651       // Sorry for the patch!  
652       // XMedCom did the trick to read some nasty GE images ...
653    else if (FoundLength == 13) {
654       // The following 'if' will be removed when there is no more
655       // images on Creatis HDs with a 13 length for Manufacturer...
656       if ( (ElVal->GetGroup() != 0x0008) ||  
657            ( (ElVal->GetElement() != 0x0070) && (ElVal->GetElement() != 0x0080) ) ) {
658       // end of remove area
659          FoundLength =10;
660          ElVal->SetReadLength(10); // a bug is to be fixed
661       }
662    } 
663      // to fix some garbage 'Leonardo' Siemens images
664      // May be commented out to avoid overhead
665    else if ( (ElVal->GetGroup() == 0x0009) 
666        &&
667        ( (ElVal->GetElement() == 0x1113) || (ElVal->GetElement() == 0x1114) ) ){
668         FoundLength =4;
669         ElVal->SetReadLength(4); // a bug is to be fixed 
670    } 
671      // end of fix
672          
673     // to try to 'go inside' SeQuences (with length), and not to skip them        
674     else if ( ElVal->GetVR() == "SQ") { 
675        if (enableSequences)    // only if the user does want to !
676           FoundLength =0;        
677     } 
678     
679     // a SeQuence Element is beginning
680     // Let's forget it's length
681     // (we want to 'go inside')
682     else if(ElVal->GetGroup() == 0xfffe){
683           FoundLength =0;            
684     }
685                   
686    ElVal->SetUsableLength(FoundLength);
687 }
688
689 /**
690  * \ingroup gdcmHeader
691  * \brief   
692  *
693  * @return 
694  */
695  guint32 gdcmHeader::FindLengthOB(void) {
696    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
697    guint16 g;
698    guint16 n; 
699    long PositionOnEntry = ftell(fp);
700    bool FoundSequenceDelimiter = false;
701    guint32 TotalLength = 0;
702    guint32 ItemLength;
703
704    while ( ! FoundSequenceDelimiter) {
705       g = ReadInt16();
706       n = ReadInt16();   
707       if (errno == 1)
708          return 0;
709       TotalLength += 4;  // We even have to decount the group and element 
710      
711       if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ {
712          char msg[100]; // for sprintf. Sorry
713          sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
714          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg); 
715          errno = 1;
716          return 0;
717       }
718       if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header  */ 
719          FoundSequenceDelimiter = true;
720       else if ( n != 0xe000 ){
721          char msg[100];  // for sprintf. Sorry
722          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
723                       n, g,n);
724          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
725          errno = 1;
726          return 0;
727       }
728       ItemLength = ReadInt32();
729       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
730                                       // the ItemLength with ReadInt32                                     
731       SkipBytes(ItemLength);
732    }
733    fseek(fp, PositionOnEntry, SEEK_SET);
734    return TotalLength;
735 }
736
737 /**
738  * \ingroup gdcmHeader
739  * \brief   
740  *
741  * @return 
742  */
743  void gdcmHeader::FindLength (gdcmElValue * ElVal) {
744    guint16 element = ElVal->GetElement();
745    guint16 group   = ElVal->GetGroup();
746    std::string  vr = ElVal->GetVR();
747    guint16 length16;
748    if( (element == 0x0010) && (group == 0x7fe0) ) {
749       dbg.SetDebug(0);
750       dbg.Verbose(2, "gdcmHeader::FindLength: ",
751                      "we reached 7fe0 0010");
752    }   
753    
754    if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
755       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
756       
757          // The following reserved two bytes (see PS 3.5-2001, section
758          // 7.1.2 Data element structure with explicit vr p27) must be
759          // skipped before proceeding on reading the length on 4 bytes.
760          fseek(fp, 2L, SEEK_CUR);
761
762          guint32 length32 = ReadInt32();
763
764          if ( (vr == "OB") && (length32 == 0xffffffff) ) {
765             ElVal->SetLength(FindLengthOB());
766             return;
767          }
768          FixFoundLength(ElVal, length32); 
769          return;
770       }
771
772       // Length is encoded on 2 bytes.
773       length16 = ReadInt16();
774       
775       // We can tell the current file is encoded in big endian (like
776       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
777       // and it's value is the one of the encoding of a big endian file.
778       // In order to deal with such big endian encoded files, we have
779       // (at least) two strategies:
780       // * when we load the "Transfer Syntax" tag with value of big endian
781       //   encoding, we raise the proper flags. Then we wait for the end
782       //   of the META group (0x0002) among which is "Transfer Syntax",
783       //   before switching the swap code to big endian. We have to postpone
784       //   the switching of the swap code since the META group is fully encoded
785       //   in little endian, and big endian coding only starts at the next
786       //   group. The corresponding code can be hard to analyse and adds
787       //   many additional unnecessary tests for regular tags.
788       // * the second strategy consists in waiting for trouble, that shall
789       //   appear when we find the first group with big endian encoding. This
790       //   is easy to detect since the length of a "Group Length" tag (the
791       //   ones with zero as element number) has to be of 4 (0x0004). When we
792       //   encounter 1024 (0x0400) chances are the encoding changed and we
793       //   found a group with big endian encoding.
794       // We shall use this second strategy. In order to make sure that we
795       // can interpret the presence of an apparently big endian encoded
796       // length of a "Group Length" without committing a big mistake, we
797       // add an additional check: we look in the already parsed elements
798       // for the presence of a "Transfer Syntax" whose value has to be "big
799       // endian encoding". When this is the case, chances are we have got our
800       // hands on a big endian encoded file: we switch the swap code to
801       // big endian and proceed...
802       if ( (element  == 0x0000) && (length16 == 0x0400) ) {
803          if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
804             dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
805             errno = 1;
806             return;
807          }
808          length16 = 4;
809          SwitchSwapToBigEndian();
810          // Restore the unproperly loaded values i.e. the group, the element
811          // and the dictionary entry depending on them.
812          guint16 CorrectGroup   = SwapShort(ElVal->GetGroup());
813          guint16 CorrectElem    = SwapShort(ElVal->GetElement());
814          gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
815                                                        CorrectElem);
816          if (!NewTag) {
817             // This correct tag is not in the dictionary. Create a new one.
818             NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
819          }
820          // FIXME this can create a memory leaks on the old entry that be
821          // left unreferenced.
822          ElVal->SetDictEntry(NewTag);
823       }
824        
825       // Heuristic: well some files are really ill-formed.
826       if ( length16 == 0xffff) {
827          length16 = 0;
828          //dbg.Verbose(0, "gdcmHeader::FindLength",
829          //            "Erroneous element length fixed.");
830          // Actually, length= 0xffff means that we deal with
831          // Unknown Sequence Length 
832       }
833
834       FixFoundLength(ElVal, (guint32)length16);
835       return;
836    }
837
838    // Either implicit VR or a non DICOM conformal (see not below) explicit
839    // VR that ommited the VR of (at least) this element. Farts happen.
840    // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
841    // on Data elements "Implicit and Explicit VR Data Elements shall
842    // not coexist in a Data Set and Data Sets nested within it".]
843    // Length is on 4 bytes.
844    FixFoundLength(ElVal, ReadInt32());
845    return;
846 }
847
848 /**
849  * \ingroup gdcmHeader
850  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
851  *          processor order.
852  * @return  The properly swaped 32 bits integer.
853  */
854 guint32 gdcmHeader::SwapLong(guint32 a) {
855    switch (sw) {
856    case    0 :
857       break;
858    case 4321 :
859       a=(   ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000)    | 
860             ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
861       break;
862    
863    case 3412 :
864       a=(   ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
865       break;
866    
867    case 2143 :
868       a=(    ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
869       break;
870    default :
871       dbg.Error(" gdcmHeader::SwapLong : unset swap code");
872       a=0;
873    }
874    return(a);
875 }
876
877 /**
878  * \ingroup gdcmHeader
879  * \brief   Swaps the bytes so they agree with the processor order
880  * @return  The properly swaped 16 bits integer.
881  */
882 guint16 gdcmHeader::SwapShort(guint16 a) {
883    if ( (sw==4321)  || (sw==2143) )
884       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
885    return (a);
886 }
887
888 /**
889  * \ingroup gdcmHeader
890  * \brief   
891  *
892  * @return 
893  */
894  void gdcmHeader::SkipBytes(guint32 NBytes) {
895    //FIXME don't dump the returned value
896    (void)fseek(fp, (long)NBytes, SEEK_CUR);
897 }
898
899 /**
900  * \ingroup gdcmHeader
901  * \brief   
902  * @param ElVal 
903  * @return 
904  */
905  void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
906     SkipBytes(ElVal->GetLength());
907 }
908
909 /**
910  * \ingroup gdcmHeader
911  * \brief   
912  * @param NewSize
913  * @return 
914  */
915  void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
916    if (NewSize < 0)
917       return;
918    if ((guint32)NewSize >= (guint32)0xffffffff) {
919       MaxSizeLoadElementValue = 0xffffffff;
920       return;
921    }
922    MaxSizeLoadElementValue = NewSize;
923 }
924
925 /**
926  * \ingroup       gdcmHeader
927  * \brief         Loads the element content if it's length is not bigger
928  *                than the value specified with
929  *                gdcmHeader::SetMaxSizeLoadElementValue()
930  */
931 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
932    size_t item_read;
933    guint16 group  = ElVal->GetGroup();
934    std::string  vr= ElVal->GetVR();
935    guint32 length = ElVal->GetLength();
936    bool SkipLoad  = false;
937
938    fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
939    
940    // FIXME Sequences not treated yet !
941    //
942    // Ne faudrait-il pas au contraire trouver immediatement
943    // une maniere 'propre' de traiter les sequences (vr = SQ)
944    // car commencer par les ignorer risque de conduire a qq chose
945    // qui pourrait ne pas etre generalisable
946    // Well, I'm expecting your code !!!
947    
948    // the test was commented out to 'go inside' the SeQuences
949    // we don't any longer skip them !
950     
951   // if( vr == "SQ" )  
952   //    SkipLoad = true;
953
954    // A SeQuence "contains" a set of Elements.  
955    //          (fffe e000) tells us an Element is beginning
956    //          (fffe e00d) tells us an Element just ended
957    //          (fffe e0dd) tells us the current SeQuence just ended
958   
959    if( group == 0xfffe )
960       SkipLoad = true;
961
962    if ( SkipLoad ) {
963       ElVal->SetLength(0);
964       ElVal->SetValue("gdcm::Skipped");
965       return;
966    }
967
968    // When the length is zero things are easy:
969    if ( length == 0 ) {
970       ElVal->SetValue("");
971       return;
972    }
973
974    // The elements whose length is bigger than the specified upper bound
975    // are not loaded. Instead we leave a short notice of the offset of
976    // the element content and it's length.
977    if (length > MaxSizeLoadElementValue) {
978       std::ostringstream s;
979       s << "gdcm::NotLoaded.";
980       s << " Address:" << (long)ElVal->GetOffset();
981       s << " Length:"  << ElVal->GetLength();
982       s << " x(" << std::hex << ElVal->GetLength() << ")";
983       ElVal->SetValue(s.str());
984       return;
985    }
986    
987    // When an integer is expected, read and convert the following two or
988    // four bytes properly i.e. as an integer as opposed to a string.
989         
990         // Actually, elements with Value Multiplicity > 1
991         // contain a set of integers (not a single one)         
992         // Any compacter code suggested (?)
993                 
994    if ( IsAnInteger(ElVal) ) {
995       guint32 NewInt;
996       std::ostringstream s;
997       int nbInt;
998       if (vr == "US" || vr == "SS") {
999          nbInt = length / 2;
1000          NewInt = ReadInt16();
1001          s << NewInt;
1002          if (nbInt > 1) {
1003             for (int i=1; i < nbInt; i++) {
1004                s << '\\';
1005                NewInt = ReadInt16();
1006                s << NewInt;
1007             }
1008          }
1009                         
1010       } else if (vr == "UL" || vr == "SL") {
1011          nbInt = length / 4;
1012          NewInt = ReadInt32();
1013          s << NewInt;
1014          if (nbInt > 1) {
1015             for (int i=1; i < nbInt; i++) {
1016                s << '\\';
1017                NewInt = ReadInt32();
1018                s << NewInt;
1019             }
1020          }
1021       }                                 
1022 #ifdef GDCM_NO_ANSI_STRING_STREAM
1023       s << std::ends; // to avoid oddities on Solaris
1024 #endif //GDCM_NO_ANSI_STRING_STREAM
1025       ElVal->SetValue(s.str());
1026       return;   
1027    }
1028    
1029    // We need an additional byte for storing \0 that is not on disk
1030    char* NewValue = (char*)malloc(length+1);
1031    if( !NewValue) {
1032       dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
1033       return;
1034    }
1035    NewValue[length]= 0;
1036    
1037    item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
1038    if ( item_read != 1 ) {
1039       free(NewValue);
1040       dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
1041       ElVal->SetValue("gdcm::UnRead");
1042       return;
1043    }
1044    ElVal->SetValue(NewValue);
1045    free(NewValue);
1046 }
1047
1048 /**
1049  * \ingroup       gdcmHeader
1050  * \brief         Loads the element while preserving the current
1051  *                underlying file position indicator as opposed to
1052  *                to LoadElementValue that modifies it.
1053  * @param ElVal   Element whose value shall be loaded. 
1054  * @return  
1055  */
1056 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
1057    long PositionOnEntry = ftell(fp);
1058    LoadElementValue(ElVal);
1059    fseek(fp, PositionOnEntry, SEEK_SET);
1060 }
1061
1062 /**
1063  * \ingroup gdcmHeader
1064  * \brief Reads a supposed to be 16 Bits integer
1065  * \     (swaps it depending on processor endianity) 
1066  *
1067  * @return integer acts as a boolean
1068  */
1069 guint16 gdcmHeader::ReadInt16(void) {
1070    guint16 g;
1071    size_t item_read;
1072    item_read = fread (&g, (size_t)2,(size_t)1, fp);
1073    if ( item_read != 1 ) {
1074       // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
1075       // if(feof(fp)) 
1076       //    dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
1077       if(ferror(fp)) 
1078          dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
1079       errno = 1;
1080       return 0;
1081    }
1082    errno = 0;
1083    g = SwapShort(g);
1084    return g;
1085 }
1086
1087 /**
1088  * \ingroup gdcmHeader
1089  * \brief  Reads a supposed to be 32 Bits integer
1090  * \       (swaps it depending on processor endianity)  
1091  *
1092  * @return 
1093  */
1094 guint32 gdcmHeader::ReadInt32(void) {
1095    guint32 g;
1096    size_t item_read;
1097    item_read = fread (&g, (size_t)4,(size_t)1, fp);
1098    if ( item_read != 1 ) { 
1099       //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
1100       //if(feof(fp)) 
1101       //   dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
1102      if(ferror(fp)) 
1103          dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");   
1104       errno = 1;
1105       return 0;
1106    }
1107    errno = 0;   
1108    g = SwapLong(g);
1109    return g;
1110 }
1111
1112 /**
1113  * \ingroup gdcmHeader
1114  * \brief   
1115  *
1116  * @return 
1117  */
1118  gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1119
1120    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1121    if (!elValue) {
1122       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1123                   "failed to Locate gdcmElValue");
1124       return (gdcmElValue*)0;
1125    }
1126    return elValue;
1127 }
1128
1129 /**
1130  * \ingroup gdcmHeader
1131  * \brief   Build a new Element Value from all the low level arguments. 
1132  *          Check for existence of dictionary entry, and build
1133  *          a default one when absent.
1134  * @param   Group group   of the underlying DictEntry
1135  * @param   Elem  element of the underlying DictEntry
1136  */
1137 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1138    // Find out if the tag we encountered is in the dictionaries:
1139    gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1140    if (!NewTag)
1141       NewTag = new gdcmDictEntry(Group, Elem);
1142
1143    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1144    if (!NewElVal) {
1145       dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1146                   "failed to allocate gdcmElValue");
1147       return (gdcmElValue*)0;
1148    }
1149    return NewElVal;
1150 }
1151
1152 /**
1153  * \ingroup gdcmHeader
1154  * \brief   TODO
1155  * @param   Value
1156  * @param   Group
1157  * @param   Elem
1158  * \return integer acts as a boolean
1159  */
1160 int gdcmHeader::ReplaceOrCreateByNumber(std::string Value, 
1161                                         guint16 Group, guint16 Elem ) {
1162         // TODO : FIXME JPRx
1163         // curieux, non ?
1164         // on (je) cree une Elvalue ne contenant pas de valeur
1165         // on l'ajoute au ElValSet
1166         // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1167         // --> devrait pouvoir etre fait + simplement ???
1168    if (CheckIfExistByNumber(Group, Elem) == 0) {
1169       gdcmElValue* a =NewElValueByNumber(Group, Elem);
1170       if (a == NULL) 
1171          return 0;
1172       PubElValSet.Add(a);
1173    }   
1174    PubElValSet.SetElValueByNumber(Value, Group, Elem);
1175    return(1);
1176 }   
1177
1178
1179 /**
1180  * \ingroup gdcmHeader
1181  * \brief   Modify (or Creates if not found) an element
1182  * @param   Value new value
1183  * @param   Group
1184  * @param   Elem
1185  * \return integer acts as a boolean 
1186  * 
1187  */
1188 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1189
1190    gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1191    PubElValSet.Add(nvElValue);
1192    std::string v = Value;       
1193    PubElValSet.SetElValueByNumber(v, Group, Elem);
1194    return(1);
1195 }  
1196
1197
1198 /**
1199  * \ingroup gdcmHeader
1200  * \brief   Set a new value if the invoked element exists
1201  *          Seems to be useless !!!
1202  * @param   Value
1203  * @param   Group
1204  * @param   Elem
1205  * \return integer acts as a boolean 
1206  */
1207 int gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1208
1209    //gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1210    std::string v = Value;       
1211    PubElValSet.SetElValueByNumber(v, Group, Elem);
1212    return 1;
1213
1214
1215
1216 /**
1217  * \ingroup gdcmHeader
1218  * \brief   Checks if a given ElValue (group,number) 
1219  * \ exists in the Public ElValSet
1220  * @param   Group
1221  * @param   Elem
1222  * @return  integer acts as a boolean  
1223  */
1224  
1225 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1226    return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1227  }
1228   
1229 /**
1230  * \ingroup gdcmHeader
1231  * \brief   Build a new Element Value from all the low level arguments. 
1232  *          Check for existence of dictionary entry, and build
1233  *          a default one when absent.
1234  * @param   Name    Name of the underlying DictEntry
1235  */
1236 gdcmElValue* gdcmHeader::NewElValueByName(std::string Name) {
1237
1238    gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1239    if (!NewTag)
1240       NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1241
1242    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1243    if (!NewElVal) {
1244       dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1245                   "failed to allocate gdcmElValue");
1246       return (gdcmElValue*)0;
1247    }
1248    return NewElVal;
1249 }  
1250
1251 /**
1252  * \ingroup gdcmHeader
1253  * \brief   Read the next tag but WITHOUT loading it's value
1254  * @return  On succes the newly created ElValue, NULL on failure.      
1255  */
1256 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1257   
1258    guint16 g,n;
1259    gdcmElValue * NewElVal;
1260    
1261    g = ReadInt16();
1262    n = ReadInt16();
1263       
1264    if (errno == 1)
1265       // We reached the EOF (or an error occured) and header parsing
1266       // has to be considered as finished.
1267       return (gdcmElValue *)0;
1268    
1269    NewElVal = NewElValueByNumber(g, n);
1270    FindVR(NewElVal);
1271    FindLength(NewElVal);
1272         
1273    if (errno == 1) {
1274       // Call it quits
1275       return (gdcmElValue *)0;
1276    }
1277    NewElVal->SetOffset(ftell(fp));  
1278    //if ( (g==0x7fe0) && (n==0x0010) ) 
1279    return NewElVal;
1280 }
1281
1282 /**
1283  * \ingroup gdcmHeader
1284  * \brief   Apply some heuristics to predict wether the considered 
1285  *          element value contains/represents an integer or not.
1286  * @param   ElVal The element value on which to apply the predicate.
1287  * @return  The result of the heuristical predicate.
1288  */
1289 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1290    guint16 element = ElVal->GetElement();
1291    std::string  vr = ElVal->GetVR();
1292    guint32 length  = ElVal->GetLength();
1293
1294    // When we have some semantics on the element we just read, and if we
1295    // a priori know we are dealing with an integer, then we shall be
1296    // able to swap it's element value properly.
1297    if ( element == 0 )  {  // This is the group length of the group
1298       if (length == 4)
1299          return true;
1300       else {
1301          dbg.Error("gdcmHeader::IsAnInteger",
1302             "Erroneous Group Length element length.");     
1303       }
1304    }
1305    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1306       return true;
1307    
1308    return false;
1309 }
1310
1311 /**
1312  * \ingroup gdcmHeader
1313  * \brief   Recover the offset (from the beginning of the file) of the pixels.
1314  */
1315 size_t gdcmHeader::GetPixelOffset(void) {
1316    // If this file complies with the norm we should encounter the
1317    // "Image Location" tag (0x0028,  0x0200). This tag contains the
1318    // the group that contains the pixel data (hence the "Pixel Data"
1319    // is found by indirection through the "Image Location").
1320    // Inside the group pointed by "Image Location" the searched element
1321    // is conventionally the element 0x0010 (when the norm is respected).
1322    // When the "Image Location" is absent we default to group 0x7fe0.
1323    guint16 grPixel;
1324    guint16 numPixel;
1325    std::string ImageLocation = GetPubElValByName("Image Location");
1326    if ( ImageLocation == GDCM_UNFOUND ) {
1327       grPixel = 0x7fe0;
1328    } else {
1329       grPixel = (guint16) atoi( ImageLocation.c_str() );
1330    }
1331    if (grPixel != 0x7fe0)
1332       // This is a kludge for old dirty Philips imager.
1333       numPixel = 0x1010;
1334    else
1335       numPixel = 0x0010;
1336          
1337    gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1338                                                               numPixel);
1339    if (PixelElement)
1340       return PixelElement->GetOffset();
1341    else
1342       return 0;
1343 }
1344
1345 /**
1346  * \ingroup gdcmHeader
1347  * \brief   Recover the pixel area length (in Bytes) .
1348  */
1349 size_t gdcmHeader::GetPixelAreaLength(void) {
1350    // If this file complies with the norm we should encounter the
1351    // "Image Location" tag (0x0028,  0x0200). This tag contains the
1352    // the group that contains the pixel data (hence the "Pixel Data"
1353    // is found by indirection through the "Image Location").
1354    // Inside the group pointed by "Image Location" the searched element
1355    // is conventionally the element 0x0010 (when the norm is respected).
1356    // When the "Image Location" is absent we default to group 0x7fe0.
1357    guint16 grPixel;
1358    guint16 numPixel;
1359    std::string ImageLocation = GetPubElValByName("Image Location");
1360    if ( ImageLocation == GDCM_UNFOUND ) {
1361       grPixel = 0x7fe0;
1362    } else {
1363       grPixel = (guint16) atoi( ImageLocation.c_str() );
1364    }
1365    if (grPixel != 0x7fe0)
1366       // This is a kludge for old dirty Philips imager.
1367       numPixel = 0x1010;
1368    else
1369       numPixel = 0x0010;
1370          
1371    gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1372                                                               numPixel);
1373    if (PixelElement)
1374       return PixelElement->GetLength();
1375    else
1376       return 0;
1377 }
1378
1379 /**
1380  * \ingroup gdcmHeader
1381  * \brief   Searches both the public and the shadow dictionary (when they
1382  *          exist) for the presence of the DictEntry with given
1383  *          group and element. The public dictionary has precedence on the
1384  *          shadow one.
1385  * @param   group   group of the searched DictEntry
1386  * @param   element element of the searched DictEntry
1387  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1388  */
1389 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1390                                                  guint16 element) {
1391    gdcmDictEntry * found = (gdcmDictEntry*)0;
1392    if (!RefPubDict && !RefShaDict) {
1393       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1394                      "we SHOULD have a default dictionary");
1395    }
1396    if (RefPubDict) {
1397       found = RefPubDict->GetTagByNumber(group, element);
1398       if (found)
1399          return found;
1400    }
1401    if (RefShaDict) {
1402       found = RefShaDict->GetTagByNumber(group, element);
1403       if (found)
1404          return found;
1405    }
1406    return found;
1407 }
1408
1409 /**
1410  * \ingroup gdcmHeader
1411  * \brief   Searches both the public and the shadow dictionary (when they
1412  *          exist) for the presence of the DictEntry with given name.
1413  *          The public dictionary has precedence on the shadow one.
1414  * @param   Name name of the searched DictEntry
1415  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1416  */
1417 gdcmDictEntry * gdcmHeader::GetDictEntryByName(std::string Name) {
1418    gdcmDictEntry * found = (gdcmDictEntry*)0;
1419    if (!RefPubDict && !RefShaDict) {
1420       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1421                      "we SHOULD have a default dictionary");
1422    }
1423    if (RefPubDict) {
1424       found = RefPubDict->GetTagByName(Name);
1425       if (found)
1426          return found;
1427    }
1428    if (RefShaDict) {
1429       found = RefShaDict->GetTagByName(Name);
1430       if (found)
1431          return found;
1432    }
1433    return found;
1434 }
1435
1436 /**
1437  * \ingroup gdcmHeader
1438  * \brief   Searches within the public dictionary for element value of
1439  *          a given tag.
1440  * @param   group Group of the researched tag.
1441  * @param   element Element of the researched tag.
1442  * @return  Corresponding element value when it exists, and the string
1443  *          GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1444  */
1445 std::string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1446    return PubElValSet.GetElValueByNumber(group, element);
1447 }
1448
1449 /**
1450  * \ingroup gdcmHeader
1451  * \brief   Searches within the public dictionary for element value
1452  *          representation of a given tag.
1453  *
1454  *          Obtaining the VR (Value Representation) might be needed by caller
1455  *          to convert the string typed content to caller's native type 
1456  *          (think of C++ vs Python). The VR is actually of a higher level
1457  *          of semantics than just the native C++ type.
1458  * @param   group Group of the researched tag.
1459  * @param   element Element of the researched tag.
1460  * @return  Corresponding element value representation when it exists,
1461  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1462  */
1463 std::string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1464    gdcmElValue* elem =  PubElValSet.GetElementByNumber(group, element);
1465    if ( !elem )
1466       return GDCM_UNFOUND;
1467    return elem->GetVR();
1468 }
1469
1470 /**
1471  * \ingroup gdcmHeader
1472  * \brief   Searches within the public dictionary for element value of
1473  *          a given tag.
1474  * @param   TagName name of the searched element.
1475  * @return  Corresponding element value when it exists, and the string
1476  *          GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1477  */
1478 std::string gdcmHeader::GetPubElValByName(std::string TagName) {
1479    return PubElValSet.GetElValueByName(TagName);
1480 }
1481
1482 /**
1483  * \ingroup gdcmHeader
1484  * \brief   Searches within the elements parsed with the public dictionary for
1485  *          the element value representation of a given tag.
1486  *
1487  *          Obtaining the VR (Value Representation) might be needed by caller
1488  *          to convert the string typed content to caller's native type 
1489  *          (think of C++ vs Python). The VR is actually of a higher level
1490  *          of semantics than just the native C++ type.
1491  * @param   TagName name of the searched element.
1492  * @return  Corresponding element value representation when it exists,
1493  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1494  */
1495 std::string gdcmHeader::GetPubElValRepByName(std::string TagName) {
1496    gdcmElValue* elem =  PubElValSet.GetElementByName(TagName);
1497    if ( !elem )
1498       return GDCM_UNFOUND;
1499    return elem->GetVR();
1500 }
1501
1502 /**
1503  * \ingroup gdcmHeader
1504  * \brief   Searches within elements parsed with the SHADOW dictionary 
1505  *          for the element value of a given tag.
1506  * @param   group Group of the searched tag.
1507  * @param   element Element of the searched tag.
1508  * @return  Corresponding element value representation when it exists,
1509  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1510  */
1511 std::string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1512    return ShaElValSet.GetElValueByNumber(group, element);
1513 }
1514
1515 /**
1516  * \ingroup gdcmHeader
1517  * \brief   Searches within the elements parsed with the SHADOW dictionary
1518  *          for the element value representation of a given tag.
1519  *
1520  *          Obtaining the VR (Value Representation) might be needed by caller
1521  *          to convert the string typed content to caller's native type 
1522  *          (think of C++ vs Python). The VR is actually of a higher level
1523  *          of semantics than just the native C++ type.
1524  * @param   group Group of the searched tag.
1525  * @param   element Element of the searched tag.
1526  * @return  Corresponding element value representation when it exists,
1527  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1528  */
1529 std::string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1530    gdcmElValue* elem =  ShaElValSet.GetElementByNumber(group, element);
1531    if ( !elem )
1532       return GDCM_UNFOUND;
1533    return elem->GetVR();
1534 }
1535
1536 /**
1537  * \ingroup gdcmHeader
1538  * \brief   Searches within the elements parsed with the shadow dictionary
1539  *          for an element value of given tag.
1540  * @param   TagName name of the searched element.
1541  * @return  Corresponding element value when it exists, and the string
1542  *          GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1543  */
1544 std::string gdcmHeader::GetShaElValByName(std::string TagName) {
1545    return ShaElValSet.GetElValueByName(TagName);
1546 }
1547
1548 /**
1549  * \ingroup gdcmHeader
1550  * \brief   Searches within the elements parsed with the shadow dictionary for
1551  *          the element value representation of a given tag.
1552  *
1553  *          Obtaining the VR (Value Representation) might be needed by caller
1554  *          to convert the string typed content to caller's native type 
1555  *          (think of C++ vs Python). The VR is actually of a higher level
1556  *          of semantics than just the native C++ type.
1557  * @param   TagName name of the searched element.
1558  * @return  Corresponding element value representation when it exists,
1559  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1560  */
1561 std::string gdcmHeader::GetShaElValRepByName(std::string TagName) {
1562    gdcmElValue* elem =  ShaElValSet.GetElementByName(TagName);
1563    if ( !elem )
1564       return GDCM_UNFOUND;
1565    return elem->GetVR();
1566 }
1567
1568 /**
1569  * \ingroup gdcmHeader
1570  * \brief   Searches within elements parsed with the public dictionary 
1571  *          and then within the elements parsed with the shadow dictionary
1572  *          for the element value of a given tag.
1573  * @param   group Group of the searched tag.
1574  * @param   element Element of the searched tag.
1575  * @return  Corresponding element value representation when it exists,
1576  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1577  */
1578 std::string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1579    std::string pub = GetPubElValByNumber(group, element);
1580    if (pub.length())
1581       return pub;
1582    return GetShaElValByNumber(group, element);
1583 }
1584
1585 /**
1586  * \ingroup gdcmHeader
1587  * \brief   Searches within elements parsed with the public dictionary 
1588  *          and then within the elements parsed with the shadow dictionary
1589  *          for the element value representation of a given tag.
1590  *
1591  *          Obtaining the VR (Value Representation) might be needed by caller
1592  *          to convert the string typed content to caller's native type 
1593  *          (think of C++ vs Python). The VR is actually of a higher level
1594  *          of semantics than just the native C++ type.
1595  * @param   group Group of the searched tag.
1596  * @param   element Element of the searched tag.
1597  * @return  Corresponding element value representation when it exists,
1598  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1599  */
1600 std::string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1601    std::string pub = GetPubElValRepByNumber(group, element);
1602    if (pub.length())
1603       return pub;
1604    return GetShaElValRepByNumber(group, element);
1605 }
1606
1607 /**
1608  * \ingroup gdcmHeader
1609  * \brief   Searches within elements parsed with the public dictionary 
1610  *          and then within the elements parsed with the shadow dictionary
1611  *          for the element value of a given tag.
1612  * @param   TagName name of the searched element.
1613  * @return  Corresponding element value when it exists,
1614  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1615  */
1616 std::string gdcmHeader::GetElValByName(std::string TagName) {
1617    std::string pub = GetPubElValByName(TagName);
1618    if (pub.length())
1619       return pub;
1620    return GetShaElValByName(TagName);
1621 }
1622
1623 /**
1624  * \ingroup gdcmHeader
1625  * \brief   Searches within elements parsed with the public dictionary 
1626  *          and then within the elements parsed with the shadow dictionary
1627  *          for the element value representation of a given tag.
1628  *
1629  *          Obtaining the VR (Value Representation) might be needed by caller
1630  *          to convert the string typed content to caller's native type 
1631  *          (think of C++ vs Python). The VR is actually of a higher level
1632  *          of semantics than just the native C++ type.
1633  * @param   TagName name of the searched element.
1634  * @return  Corresponding element value representation when it exists,
1635  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1636  */
1637 std::string gdcmHeader::GetElValRepByName(std::string TagName) {
1638    std::string pub = GetPubElValRepByName(TagName);
1639    if (pub.length())
1640       return pub;
1641    return GetShaElValRepByName(TagName);
1642 }
1643
1644 /**
1645  * \ingroup gdcmHeader
1646  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1647  *          through it's (group, element) and modifies it's content with
1648  *          the given value.
1649  * @param   content new value to substitute with
1650  * @param   group   group of the ElVal to modify
1651  * @param   element element of the ElVal to modify
1652  */
1653 int gdcmHeader::SetPubElValByNumber(std::string content, guint16 group,
1654                                     guint16 element)
1655                                     
1656 //TODO  : homogeneiser les noms : SetPubElValByNumber   
1657 //                    qui appelle PubElValSet.SetElValueByNumber 
1658 //        pourquoi pas            SetPubElValueByNumber ??
1659 {
1660
1661    return (  PubElValSet.SetElValueByNumber (content, group, element) );
1662 }
1663
1664 /**
1665  * \ingroup gdcmHeader
1666  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1667  *          through tag name and modifies it's content with the given value.
1668  * @param   content new value to substitute with
1669  * @param   TagName name of the tag to be modified
1670  */
1671 int gdcmHeader::SetPubElValByName(std::string content, std::string TagName) {
1672    return (  PubElValSet.SetElValueByName (content, TagName) );
1673 }
1674
1675 /**
1676  * \ingroup gdcmHeader
1677  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1678  *          through it's (group, element) and modifies it's length with
1679  *          the given value.
1680  * \warning Use with extreme caution.
1681  * @param   length new length to substitute with
1682  * @param   group   group of the ElVal to modify
1683  * @param   element element of the ElVal to modify
1684  * @return  1 on success, 0 otherwise.
1685  */
1686
1687 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1688                                     guint16 element) {
1689         return (  PubElValSet.SetElValueLengthByNumber (length, group, element) );
1690 }
1691
1692 /**
1693  * \ingroup gdcmHeader
1694  * \brief   Accesses an existing gdcmElValue in the ShaElValSet of this instance
1695  *          through it's (group, element) and modifies it's content with
1696  *          the given value.
1697  * @param   content new value to substitute with
1698  * @param   group   group of the ElVal to modify
1699  * @param   element element of the ElVal to modify
1700  * @return  1 on success, 0 otherwise.
1701  */
1702 int gdcmHeader::SetShaElValByNumber(std::string content,
1703                                     guint16 group, guint16 element) {
1704    return (  ShaElValSet.SetElValueByNumber (content, group, element) );
1705 }
1706
1707 /**
1708  * \ingroup gdcmHeader
1709  * \brief   Accesses an existing gdcmElValue in the ShaElValSet of this instance
1710  *          through tag name and modifies it's content with the given value.
1711  * @param   content new value to substitute with
1712  * @param   ShadowTagName name of the tag to be modified
1713  */
1714 int gdcmHeader::SetShaElValByName(std::string content, std::string ShadowTagName) {
1715    return (  ShaElValSet.SetElValueByName (content, ShadowTagName) );
1716 }
1717
1718 /**
1719  * \ingroup gdcmHeader
1720  * \brief   Parses the header of the file but WITHOUT loading element values.
1721  */
1722 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1723    gdcmElValue * newElValue = (gdcmElValue *)0;
1724    
1725    rewind(fp);
1726    CheckSwap();
1727    while ( (newElValue = ReadNextElement()) ) { 
1728       SkipElementValue(newElValue);
1729       PubElValSet.Add(newElValue);
1730    }
1731 }
1732
1733 /**
1734  * \ingroup gdcmHeader
1735  * \brief  This predicate, based on hopefully reasonable heuristics,
1736  *         decides whether or not the current gdcmHeader was properly parsed
1737  *         and contains the mandatory information for being considered as
1738  *         a well formed and usable image.
1739  * @return true when gdcmHeader is the one of a reasonable Dicom file,
1740  *         false otherwise. 
1741  */
1742 bool gdcmHeader::IsReadable(void) {
1743    if (   GetElValByName("Image Dimensions") != GDCM_UNFOUND
1744       && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1745       return false;
1746    }
1747    if ( GetElValByName("Bits Allocated")       == GDCM_UNFOUND )
1748       return false;
1749    if ( GetElValByName("Bits Stored")          == GDCM_UNFOUND )
1750       return false;
1751    if ( GetElValByName("High Bit")             == GDCM_UNFOUND )
1752       return false;
1753    if ( GetElValByName("Pixel Representation") == GDCM_UNFOUND )
1754       return false;
1755    return true;
1756 }
1757
1758 /**
1759  * \ingroup gdcmHeader
1760  * \brief   Small utility function that creates a new manually crafted
1761  *          (as opposed as read from the file) gdcmElValue with user
1762  *          specified name and adds it to the public tag hash table.
1763  * \note    A fake TagKey is generated so the PubDict can keep it's coherence.
1764  * @param   NewTagName The name to be given to this new tag.
1765  * @param   VR The Value Representation to be given to this new tag.
1766  * @ return The newly hand crafted Element Value.
1767  */
1768 gdcmElValue* gdcmHeader::NewManualElValToPubDict(std::string NewTagName, 
1769                                                  std::string VR) {
1770    gdcmElValue* NewElVal = (gdcmElValue*)0;
1771    guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
1772    guint32 FreeElem = 0;
1773    gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1774
1775    FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1776    if (FreeElem == UINT32_MAX) {
1777       dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1778                      "Group 0xffff in Public Dict is full");
1779       return (gdcmElValue*)0;
1780    }
1781    NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1782                                 VR, "GDCM", NewTagName);
1783    NewElVal = new gdcmElValue(NewEntry);
1784    PubElValSet.Add(NewElVal);
1785    return NewElVal;
1786 }
1787
1788 /**
1789  * \ingroup gdcmHeader
1790  * \brief   Loads the element values of all the elements present in the
1791  *          public tag based hash table.
1792  */
1793 void gdcmHeader::LoadElements(void) {
1794    rewind(fp);
1795    
1796    // We don't use any longer the HashTable, since a lot a stuff is missing
1797    // when SeQuences were encountered 
1798    //  
1799    //TagElValueHT ht = PubElValSet.GetTagHt();
1800    //for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1801    //     LoadElementValue(tag->second);
1802    //}
1803    
1804      for (ListTag::iterator i = GetListElem().begin();  
1805            i != GetListElem().end();
1806            ++i){
1807         LoadElementValue(*i);   
1808      }    
1809     
1810    rewind(fp);
1811
1812    // Load 'non string' values   
1813    std::string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);   
1814    if( PhotometricInterpretation == "PALETTE COLOR " ){ 
1815       LoadElementVoidArea(0x0028,0x1200);  // gray LUT   
1816       LoadElementVoidArea(0x0028,0x1201);  // R    LUT
1817       LoadElementVoidArea(0x0028,0x1202);  // G    LUT
1818       LoadElementVoidArea(0x0028,0x1203);  // B    LUT
1819       
1820       LoadElementVoidArea(0x0028,0x1221);  // Segmented Red   Palette Color LUT Data
1821       LoadElementVoidArea(0x0028,0x1222);  // Segmented Green Palette Color LUT Data
1822       LoadElementVoidArea(0x0028,0x1223);  // Segmented Blue  Palette Color LUT Data
1823    }
1824
1825    // --------------------------------------------------------------
1826    // Special Patch to allow gdcm to read ACR-LibIDO formated images
1827    //
1828    // if recognition code tells us we deal with a LibIDO image
1829    // we switch lineNumber and columnNumber
1830    //
1831    std::string RecCode; 
1832    RecCode = GetPubElValByNumber(0x0008, 0x0010);
1833    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1834        RecCode == "CANRME_AILIBOD1_1." ) {
1835          filetype = ACR_LIBIDO; 
1836          std::string rows    = GetPubElValByNumber(0x0028, 0x0010);
1837          std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1838          SetPubElValByNumber(columns, 0x0028, 0x0010);
1839          SetPubElValByNumber(rows   , 0x0028, 0x0011);
1840    }
1841    // ----------------- End of Special Patch ----------------
1842 }
1843
1844 /**
1845   * \ingroup gdcmHeader
1846   * \brief
1847   * @return
1848   */ 
1849 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1850    PubElValSet.Print(os);
1851 }
1852
1853 /**
1854   * \ingroup gdcmHeader
1855   * \brief 
1856   * @return
1857   */  
1858 void gdcmHeader::PrintPubDict(std::ostream & os) {
1859    RefPubDict->Print(os);
1860 }
1861
1862 /**
1863   * \ingroup gdcmHeader
1864   * \brief
1865   * @return integer, acts as a Boolean
1866   */ 
1867 int gdcmHeader::Write(FILE * fp, FileType type) {
1868
1869    // TODO : move the following lines (and a lot of others, to be written)
1870    // to a future function CheckAndCorrectHeader
1871
1872    if (type == ImplicitVR) {
1873       std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
1874       ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
1875       
1876       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1877       //      values with a VR of UI shall be padded with a single trailing null
1878       //      Dans le cas suivant on doit pader manuellement avec un 0
1879       
1880       PubElValSet.SetElValueLengthByNumber(18, 0x0002, 0x0010);
1881    } 
1882
1883    if (type == ExplicitVR) {
1884       std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
1885       ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
1886       
1887       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1888       //      values with a VR of UI shall be padded with a single trailing null
1889       //      Dans le cas suivant on doit pader manuellement avec un 0
1890       
1891       PubElValSet.SetElValueLengthByNumber(20, 0x0002, 0x0010);
1892    }
1893
1894    return PubElValSet.Write(fp, type);
1895 }
1896
1897 //
1898 // ------------------------ 'non string' elements related functions
1899 //
1900
1901 /**
1902  * \ingroup       gdcmHeader
1903  * \brief         Loads (from disk) the element content 
1904  *                when a string is not suitable
1905  */
1906 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1907    gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1908    if ( !Element )
1909       return NULL;
1910    size_t o =(size_t)Element->GetOffset();
1911    fseek(fp, o, SEEK_SET);
1912    int l=Element->GetLength();
1913    void * a = malloc(l);
1914    if(!a) {
1915         std::cout << "Big Broblem (LoadElementVoidArea, malloc) " 
1916                   << std::hex << Group << " " << Elem << std::endl;
1917         return NULL;
1918    }  
1919    /* int res = */ PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1920    // TODO check the result 
1921    size_t l2 = fread(a, 1, l ,fp);
1922    if(l != l2) {
1923         std::cout << "Big Broblem (LoadElementVoidArea, fread) " 
1924                   << std::hex << Group << " " << Elem << std::endl;
1925         free(a);
1926         return NULL;
1927    }
1928    return a;  
1929 }
1930
1931 /**
1932  * \ingroup gdcmHeader
1933  * \brief   Gets (from Header) the offset  of a 'non string' element value 
1934  * \        (LoadElementValue has already be executed)
1935  * @param   Group
1936  * @param   Elem
1937  * @return File Offset of the Element Value 
1938  */
1939  size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1940    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1941    if (!elValue) {
1942       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1943                       "failed to Locate gdcmElValue");
1944       return (size_t)0;
1945    }
1946    return elValue->GetOffset();
1947 }
1948
1949 /**
1950  * \ingroup gdcmHeader
1951 * \brief   Gets (from Header) a 'non string' element value 
1952  * \        (LoadElementValue has already be executed)  
1953  * @param   Group
1954  * @param   Elem
1955  * @return Pointer to the 'non string' area
1956  
1957  */
1958  void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1959    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1960    if (!elValue) {
1961       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1962                   "failed to Locate gdcmElValue");
1963       return (NULL);
1964    }
1965    return elValue->GetVoidArea();
1966 }
1967
1968
1969 //
1970 // =============================================================================
1971 //   Heuristics based accessors
1972 //==============================================================================
1973 //
1974
1975 // TODO : move to an other file.
1976
1977
1978 /**
1979  * \ingroup gdcmHeader
1980  * \brief   Retrieve the number of columns of image.
1981  * @return  The encountered size when found, 0 by default.
1982  */
1983 int gdcmHeader::GetXSize(void) {
1984    // We cannot check for "Columns" because the "Columns" tag is present
1985    // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1986    std::string StrSize = GetPubElValByNumber(0x0028,0x0011);
1987    if (StrSize == GDCM_UNFOUND)
1988       return 0;
1989    return atoi(StrSize.c_str());
1990 }
1991
1992 /**
1993  * \ingroup gdcmHeader
1994  * \brief   Retrieve the number of lines of image.
1995  * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1996  * @return  The encountered size when found, 1 by default.
1997  */
1998 int gdcmHeader::GetYSize(void) {
1999    // We cannot check for "Rows" because the "Rows" tag is present
2000    // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
2001    std::string StrSize = GetPubElValByNumber(0x0028,0x0010);
2002    if (StrSize != GDCM_UNFOUND)
2003       return atoi(StrSize.c_str());
2004    if ( IsDicomV3() )
2005       return 0;
2006    else
2007       // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
2008       // hence be a signal (1d image). So we default to 1:
2009       return 1;
2010 }
2011
2012 /**
2013  * \ingroup gdcmHeader
2014  * \brief   Retrieve the number of planes of volume or the number
2015  *          of frames of a multiframe.
2016  * \warning When present we consider the "Number of Frames" as the third
2017  *          dimension. When absent we consider the third dimension as
2018  *          being the "Planes" tag content.
2019  * @return  The encountered size when found, 1 by default.
2020  */
2021 int gdcmHeader::GetZSize(void) {
2022    // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
2023    // as the third dimension.
2024    std::string StrSize = GetPubElValByNumber(0x0028,0x0008);
2025    if (StrSize != GDCM_UNFOUND)
2026       return atoi(StrSize.c_str());
2027
2028    // We then consider the "Planes" entry as the third dimension [we
2029    // cannot retrieve by name since "Planes tag is present both in
2030    // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary]. 
2031    StrSize = GetPubElValByNumber(0x0028,0x0012);
2032    if (StrSize != GDCM_UNFOUND)
2033       return atoi(StrSize.c_str());
2034    return 1;
2035 }
2036
2037 /**
2038  * \ingroup gdcmHeader
2039  * \brief   Retrieve the number of Bits Stored
2040  *          (as opposite to number of Bits Allocated)
2041  * 
2042  * @return  The encountered number of Bits Stored, 0 by default.
2043  */
2044 int gdcmHeader::GetBitsStored(void) { 
2045    std::string StrSize = GetPubElValByNumber(0x0028,0x0101);
2046    if (StrSize == GDCM_UNFOUND)
2047       return 1;
2048    return atoi(StrSize.c_str());
2049 }
2050
2051 /**
2052  * \ingroup gdcmHeader
2053  * \brief   Retrieve the number of Bits Allocated
2054  *          (8, 12 -compacted ACR-NEMA files, 16, ...)
2055  * 
2056  * @return  The encountered number of Bits Allocated, 0 by default.
2057  */
2058 int gdcmHeader::GetBitsAllocated(void) { 
2059    std::string StrSize = GetPubElValByNumber(0x0028,0x0100);
2060    if (StrSize == GDCM_UNFOUND)
2061       return 1;
2062    return atoi(StrSize.c_str());
2063 }
2064
2065 /**
2066  * \ingroup gdcmHeader
2067  * \brief   Retrieve the number of Samples Per Pixel
2068  *          (1 : gray level, 3 : RGB -1 or 3 Planes-)
2069  * 
2070  * @return  The encountered number of Samples Per Pixel, 1 by default.
2071  */
2072 int gdcmHeader::GetSamplesPerPixel(void) { 
2073    std::string StrSize = GetPubElValByNumber(0x0028,0x0002);
2074    if (StrSize == GDCM_UNFOUND)
2075       return 1; // Well, it's supposed to be mandatory ...
2076    return atoi(StrSize.c_str());
2077 }
2078
2079 /**
2080  * \ingroup gdcmHeader
2081  * \brief   Retrieve the Planar Configuration for RGB images
2082  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
2083  * 
2084  * @return  The encountered Planar Configuration, 0 by default.
2085  */
2086 int gdcmHeader::GetPlanarConfiguration(void) { 
2087    std::string StrSize = GetPubElValByNumber(0x0028,0x0006);
2088    if (StrSize == GDCM_UNFOUND)
2089       return 0;
2090    return atoi(StrSize.c_str());
2091 }
2092
2093 /**
2094  * \ingroup gdcmHeader
2095  * \brief   Return the size (in bytes) of a single pixel of data.
2096  * @return  The size in bytes of a single pixel of data.
2097  *
2098  */
2099 int gdcmHeader::GetPixelSize(void) {
2100    std::string PixelType = GetPixelType();
2101    if (PixelType == "8U"  || PixelType == "8S")
2102       return 1;
2103    if (PixelType == "16U" || PixelType == "16S")
2104       return 2;
2105    if (PixelType == "32U" || PixelType == "32S")
2106       return 4;
2107    dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
2108    return 0;
2109 }
2110
2111 /**
2112  * \ingroup gdcmHeader
2113  * \brief   Build the Pixel Type of the image.
2114  *          Possible values are:
2115  *          - 8U  unsigned  8 bit,
2116  *          - 8S    signed  8 bit,
2117  *          - 16U unsigned 16 bit,
2118  *          - 16S   signed 16 bit,
2119  *          - 32U unsigned 32 bit,
2120  *          - 32S   signed 32 bit,
2121  * \warning 12 bit images appear as 16 bit.
2122  * \        24 bit images appear as 8 bit
2123  * @return  
2124  */
2125 std::string gdcmHeader::GetPixelType(void) {
2126    std::string BitsAlloc;
2127    BitsAlloc = GetElValByName("Bits Allocated");
2128    if (BitsAlloc == GDCM_UNFOUND) {
2129       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
2130       BitsAlloc = std::string("16");
2131    }
2132    if (BitsAlloc == "12")            // It will be unpacked
2133       BitsAlloc = std::string("16");
2134    else if (BitsAlloc == "24")       // (in order no to be messed up
2135       BitsAlloc = std::string("8");  // by old RGB images)
2136      
2137    std::string Signed;
2138    Signed = GetElValByName("Pixel Representation");
2139    if (Signed == GDCM_UNFOUND) {
2140       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
2141       BitsAlloc = std::string("0");
2142    }
2143    if (Signed == "0")
2144       Signed = std::string("U");
2145    else
2146
2147 std::cout << "GetPixelType : " << BitsAlloc + Signed << std::endl;
2148       Signed = std::string("S");
2149
2150    return( BitsAlloc + Signed);
2151 }
2152
2153 /**
2154   * \ingroup gdcmHeader
2155   * \brief gets the info from 0002,0010 : Transfert Syntax
2156   * \           else 1.
2157   * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
2158   */
2159 std::string gdcmHeader::GetTransferSyntaxName(void) { 
2160    std::string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
2161    if (TransfertSyntax == GDCM_UNFOUND) {
2162       dbg.Verbose(0, "gdcmHeader::GetTransferSyntaxName: unfound Transfert Syntax (0002,0010)");
2163       return "Uncompressed ACR-NEMA";
2164    }
2165    // we do it only when we need it
2166    gdcmTS * ts = gdcmGlobal::GetTS();
2167    std::string tsName=ts->GetValue(TransfertSyntax);
2168    //delete ts; // Seg Fault when deleted ?!
2169    return tsName;
2170 }
2171
2172 // -------------------------------- Lookup Table related functions ------------
2173
2174 /**
2175   * \ingroup gdcmHeader
2176   * \brief tells us if LUT are used
2177   * \warning Right now, Segmented xxx Palette Color Lookup Table Data
2178   * \        are NOT considered as LUT, since nobody knows
2179   *\         how to deal with them
2180   * @return int acts as a Boolean 
2181   */
2182   
2183 int gdcmHeader::HasLUT(void) {
2184
2185    // Check the presence of the LUT Descriptors 
2186    if (GetPubElValByNumber(0x0028,0x1101) == GDCM_UNFOUND)
2187       return 0;
2188    // LutDescriptorGreen 
2189    if (GetPubElValByNumber(0x0028,0x1102) == GDCM_UNFOUND)
2190       return 0;
2191    // LutDescriptorBlue 
2192    if (GetPubElValByNumber(0x0028,0x1103) == GDCM_UNFOUND)
2193       return 0;
2194    //  It is not enough
2195    // we check also 
2196    if (GetPubElValByNumber(0x0028,0x1201) == GDCM_UNFOUND)
2197       return 0;  
2198    if (GetPubElValByNumber(0x0028,0x1202) == GDCM_UNFOUND)
2199       return 0;
2200    if (GetPubElValByNumber(0x0028,0x1203) == GDCM_UNFOUND)
2201       return 0;   
2202    return 1;
2203 }
2204
2205 /**
2206   * \ingroup gdcmHeader
2207   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2208   * \           else 0
2209   * @return Lookup Table nBit 
2210   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ] 
2211   */
2212   
2213 int gdcmHeader::GetLUTNbits(void) {
2214    std::vector<std::string> tokens;
2215    //int LutLength;
2216    //int LutDepth;
2217    int LutNbits;
2218    //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2219    // Consistency already checked in GetLUTLength
2220    std::string LutDescription = GetPubElValByNumber(0x0028,0x1101);
2221    if (LutDescription == GDCM_UNFOUND)
2222       return 0;
2223    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2224    Tokenize (LutDescription, tokens, "\\");
2225    //LutLength=atoi(tokens[0].c_str());
2226    //LutDepth=atoi(tokens[1].c_str());
2227    LutNbits=atoi(tokens[2].c_str());
2228    tokens.clear();
2229    return LutNbits;
2230 }
2231
2232 /**
2233   * \ingroup gdcmHeader
2234   * \brief builts Red/Green/Blue/Alpha LUT from Header
2235   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2236   * \        and (0028,1101),(0028,1102),(0028,1102)  
2237   * \          - xxx Palette Color Lookup Table Descriptor - are found
2238   * \        and (0028,1201),(0028,1202),(0028,1202) 
2239   * \          - xxx Palette Color Lookup Table Data - are found 
2240   * \warning does NOT deal with :
2241   * \ 0028 1100 Gray Lookup Table Descriptor (Retired)
2242   * \ 0028 1221 Segmented Red Palette Color Lookup Table Data
2243   * \ 0028 1222 Segmented Green Palette Color Lookup Table Data
2244   * \ 0028 1223 Segmented Blue Palette Color Lookup Table Data 
2245   * \ no known Dicom reader deails with them :-(
2246   * @return Lookup Table RGBA
2247   */ 
2248   
2249 unsigned char * gdcmHeader::GetLUTRGBA(void) {
2250 // Not so easy : see 
2251 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
2252 // and  OT-PAL-8-face.dcm
2253
2254 //  if Photometric Interpretation # PALETTE COLOR, no LUT to be done
2255                  
2256    if (gdcmHeader::GetPubElValByNumber(0x0028,0x0004) != "PALETTE COLOR ") {
2257         return NULL;
2258    }  
2259
2260    int lengthR, debR, nbitsR;
2261    int lengthG, debG, nbitsG;
2262    int lengthB, debB, nbitsB;
2263    
2264 // Get info from Lut Descriptors
2265 // (the 3 LUT descriptors may be different)    
2266    
2267    std::string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
2268    if (LutDescriptionR == GDCM_UNFOUND)
2269       return NULL;
2270    std::string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
2271    if (LutDescriptionG == GDCM_UNFOUND)
2272       return NULL;   
2273    std::string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
2274    if (LutDescriptionB == GDCM_UNFOUND)
2275       return NULL;
2276       
2277    std::vector<std::string> tokens;
2278       
2279    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2280    Tokenize (LutDescriptionR, tokens, "\\");
2281    lengthR=atoi(tokens[0].c_str()); // Red LUT length in Bytes
2282    debR   =atoi(tokens[1].c_str()); // subscript of the first Lut Value
2283    nbitsR =atoi(tokens[2].c_str()); // Lut item size (in Bits)
2284    tokens.clear();
2285    
2286    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2287    Tokenize (LutDescriptionG, tokens, "\\");
2288    lengthG=atoi(tokens[0].c_str()); // Green LUT length in Bytes
2289    debG   =atoi(tokens[1].c_str());
2290    nbitsG =atoi(tokens[2].c_str());
2291    tokens.clear();  
2292    
2293    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2294    Tokenize (LutDescriptionB, tokens, "\\");
2295    lengthB=atoi(tokens[0].c_str()); // Blue LUT length in Bytes
2296    debB   =atoi(tokens[1].c_str());
2297    nbitsB =atoi(tokens[2].c_str());
2298    tokens.clear();
2299  
2300 // Load LUTs into memory, (as they were stored on disk)
2301    
2302    unsigned char *lutR =(unsigned char *)
2303                                    GetPubElValVoidAreaByNumber(0x0028,0x1201);
2304    unsigned char *lutG =(unsigned char *)
2305                                    GetPubElValVoidAreaByNumber(0x0028,0x1202);
2306    unsigned char *lutB =(unsigned char *)
2307                                    GetPubElValVoidAreaByNumber(0x0028,0x1203); 
2308    
2309    if (!lutR || !lutG || !lutB ) {
2310         return NULL;
2311    } 
2312  // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT 
2313    
2314   unsigned char *LUTRGBA = (unsigned char *)calloc(1024,1); // 256 * 4 (R, G, B, Alpha) 
2315   if (!LUTRGBA) {
2316      return NULL;
2317   }
2318   memset(LUTRGBA, 0, 1024);
2319         // Bits Allocated
2320    int nb;
2321    std::string str_nb = GetPubElValByNumber(0x0028,0x0100);
2322    if (str_nb == GDCM_UNFOUND ) {
2323       nb = 16;
2324    } else {
2325       nb = atoi(str_nb.c_str() );
2326    }  
2327   int mult;
2328   
2329   if (nbitsR==16 && nb==8) // when LUT item size is different than pixel size
2330      mult=2;               // high byte must be = low byte 
2331   else                     // See PS 3.3-2003 C.11.1.1.2 p 619
2332      mult=1; 
2333  
2334  
2335             // if we get a black image, let's just remove the '+1'
2336             // from 'i*mult+1' and check again 
2337             // if it works, we shall have to check the 3 Palettes
2338             // to see which byte is ==0 (first one, or second one)
2339             // and fix the code
2340             // We give up the checking to avoid some overhead 
2341             
2342   unsigned char *a;      
2343   int i;
2344   a= LUTRGBA+0;
2345   for(i=0;i<lengthR;i++) {
2346      *a = lutR[i*mult+1]; 
2347      a+=4;       
2348   }        
2349   a= LUTRGBA+1;
2350   for(i=0;i<lengthG;i++) {
2351      *a = lutG[i*mult+1]; 
2352      a+=4;       
2353   }  
2354   a= LUTRGBA+2;
2355   for(i=0;i<lengthB;i++) {
2356      *a = lutB[i*mult+1]; 
2357      a+=4;       
2358   }  
2359   a= LUTRGBA+3;
2360   for(i=0;i<256;i++) {
2361      *a = 1; // Alpha component
2362      a+=4; 
2363   } 
2364       
2365 //How to free the now useless LUTs?
2366 //
2367 //free(LutR); free(LutB); free(LutG);
2368
2369   return(LUTRGBA);   
2370
2371