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