]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
7cb2cad0fad356999bfcf623eec6399ea0256169
[gdcm.git] / src / gdcmHeader.cxx
1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.103 2003/10/23 12:08:32 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    ElVal->SetLength(FoundLength);
651 }
652
653 /**
654  * \ingroup gdcmHeader
655  * \brief   
656  *
657  * @return 
658  */
659  guint32 gdcmHeader::FindLengthOB(void) {
660    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
661    guint16 g;
662    guint16 n; 
663    long PositionOnEntry = ftell(fp);
664    bool FoundSequenceDelimiter = false;
665    guint32 TotalLength = 0;
666    guint32 ItemLength;
667
668    while ( ! FoundSequenceDelimiter) {
669       g = ReadInt16();
670       n = ReadInt16();   
671       if (errno == 1)
672          return 0;
673       TotalLength += 4;  // We even have to decount the group and element 
674      
675       if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ {
676          char msg[100]; // for sprintf. Sorry
677          sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
678          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg); 
679          errno = 1;
680          return 0;
681       }
682       if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header  */ 
683          FoundSequenceDelimiter = true;
684       else if ( n != 0xe000 ){
685          char msg[100];  // for sprintf. Sorry
686          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
687                       n, g,n);
688          dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
689          errno = 1;
690          return 0;
691       }
692       ItemLength = ReadInt32();
693       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
694                                       // the ItemLength with ReadInt32                                     
695       SkipBytes(ItemLength);
696    }
697    fseek(fp, PositionOnEntry, SEEK_SET);
698    return TotalLength;
699 }
700
701 /**
702  * \ingroup gdcmHeader
703  * \brief   
704  *
705  * @return 
706  */
707  void gdcmHeader::FindLength (gdcmElValue * ElVal) {
708    guint16 element = ElVal->GetElement();
709    guint16 group   = ElVal->GetGroup();
710    std::string  vr = ElVal->GetVR();
711    guint16 length16;
712    if( (element == 0x0010) && (group == 0x7fe0) ) {
713       dbg.SetDebug(0);
714       dbg.Verbose(2, "gdcmHeader::FindLength: ",
715                      "we reached 7fe0 0010");
716    }   
717    
718    if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
719       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
720       
721          // The following reserved two bytes (see PS 3.5-2001, section
722          // 7.1.2 Data element structure with explicit vr p27) must be
723          // skipped before proceeding on reading the length on 4 bytes.
724          fseek(fp, 2L, SEEK_CUR);
725
726          guint32 length32 = ReadInt32();
727
728          if ( (vr == "OB") && (length32 == 0xffffffff) ) {
729             ElVal->SetLength(FindLengthOB());
730             return;
731          }
732          FixFoundLength(ElVal, length32);        
733          return;
734       }
735
736       // Length is encoded on 2 bytes.
737       length16 = ReadInt16();
738       
739       // We can tell the current file is encoded in big endian (like
740       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
741       // and it's value is the one of the encoding of a big endian file.
742       // In order to deal with such big endian encoded files, we have
743       // (at least) two strategies:
744       // * when we load the "Transfer Syntax" tag with value of big endian
745       //   encoding, we raise the proper flags. Then we wait for the end
746       //   of the META group (0x0002) among which is "Transfer Syntax",
747       //   before switching the swap code to big endian. We have to postpone
748       //   the switching of the swap code since the META group is fully encoded
749       //   in little endian, and big endian coding only starts at the next
750       //   group. The corresponding code can be hard to analyse and adds
751       //   many additional unnecessary tests for regular tags.
752       // * the second strategy consists in waiting for trouble, that shall
753       //   appear when we find the first group with big endian encoding. This
754       //   is easy to detect since the length of a "Group Length" tag (the
755       //   ones with zero as element number) has to be of 4 (0x0004). When we
756       //   encouter 1024 (0x0400) chances are the encoding changed and we
757       //   found a group with big endian encoding.
758       // We shall use this second strategy. In order to make sure that we
759       // can interpret the presence of an apparently big endian encoded
760       // length of a "Group Length" without committing a big mistake, we
761       // add an additional check: we look in the already parsed elements
762       // for the presence of a "Transfer Syntax" whose value has to be "big
763       // endian encoding". When this is the case, chances are we have got our
764       // hands on a big endian encoded file: we switch the swap code to
765       // big endian and proceed...
766       if ( (element  == 0x0000) && (length16 == 0x0400) ) {
767          if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
768             dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
769             errno = 1;
770             return;
771          }
772          length16 = 4;
773          SwitchSwapToBigEndian();
774          // Restore the unproperly loaded values i.e. the group, the element
775          // and the dictionary entry depending on them.
776          guint16 CorrectGroup   = SwapShort(ElVal->GetGroup());
777          guint16 CorrectElem    = SwapShort(ElVal->GetElement());
778          gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
779                                                        CorrectElem);
780          if (!NewTag) {
781             // This correct tag is not in the dictionary. Create a new one.
782             NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
783          }
784          // FIXME this can create a memory leaks on the old entry that be
785          // left unreferenced.
786          ElVal->SetDictEntry(NewTag);
787       }
788        
789       // Heuristic: well some files are really ill-formed.
790       if ( length16 == 0xffff) {
791          length16 = 0;
792          //dbg.Verbose(0, "gdcmHeader::FindLength",
793          //            "Erroneous element length fixed.");
794          // Actually, length= 0xffff means that we deal with
795          // Unknown Sequence Length 
796       }
797
798       FixFoundLength(ElVal, (guint32)length16);
799       return;
800    }
801
802    // Either implicit VR or a non DICOM conformal (see not below) explicit
803    // VR that ommited the VR of (at least) this element. Farts happen.
804    // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
805    // on Data elements "Implicit and Explicit VR Data Elements shall
806    // not coexist in a Data Set and Data Sets nested within it".]
807    // Length is on 4 bytes.
808    FixFoundLength(ElVal, ReadInt32());
809 }
810
811 /**
812  * \ingroup gdcmHeader
813  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
814  *          processor order.
815  *
816  * @return  The suggested integer.
817  */
818 guint32 gdcmHeader::SwapLong(guint32 a) {
819    switch (sw) {
820    case    0 :
821       break;
822    case 4321 :
823       a=(   ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000)    | 
824             ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
825       break;
826    
827    case 3412 :
828       a=(   ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
829       break;
830    
831    case 2143 :
832       a=(    ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
833       break;
834    default :
835       dbg.Error(" gdcmHeader::SwapLong : unset swap code");
836       a=0;
837    }
838    return(a);
839 }
840
841 /**
842  * \ingroup gdcmHeader
843  * \brief   Swaps the bytes so they agree with the processor order
844  * @return  The properly swaped 16 bits integer.
845  */
846 guint16 gdcmHeader::SwapShort(guint16 a) {
847    if ( (sw==4321)  || (sw==2143) )
848       a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
849    return (a);
850 }
851
852 /**
853  * \ingroup gdcmHeader
854  * \brief   
855  *
856  * @return 
857  */
858  void gdcmHeader::SkipBytes(guint32 NBytes) {
859    //FIXME don't dump the returned value
860    (void)fseek(fp, (long)NBytes, SEEK_CUR);
861 }
862
863 /**
864  * \ingroup gdcmHeader
865  * \brief   
866  * @param ElVal 
867  * @return 
868  */
869  void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
870    SkipBytes(ElVal->GetLength());
871 }
872
873 /**
874  * \ingroup gdcmHeader
875  * \brief   
876  * @param NewSize
877  * @return 
878  */
879  void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
880    if (NewSize < 0)
881       return;
882    if ((guint32)NewSize >= (guint32)0xffffffff) {
883       MaxSizeLoadElementValue = 0xffffffff;
884       return;
885    }
886    MaxSizeLoadElementValue = NewSize;
887 }
888
889 /**
890  * \ingroup       gdcmHeader
891  * \brief         Loads the element content if it's length is not bigger
892  *                than the value specified with
893  *                gdcmHeader::SetMaxSizeLoadElementValue()
894  */
895 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
896    size_t item_read;
897    guint16 group  = ElVal->GetGroup();
898    std::string  vr= ElVal->GetVR();
899    guint32 length = ElVal->GetLength();
900    bool SkipLoad  = false;
901
902    fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
903    
904    // FIXME Sequences not treated yet !
905    //
906    // Ne faudrait-il pas au contraire trouver immediatement
907    // une maniere 'propre' de traiter les sequences (vr = SQ)
908    // car commencer par les ignorer risque de conduire a qq chose
909    // qui pourrait ne pas etre generalisable
910    // Well, I'm expecting your code !!!
911     
912    if( vr == "SQ" )
913       SkipLoad = true;
914
915    // Heuristic : a sequence "contains" a set of tags (called items). It looks
916    // like the last tag of a sequence (the one that terminates the sequence)
917    // has a group of 0xfffe (with a dummy length).
918    // Well ... 
919    // Actually (fffe e000) tells us an Element is beginning
920    //          (fffe e00d) tells us an Element just ended
921    //          (fffe e0dd) tells us the current SEQuence just ended
922   
923    if( group == 0xfffe )
924       SkipLoad = true;
925
926    if ( SkipLoad ) {
927       ElVal->SetLength(0);
928       ElVal->SetValue("gdcm::Skipped");
929       return;
930    }
931
932    // When the length is zero things are easy:
933    if ( length == 0 ) {
934       ElVal->SetValue("");
935       return;
936    }
937
938    // The elements whose length is bigger than the specified upper bound
939    // are not loaded. Instead we leave a short notice of the offset of
940    // the element content and it's length.
941    if (length > MaxSizeLoadElementValue) {
942       std::ostringstream s;
943       s << "gdcm::NotLoaded.";
944       s << " Address:" << (long)ElVal->GetOffset();
945       s << " Length:"  << ElVal->GetLength();
946       ElVal->SetValue(s.str());
947       return;
948    }
949    
950    // When an integer is expected, read and convert the following two or
951    // four bytes properly i.e. as an integer as opposed to a string.
952         
953         // pour les elements de Value Multiplicity > 1
954         // on aura en fait une serie d'entiers  
955         // on devrait pouvoir faire + compact (?)
956                 
957    if ( IsAnInteger(ElVal) ) {
958       guint32 NewInt;
959       std::ostringstream s;
960       int nbInt;
961       if (vr == "US" || vr == "SS") {
962          nbInt = length / 2;
963          NewInt = ReadInt16();
964          s << NewInt;
965          if (nbInt > 1) {
966             for (int i=1; i < nbInt; i++) {
967                s << '\\';
968                NewInt = ReadInt16();
969                s << NewInt;
970             }
971          }
972                         
973       } else if (vr == "UL" || vr == "SL") {
974          nbInt = length / 4;
975          NewInt = ReadInt32();
976          s << NewInt;
977          if (nbInt > 1) {
978             for (int i=1; i < nbInt; i++) {
979                s << '\\';
980                NewInt = ReadInt32();
981                s << NewInt;
982             }
983          }
984       }                                 
985       ElVal->SetValue(s.str());
986       return;   
987    }
988    
989    // We need an additional byte for storing \0 that is not on disk
990    char* NewValue = (char*)malloc(length+1);
991    if( !NewValue) {
992       dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
993       return;
994    }
995    NewValue[length]= 0;
996    
997    item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
998    if ( item_read != 1 ) {
999       free(NewValue);
1000       dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
1001       ElVal->SetValue("gdcm::UnRead");
1002       return;
1003    }
1004    ElVal->SetValue(NewValue);
1005    free(NewValue);
1006 }
1007
1008 /**
1009  * \ingroup       gdcmHeader
1010  * \brief         Loads the element while preserving the current
1011  *                underlying file position indicator as opposed to
1012  *                to LoadElementValue that modifies it.
1013  * @param ElVal   Element whose value shall be loaded. 
1014  * @return  
1015  */
1016 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
1017    long PositionOnEntry = ftell(fp);
1018    LoadElementValue(ElVal);
1019    fseek(fp, PositionOnEntry, SEEK_SET);
1020 }
1021
1022 /**
1023  * \ingroup gdcmHeader
1024  * \brief Reads a supposed to be 16 Bits integer
1025  * \     (swaps it depending on processor endianity) 
1026  *
1027  * @return integer acts as a boolean
1028  */
1029 guint16 gdcmHeader::ReadInt16(void) {
1030    guint16 g;
1031    size_t item_read;
1032    item_read = fread (&g, (size_t)2,(size_t)1, fp);
1033    if ( item_read != 1 ) {
1034       // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
1035       // if(feof(fp)) 
1036       //    dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
1037       if(ferror(fp)) 
1038          dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
1039       errno = 1;
1040       return 0;
1041    }
1042    errno = 0;
1043    g = SwapShort(g);
1044    return g;
1045 }
1046
1047 /**
1048  * \ingroup gdcmHeader
1049  * \brief  Reads a supposed to be 32 Bits integer
1050  * \       (swaps it depending on processor endianity)  
1051  *
1052  * @return 
1053  */
1054 guint32 gdcmHeader::ReadInt32(void) {
1055    guint32 g;
1056    size_t item_read;
1057    item_read = fread (&g, (size_t)4,(size_t)1, fp);
1058    if ( item_read != 1 ) { 
1059       //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
1060       //if(feof(fp)) 
1061       //   dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
1062      if(ferror(fp)) 
1063          dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");   
1064       errno = 1;
1065       return 0;
1066    }
1067    errno = 0;   
1068    g = SwapLong(g);
1069    return g;
1070 }
1071
1072 /**
1073  * \ingroup gdcmHeader
1074  * \brief   
1075  *
1076  * @return 
1077  */
1078  gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1079
1080    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1081    if (!elValue) {
1082       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1083                   "failed to Locate gdcmElValue");
1084       return (gdcmElValue*)0;
1085    }
1086    return elValue;
1087 }
1088
1089 /**
1090  * \ingroup gdcmHeader
1091  * \brief   Build a new Element Value from all the low level arguments. 
1092  *          Check for existence of dictionary entry, and build
1093  *          a default one when absent.
1094  * @param   Group group   of the underlying DictEntry
1095  * @param   Elem  element of the underlying DictEntry
1096  */
1097 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1098    // Find out if the tag we encountered is in the dictionaries:
1099    gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1100    if (!NewTag)
1101       NewTag = new gdcmDictEntry(Group, Elem);
1102
1103    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1104    if (!NewElVal) {
1105       dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1106                   "failed to allocate gdcmElValue");
1107       return (gdcmElValue*)0;
1108    }
1109    return NewElVal;
1110 }
1111
1112 /**
1113  * \ingroup gdcmHeader
1114  * \brief   TODO
1115  * @param   Value
1116  * @param   Group
1117  * @param   Elem
1118  * \return integer acts as a boolean
1119  */
1120 int gdcmHeader::ReplaceOrCreateByNumber(std::string Value, 
1121                                         guint16 Group, guint16 Elem ) {
1122
1123         // TODO : FIXME JPRx
1124         // curieux, non ?
1125         // on (je) cree une Elvalue ne contenant pas de valeur
1126         // on l'ajoute au ElValSet
1127         // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1128         // --> devrait pouvoir etre fait + simplement ???
1129    if (CheckIfExistByNumber(Group, Elem) == 0) {
1130       gdcmElValue* a =NewElValueByNumber(Group, Elem);
1131       if (a == NULL) 
1132          return 0;
1133       PubElValSet.Add(a);
1134    }   
1135    PubElValSet.SetElValueByNumber(Value, Group, Elem);
1136    return(1);
1137 }   
1138
1139
1140 /**
1141  * \ingroup gdcmHeader
1142  * \brief   Modify (or Creates if not found) an element
1143  * @param   Value new value
1144  * @param   Group
1145  * @param   Elem
1146  * \return integer acts as a boolean 
1147  * 
1148  */
1149 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1150
1151    gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1152    PubElValSet.Add(nvElValue);
1153    std::string v = Value;       
1154    PubElValSet.SetElValueByNumber(v, Group, Elem);
1155    return(1);
1156 }  
1157
1158
1159 /**
1160  * \ingroup gdcmHeader
1161  * \brief   Set a new value if the invoked element exists
1162  *          Seems to be useless !!!
1163  * @param   Value
1164  * @param   Group
1165  * @param   Elem
1166  * \return integer acts as a boolean 
1167  */
1168 int gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1169
1170    //gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1171    std::string v = Value;       
1172    PubElValSet.SetElValueByNumber(v, Group, Elem);
1173    return 1;
1174
1175
1176
1177 /**
1178  * \ingroup gdcmHeader
1179  * \brief   Checks if a given ElValue (group,number) 
1180  * \ exists in the Public ElValSet
1181  * @param   Group
1182  * @param   Elem
1183  * @return  integer acts as a boolean  
1184  */
1185  
1186 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1187    return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1188  }
1189   
1190 /**
1191  * \ingroup gdcmHeader
1192  * \brief   Build a new Element Value from all the low level arguments. 
1193  *          Check for existence of dictionary entry, and build
1194  *          a default one when absent.
1195  * @param   Name    Name of the underlying DictEntry
1196  */
1197 gdcmElValue* gdcmHeader::NewElValueByName(std::string Name) {
1198
1199    gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1200    if (!NewTag)
1201       NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1202
1203    gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1204    if (!NewElVal) {
1205       dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1206                   "failed to allocate gdcmElValue");
1207       return (gdcmElValue*)0;
1208    }
1209    return NewElVal;
1210 }  
1211
1212 /**
1213  * \ingroup gdcmHeader
1214  * \brief   Read the next tag but WITHOUT loading it's value
1215  * @return  On succes the newly created ElValue, NULL on failure.      
1216  */
1217 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1218   
1219    guint16 g,n;
1220    gdcmElValue * NewElVal;
1221    
1222    g = ReadInt16();
1223    n = ReadInt16();
1224       
1225    if (errno == 1)
1226       // We reached the EOF (or an error occured) and header parsing
1227       // has to be considered as finished.
1228       return (gdcmElValue *)0;
1229    
1230    NewElVal = NewElValueByNumber(g, n);
1231    FindVR(NewElVal);
1232    FindLength(NewElVal);
1233    if (errno == 1) {
1234       // Call it quits
1235       return (gdcmElValue *)0;
1236    }
1237    NewElVal->SetOffset(ftell(fp));  
1238    //if ( (g==0x7fe0) && (n==0x0010) ) 
1239    return NewElVal;
1240 }
1241
1242 /**
1243  * \ingroup gdcmHeader
1244  * \brief   Apply some heuristics to predict wether the considered 
1245  *          element value contains/represents an integer or not.
1246  * @param   ElVal The element value on which to apply the predicate.
1247  * @return  The result of the heuristical predicate.
1248  */
1249 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1250    guint16 element = ElVal->GetElement();
1251    std::string  vr = ElVal->GetVR();
1252    guint32 length  = ElVal->GetLength();
1253
1254    // When we have some semantics on the element we just read, and if we
1255    // a priori know we are dealing with an integer, then we shall be
1256    // able to swap it's element value properly.
1257    if ( element == 0 )  {  // This is the group length of the group
1258       if (length == 4)
1259          return true;
1260       else {
1261          dbg.Error("gdcmHeader::IsAnInteger",
1262             "Erroneous Group Length element length.");     
1263       }
1264    }
1265    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1266       return true;
1267    
1268    return false;
1269 }
1270
1271 /**
1272  * \ingroup gdcmHeader
1273  * \brief   Recover the offset (from the beginning of the file) of the pixels.
1274  */
1275 size_t gdcmHeader::GetPixelOffset(void) {
1276    // If this file complies with the norm we should encounter the
1277    // "Image Location" tag (0x0028,  0x0200). This tag contains the
1278    // the group that contains the pixel data (hence the "Pixel Data"
1279    // is found by indirection through the "Image Location").
1280    // Inside the group pointed by "Image Location" the searched element
1281    // is conventionally the element 0x0010 (when the norm is respected).
1282    // When the "Image Location" is absent we default to group 0x7fe0.
1283    guint16 grPixel;
1284    guint16 numPixel;
1285    std::string ImageLocation = GetPubElValByName("Image Location");
1286    if ( ImageLocation == GDCM_UNFOUND ) {
1287       grPixel = 0x7fe0;
1288    } else {
1289       grPixel = (guint16) atoi( ImageLocation.c_str() );
1290    }
1291    if (grPixel != 0x7fe0)
1292       // This is a kludge for old dirty Philips imager.
1293       numPixel = 0x1010;
1294    else
1295       numPixel = 0x0010;
1296          
1297    gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1298                                                               numPixel);
1299    if (PixelElement)
1300       return PixelElement->GetOffset();
1301    else
1302       return 0;
1303 }
1304
1305 /**
1306  * \ingroup gdcmHeader
1307  * \brief   Searches both the public and the shadow dictionary (when they
1308  *          exist) for the presence of the DictEntry with given
1309  *          group and element. The public dictionary has precedence on the
1310  *          shadow one.
1311  * @param   group   group of the searched DictEntry
1312  * @param   element element of the searched DictEntry
1313  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1314  */
1315 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1316                                                  guint16 element) {
1317    gdcmDictEntry * found = (gdcmDictEntry*)0;
1318    if (!RefPubDict && !RefShaDict) {
1319       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1320                      "we SHOULD have a default dictionary");
1321    }
1322    if (RefPubDict) {
1323       found = RefPubDict->GetTagByNumber(group, element);
1324       if (found)
1325          return found;
1326    }
1327    if (RefShaDict) {
1328       found = RefShaDict->GetTagByNumber(group, element);
1329       if (found)
1330          return found;
1331    }
1332    return found;
1333 }
1334
1335 /**
1336  * \ingroup gdcmHeader
1337  * \brief   Searches both the public and the shadow dictionary (when they
1338  *          exist) for the presence of the DictEntry with given name.
1339  *          The public dictionary has precedence on the shadow one.
1340  * @param   Name name of the searched DictEntry
1341  * @return  Corresponding DictEntry when it exists, NULL otherwise.
1342  */
1343 gdcmDictEntry * gdcmHeader::GetDictEntryByName(std::string Name) {
1344    gdcmDictEntry * found = (gdcmDictEntry*)0;
1345    if (!RefPubDict && !RefShaDict) {
1346       dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1347                      "we SHOULD have a default dictionary");
1348    }
1349    if (RefPubDict) {
1350       found = RefPubDict->GetTagByName(Name);
1351       if (found)
1352          return found;
1353    }
1354    if (RefShaDict) {
1355       found = RefShaDict->GetTagByName(Name);
1356       if (found)
1357          return found;
1358    }
1359    return found;
1360 }
1361
1362 /**
1363  * \ingroup gdcmHeader
1364  * \brief   Searches within the public dictionary for element value of
1365  *          a given tag.
1366  * @param   group Group of the researched tag.
1367  * @param   element Element of the researched tag.
1368  * @return  Corresponding element value when it exists, and the string
1369  *          GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1370  */
1371 std::string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1372    return PubElValSet.GetElValueByNumber(group, element);
1373 }
1374
1375 /**
1376  * \ingroup gdcmHeader
1377  * \brief   Searches within the public dictionary for element value
1378  *          representation of a given tag.
1379  *
1380  *          Obtaining the VR (Value Representation) might be needed by caller
1381  *          to convert the string typed content to caller's native type 
1382  *          (think of C++ vs Python). The VR is actually of a higher level
1383  *          of semantics than just the native C++ type.
1384  * @param   group Group of the researched tag.
1385  * @param   element Element of the researched tag.
1386  * @return  Corresponding element value representation when it exists,
1387  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1388  */
1389 std::string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1390    gdcmElValue* elem =  PubElValSet.GetElementByNumber(group, element);
1391    if ( !elem )
1392       return GDCM_UNFOUND;
1393    return elem->GetVR();
1394 }
1395
1396 /**
1397  * \ingroup gdcmHeader
1398  * \brief   Searches within the public dictionary for element value of
1399  *          a given tag.
1400  * @param   TagName name of the researched element.
1401  * @return  Corresponding element value when it exists, and the string
1402  *          GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1403  */
1404 std::string gdcmHeader::GetPubElValByName(std::string TagName) {
1405    return PubElValSet.GetElValueByName(TagName);
1406 }
1407
1408 /**
1409  * \ingroup gdcmHeader
1410  * \brief   Searches within the elements parsed with the public dictionary for
1411  *          the element value representation of a given tag.
1412  *
1413  *          Obtaining the VR (Value Representation) might be needed by caller
1414  *          to convert the string typed content to caller's native type 
1415  *          (think of C++ vs Python). The VR is actually of a higher level
1416  *          of semantics than just the native C++ type.
1417  * @param   TagName name of the researched element.
1418  * @return  Corresponding element value representation when it exists,
1419  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1420  */
1421 std::string gdcmHeader::GetPubElValRepByName(std::string TagName) {
1422    gdcmElValue* elem =  PubElValSet.GetElementByName(TagName);
1423    if ( !elem )
1424       return GDCM_UNFOUND;
1425    return elem->GetVR();
1426 }
1427
1428 /**
1429  * \ingroup gdcmHeader
1430  * \brief   Searches within elements parsed with the SHADOW dictionary 
1431  *          for the element value of a given tag.
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::GetShaElValByNumber(guint16 group, guint16 element) {
1438    return ShaElValSet.GetElValueByNumber(group, element);
1439 }
1440
1441 /**
1442  * \ingroup gdcmHeader
1443  * \brief   Searches within the elements parsed with the SHADOW dictionary
1444  *          for the element value representation of a given tag.
1445  *
1446  *          Obtaining the VR (Value Representation) might be needed by caller
1447  *          to convert the string typed content to caller's native type 
1448  *          (think of C++ vs Python). The VR is actually of a higher level
1449  *          of semantics than just the native C++ type.
1450  * @param   group Group of the researched tag.
1451  * @param   element Element of the researched tag.
1452  * @return  Corresponding element value representation when it exists,
1453  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1454  */
1455 std::string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1456    gdcmElValue* elem =  ShaElValSet.GetElementByNumber(group, element);
1457    if ( !elem )
1458       return GDCM_UNFOUND;
1459    return elem->GetVR();
1460 }
1461
1462 /**
1463  * \ingroup gdcmHeader
1464  * \brief   Searches within the elements parsed with the shadow dictionary
1465  *          for an element value of given tag.
1466  * @param   TagName name of the researched element.
1467  * @return  Corresponding element value when it exists, and the string
1468  *          GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1469  */
1470 std::string gdcmHeader::GetShaElValByName(std::string TagName) {
1471    return ShaElValSet.GetElValueByName(TagName);
1472 }
1473
1474 /**
1475  * \ingroup gdcmHeader
1476  * \brief   Searches within the elements parsed with the shadow dictionary for
1477  *          the element value representation of a given tag.
1478  *
1479  *          Obtaining the VR (Value Representation) might be needed by caller
1480  *          to convert the string typed content to caller's native type 
1481  *          (think of C++ vs Python). The VR is actually of a higher level
1482  *          of semantics than just the native C++ type.
1483  * @param   TagName name of the researched element.
1484  * @return  Corresponding element value representation when it exists,
1485  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1486  */
1487 std::string gdcmHeader::GetShaElValRepByName(std::string TagName) {
1488    gdcmElValue* elem =  ShaElValSet.GetElementByName(TagName);
1489    if ( !elem )
1490       return GDCM_UNFOUND;
1491    return elem->GetVR();
1492 }
1493
1494 /**
1495  * \ingroup gdcmHeader
1496  * \brief   Searches within elements parsed with the public dictionary 
1497  *          and then within the elements parsed with the shadow dictionary
1498  *          for the element value of a given tag.
1499  * @param   group Group of the researched tag.
1500  * @param   element Element of the researched tag.
1501  * @return  Corresponding element value representation when it exists,
1502  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1503  */
1504 std::string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1505    std::string pub = GetPubElValByNumber(group, element);
1506    if (pub.length())
1507       return pub;
1508    return GetShaElValByNumber(group, element);
1509 }
1510
1511 /**
1512  * \ingroup gdcmHeader
1513  * \brief   Searches within elements parsed with the public dictionary 
1514  *          and then within the elements parsed with the shadow dictionary
1515  *          for the element value representation of a given tag.
1516  *
1517  *          Obtaining the VR (Value Representation) might be needed by caller
1518  *          to convert the string typed content to caller's native type 
1519  *          (think of C++ vs Python). The VR is actually of a higher level
1520  *          of semantics than just the native C++ type.
1521  * @param   group Group of the researched tag.
1522  * @param   element Element of the researched tag.
1523  * @return  Corresponding element value representation when it exists,
1524  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1525  */
1526 std::string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1527    std::string pub = GetPubElValRepByNumber(group, element);
1528    if (pub.length())
1529       return pub;
1530    return GetShaElValRepByNumber(group, element);
1531 }
1532
1533 /**
1534  * \ingroup gdcmHeader
1535  * \brief   Searches within elements parsed with the public dictionary 
1536  *          and then within the elements parsed with the shadow dictionary
1537  *          for the element value of a given tag.
1538  * @param   TagName name of the researched element.
1539  * @return  Corresponding element value when it exists,
1540  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1541  */
1542 std::string gdcmHeader::GetElValByName(std::string TagName) {
1543    std::string pub = GetPubElValByName(TagName);
1544    if (pub.length())
1545       return pub;
1546    return GetShaElValByName(TagName);
1547 }
1548
1549 /**
1550  * \ingroup gdcmHeader
1551  * \brief   Searches within elements parsed with the public dictionary 
1552  *          and then within the elements parsed with the shadow dictionary
1553  *          for the element value representation of a given tag.
1554  *
1555  *          Obtaining the VR (Value Representation) might be needed by caller
1556  *          to convert the string typed content to caller's native type 
1557  *          (think of C++ vs Python). The VR is actually of a higher level
1558  *          of semantics than just the native C++ type.
1559  * @param   TagName name of the researched element.
1560  * @return  Corresponding element value representation when it exists,
1561  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1562  */
1563 std::string gdcmHeader::GetElValRepByName(std::string TagName) {
1564    std::string pub = GetPubElValRepByName(TagName);
1565    if (pub.length())
1566       return pub;
1567    return GetShaElValRepByName(TagName);
1568 }
1569
1570 /**
1571  * \ingroup gdcmHeader
1572  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1573  *          through it's (group, element) and modifies it's content with
1574  *          the given value.
1575  * @param   content new value to substitute with
1576  * @param   group   group of the ElVal to modify
1577  * @param   element element of the ElVal to modify
1578  */
1579 int gdcmHeader::SetPubElValByNumber(std::string content, guint16 group,
1580                                     guint16 element)
1581                                     
1582 //TODO  : homogeneiser les noms : SetPubElValByNumber   
1583 //                    qui appelle PubElValSet.SetElValueByNumber 
1584 //        pourquoi pas            SetPubElValueByNumber ??
1585 {
1586
1587    return (  PubElValSet.SetElValueByNumber (content, group, element) );
1588 }
1589
1590 /**
1591  * \ingroup gdcmHeader
1592  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1593  *          through tag name and modifies it's content with the given value.
1594  * @param   content new value to substitute with
1595  * @param   TagName name of the tag to be modified
1596  */
1597 int gdcmHeader::SetPubElValByName(std::string content, std::string TagName) {
1598    return (  PubElValSet.SetElValueByName (content, TagName) );
1599 }
1600
1601 /**
1602  * \ingroup gdcmHeader
1603  * \brief   Accesses an existing gdcmElValue in the PubElValSet of this instance
1604  *          through it's (group, element) and modifies it's length with
1605  *          the given value.
1606  * \warning Use with extreme caution.
1607  * @param   length new length to substitute with
1608  * @param   group   group of the ElVal to modify
1609  * @param   element element of the ElVal to modify
1610  * @return  1 on success, 0 otherwise.
1611  */
1612
1613 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1614                                     guint16 element) {
1615         return (  PubElValSet.SetElValueLengthByNumber (length, group, element) );
1616 }
1617
1618 /**
1619  * \ingroup gdcmHeader
1620  * \brief   Accesses an existing gdcmElValue in the ShaElValSet 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  * @return  1 on success, 0 otherwise.
1627  */
1628 int gdcmHeader::SetShaElValByNumber(std::string content,
1629                                     guint16 group, guint16 element) {
1630    return (  ShaElValSet.SetElValueByNumber (content, group, element) );
1631 }
1632
1633 /**
1634  * \ingroup gdcmHeader
1635  * \brief   Accesses an existing gdcmElValue in the ShaElValSet of this instance
1636  *          through tag name and modifies it's content with the given value.
1637  * @param   content new value to substitute with
1638  * @param   ShadowTagName name of the tag to be modified
1639  */
1640 int gdcmHeader::SetShaElValByName(std::string content, std::string ShadowTagName) {
1641    return (  ShaElValSet.SetElValueByName (content, ShadowTagName) );
1642 }
1643
1644 /**
1645  * \ingroup gdcmHeader
1646  * \brief   Parses the header of the file but WITHOUT loading element values.
1647  */
1648 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1649    gdcmElValue * newElValue = (gdcmElValue *)0;
1650    
1651    rewind(fp);
1652    CheckSwap();
1653    while ( (newElValue = ReadNextElement()) ) {
1654       SkipElementValue(newElValue);
1655       PubElValSet.Add(newElValue);
1656    }
1657 }
1658
1659 /**
1660  * \ingroup gdcmHeader
1661  * \brief  This predicate, based on hopefully reasonnable heuristics,
1662  *         decides whether or not the current gdcmHeader was properly parsed
1663  *         and contains the mandatory information for being considered as
1664  *         a well formed and usable image.
1665  * @return true when gdcmHeader is the one of a reasonable Dicom file,
1666  *         false otherwise. 
1667  */
1668 bool gdcmHeader::IsReadable(void) {
1669    if (   GetElValByName("Image Dimensions") != GDCM_UNFOUND
1670       && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1671       return false;
1672    }
1673    if ( GetElValByName("Bits Allocated")       == GDCM_UNFOUND )
1674       return false;
1675    if ( GetElValByName("Bits Stored")          == GDCM_UNFOUND )
1676       return false;
1677    if ( GetElValByName("High Bit")             == GDCM_UNFOUND )
1678       return false;
1679    if ( GetElValByName("Pixel Representation") == GDCM_UNFOUND )
1680       return false;
1681    return true;
1682 }
1683
1684 /**
1685  * \ingroup gdcmHeader
1686  * \brief   Small utility function that creates a new manually crafted
1687  *          (as opposed as read from the file) gdcmElValue with user
1688  *          specified name and adds it to the public tag hash table.
1689  * \note    A fake TagKey is generated so the PubDict can keep it's coherence.
1690  * @param   NewTagName The name to be given to this new tag.
1691  * @param   VR The Value Representation to be given to this new tag.
1692  * @ return The newly hand crafted Element Value.
1693  */
1694 gdcmElValue* gdcmHeader::NewManualElValToPubDict(std::string NewTagName, 
1695                                                  std::string VR) {
1696    gdcmElValue* NewElVal = (gdcmElValue*)0;
1697    guint32 StuffGroup = 0xffff;   // Group to be stuffed with additional info
1698    guint32 FreeElem = 0;
1699    gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1700
1701    FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1702    if (FreeElem == UINT32_MAX) {
1703       dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1704                      "Group 0xffff in Public Dict is full");
1705       return (gdcmElValue*)0;
1706    }
1707    NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1708                                 VR, "GDCM", NewTagName);
1709    NewElVal = new gdcmElValue(NewEntry);
1710    PubElValSet.Add(NewElVal);
1711    return NewElVal;
1712 }
1713
1714 /**
1715  * \ingroup gdcmHeader
1716  * \brief   Loads the element values of all the elements present in the
1717  *          public tag based hash table.
1718  */
1719 void gdcmHeader::LoadElements(void) {
1720    rewind(fp);   
1721    TagElValueHT ht = PubElValSet.GetTagHt();
1722    for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1723       LoadElementValue(tag->second);
1724    }
1725    rewind(fp);
1726
1727    // Load 'non string' values   
1728    std::string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);   
1729    if( PhotometricInterpretation == "PALETTE COLOR " ){ 
1730       LoadElementVoidArea(0x0028,0x1200);  // gray LUT   
1731       LoadElementVoidArea(0x0028,0x1201);  // R    LUT
1732       LoadElementVoidArea(0x0028,0x1202);  // G    LUT
1733       LoadElementVoidArea(0x0028,0x1203);  // B    LUT
1734       
1735       LoadElementVoidArea(0x0028,0x1221);  // Segmented Red   Palette Color LUT Data
1736       LoadElementVoidArea(0x0028,0x1222);  // Segmented Green Palette Color LUT Data
1737       LoadElementVoidArea(0x0028,0x1223);  // Segmented Blue  Palette Color LUT Data
1738    }
1739
1740    // --------------------------------------------------------------
1741    // Special Patch to allow gdcm to read ACR-LibIDO formated images
1742    //
1743    // if recognition code tells us we deal with a LibIDO image
1744    // we switch lineNumber and columnNumber
1745    //
1746    std::string RecCode; 
1747    RecCode = GetPubElValByNumber(0x0008, 0x0010);
1748    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1749        RecCode == "CANRME_AILIBOD1_1." ) {
1750          filetype = ACR_LIBIDO; 
1751          std::string rows    = GetPubElValByNumber(0x0028, 0x0010);
1752          std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1753          SetPubElValByNumber(columns, 0x0028, 0x0010);
1754          SetPubElValByNumber(rows   , 0x0028, 0x0011);
1755    }
1756    // ----------------- End of Special Patch ----------------
1757 }
1758
1759 /**
1760   * \ingroup gdcmHeader
1761   * \brief
1762   * @return
1763   */ 
1764 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1765    PubElValSet.Print(os);
1766 }
1767
1768 /**
1769   * \ingroup gdcmHeader
1770   * \brief 
1771   * @return
1772   */  
1773 void gdcmHeader::PrintPubDict(std::ostream & os) {
1774    RefPubDict->Print(os);
1775 }
1776
1777 /**
1778   * \ingroup gdcmHeader
1779   * \brief
1780   * @return integer, acts as a Boolean
1781   */ 
1782 int gdcmHeader::Write(FILE * fp, FileType type) {
1783
1784
1785    // TODO : move the following lines (and a lot of others)
1786    // to a future function CheckAndCorrectHeader
1787
1788    if (type == ImplicitVR) {
1789       std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
1790       ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
1791       
1792       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1793       //      values with a VR of UI shall be padded with a single trailing null
1794       //      Dans le cas suivant on doit pader manuellement avec un 0
1795       
1796       PubElValSet.SetElValueLengthByNumber(18, 0x0002, 0x0010);
1797    } 
1798
1799    if (type == ExplicitVR) {
1800       std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
1801       ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
1802       
1803       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1804       //      values with a VR of UI shall be padded with a single trailing null
1805       //      Dans le cas suivant on doit pader manuellement avec un 0
1806       
1807       PubElValSet.SetElValueLengthByNumber(20, 0x0002, 0x0010);
1808    }
1809
1810    return PubElValSet.Write(fp, type);
1811 }
1812
1813 //
1814 // ------------------------ 'non string' elements related functions
1815 //
1816
1817 /**
1818  * \ingroup       gdcmHeader
1819  * \brief         Loads (from disk) the element content 
1820  *                when a string is not suitable
1821  */
1822 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1823    gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1824    if ( !Element )
1825       return NULL;
1826    size_t o =(size_t)Element->GetOffset();
1827    fseek(fp, o, SEEK_SET);
1828    int l=Element->GetLength();
1829    void * a = malloc(l);
1830    if(!a) {
1831         std::cout << "Big Broblem (LoadElementVoidArea, malloc) " 
1832                   << std::hex << Group << " " << Elem << std::endl;
1833         return NULL;
1834    }  
1835    /* int res = */ PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1836    // TODO check the result 
1837    size_t l2 = fread(a, 1, l ,fp);
1838    if(l != l2) {
1839         std::cout << "Big Broblem (LoadElementVoidArea, fread) " 
1840                   << std::hex << Group << " " << Elem << std::endl;
1841         free(a);
1842         return NULL;
1843    }
1844    return a;  
1845 }
1846
1847 /**
1848  * \ingroup gdcmHeader
1849  * \brief   Gets (from Header) the offset  of a 'non string' element value 
1850  * \        (LoadElementValue has already be executed)
1851  * @param   Group
1852  * @param   Elem
1853  * @return File Offset of the Element Value 
1854  */
1855  size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1856    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1857    if (!elValue) {
1858       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1859                       "failed to Locate gdcmElValue");
1860       return (size_t)0;
1861    }
1862    return elValue->GetOffset();
1863 }
1864
1865 /**
1866  * \ingroup gdcmHeader
1867 * \brief   Gets (from Header) a 'non string' element value 
1868  * \        (LoadElementValue has already be executed)  
1869  * @param   Group
1870  * @param   Elem
1871  * @return Pointer to the 'non string' area
1872  
1873  */
1874  void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1875    gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);   
1876    if (!elValue) {
1877       dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1878                   "failed to Locate gdcmElValue");
1879       return (NULL);
1880    }
1881    return elValue->GetVoidArea();
1882 }
1883
1884
1885 //
1886 // =============================================================================
1887 //   Heuristics based accessors
1888 //==============================================================================
1889 //
1890
1891 // TODO : move to an other file.
1892
1893
1894 /**
1895  * \ingroup gdcmHeader
1896  * \brief   Retrieve the number of columns of image.
1897  * @return  The encountered size when found, 0 by default.
1898  */
1899 int gdcmHeader::GetXSize(void) {
1900    // We cannot check for "Columns" because the "Columns" tag is present
1901    // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1902    std::string StrSize = GetPubElValByNumber(0x0028,0x0011);
1903    if (StrSize == GDCM_UNFOUND)
1904       return 0;
1905    return atoi(StrSize.c_str());
1906 }
1907
1908 /**
1909  * \ingroup gdcmHeader
1910  * \brief   Retrieve the number of lines of image.
1911  * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1912  * @return  The encountered size when found, 1 by default.
1913  */
1914 int gdcmHeader::GetYSize(void) {
1915    // We cannot check for "Rows" because the "Rows" tag is present
1916    // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1917    std::string StrSize = GetPubElValByNumber(0x0028,0x0010);
1918    if (StrSize != GDCM_UNFOUND)
1919       return atoi(StrSize.c_str());
1920    if ( IsDicomV3() )
1921       return 0;
1922    else
1923       // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1924       // hence be a signal (1d image). So we default to 1:
1925       return 1;
1926 }
1927
1928 /**
1929  * \ingroup gdcmHeader
1930  * \brief   Retrieve the number of planes of volume or the number
1931  *          of frames of a multiframe.
1932  * \warning When present we consider the "Number of Frames" as the third
1933  *          dimension. When absent we consider the third dimension as
1934  *          being the "Planes" tag content.
1935  * @return  The encountered size when found, 1 by default.
1936  */
1937 int gdcmHeader::GetZSize(void) {
1938    // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1939    // as the third dimension.
1940    std::string StrSize = GetPubElValByNumber(0x0028,0x0008);
1941    if (StrSize != GDCM_UNFOUND)
1942       return atoi(StrSize.c_str());
1943
1944    // We then consider the "Planes" entry as the third dimension [we
1945    // cannot retrieve by name since "Planes tag is present both in
1946    // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary]. 
1947    StrSize = GetPubElValByNumber(0x0028,0x0012);
1948    if (StrSize != GDCM_UNFOUND)
1949       return atoi(StrSize.c_str());
1950    return 1;
1951 }
1952
1953 /**
1954  * \ingroup gdcmHeader
1955  * \brief   Retrieve the number of Bits Stored
1956  *          (as opposite to number of Bits Allocated)
1957  * 
1958  * @return  The encountered number of Bits Stored, 0 by default.
1959  */
1960 int gdcmHeader::GetBitsStored(void) { 
1961    std::string StrSize = GetPubElValByNumber(0x0028,0x0101);
1962    if (StrSize == GDCM_UNFOUND)
1963       return 1;
1964    return atoi(StrSize.c_str());
1965 }
1966
1967 /**
1968  * \ingroup gdcmHeader
1969  * \brief   Retrieve the number of Bits Allocated
1970  *          (8, 12 -compacted ACR-NEMA files, 16, ...)
1971  * 
1972  * @return  The encountered number of Bits Allocated, 0 by default.
1973  */
1974 int gdcmHeader::GetBitsAllocated(void) { 
1975    std::string StrSize = GetPubElValByNumber(0x0028,0x0100);
1976    if (StrSize == GDCM_UNFOUND)
1977       return 1;
1978    return atoi(StrSize.c_str());
1979 }
1980
1981 /**
1982  * \ingroup gdcmHeader
1983  * \brief   Retrieve the number of Samples Per Pixel
1984  *          (1 : gray level, 3 : RGB)
1985  * 
1986  * @return  The encountered number of Samples Per Pixel, 1 by default.
1987  */
1988 int gdcmHeader::GetSamplesPerPixel(void) { 
1989    std::string StrSize = GetPubElValByNumber(0x0028,0x0002);
1990    if (StrSize == GDCM_UNFOUND)
1991       return 1; // Well, it's supposed to be mandatory ...
1992    return atoi(StrSize.c_str());
1993 }
1994
1995 /**
1996  * \ingroup gdcmHeader
1997  * \brief   Retrieve the Planar Configuration for RGB images
1998  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1999  * 
2000  * @return  The encountered Planar Configuration, 0 by default.
2001  */
2002 int gdcmHeader::GetPlanarConfiguration(void) { 
2003    std::string StrSize = GetPubElValByNumber(0x0028,0x0006);
2004    if (StrSize == GDCM_UNFOUND)
2005       return 0;
2006    return atoi(StrSize.c_str());
2007 }
2008
2009 /**
2010  * \ingroup gdcmHeader
2011  * \brief   Return the size (in bytes) of a single pixel of data.
2012  * @return  The size in bytes of a single pixel of data.
2013  *
2014  */
2015 int gdcmHeader::GetPixelSize(void) {
2016    std::string PixelType = GetPixelType();
2017    if (PixelType == "8U"  || PixelType == "8S")
2018       return 1;
2019    if (PixelType == "16U" || PixelType == "16S")
2020       return 2;
2021    if (PixelType == "32U" || PixelType == "32S")
2022       return 4;
2023    dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
2024    return 0;
2025 }
2026
2027 /**
2028  * \ingroup gdcmHeader
2029  * \brief   Build the Pixel Type of the image.
2030  *          Possible values are:
2031  *          - 8U  unsigned  8 bit,
2032  *          - 8S    signed  8 bit,
2033  *          - 16U unsigned 16 bit,
2034  *          - 16S   signed 16 bit,
2035  *          - 32U unsigned 32 bit,
2036  *          - 32S   signed 32 bit,
2037  * \warning 12 bit images appear as 16 bit.
2038  * @return  
2039  */
2040 std::string gdcmHeader::GetPixelType(void) {
2041    std::string BitsAlloc;
2042    BitsAlloc = GetElValByName("Bits Allocated");
2043    if (BitsAlloc == GDCM_UNFOUND) {
2044       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
2045       BitsAlloc = std::string("16");
2046    }
2047    if (BitsAlloc == "12")
2048       BitsAlloc = std::string("16");
2049
2050    std::string Signed;
2051    Signed = GetElValByName("Pixel Representation");
2052    if (Signed == GDCM_UNFOUND) {
2053       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
2054       BitsAlloc = std::string("0");
2055    }
2056    if (Signed == "0")
2057       Signed = std::string("U");
2058    else
2059       Signed = std::string("S");
2060
2061    return( BitsAlloc + Signed);
2062 }
2063
2064 /**
2065   * \ingroup gdcmHeader
2066   * \brief gets the info from 0002,0010 : Transfert Syntax
2067   * \           else 1.
2068   * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
2069   */
2070 std::string gdcmHeader::GetTransferSyntaxName(void) { 
2071    std::string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
2072    if (TransfertSyntax == GDCM_UNFOUND) {
2073       dbg.Verbose(0, "gdcmHeader::GetTransferSyntaxName: unfound Transfert Syntax (0002,0010)");
2074       return "Uncompressed ACR-NEMA";
2075    }
2076    // we do it only when we need it
2077    gdcmTS * ts = gdcmGlobal::GetTS();
2078    std::string tsName=ts->GetValue(TransfertSyntax);
2079    //delete ts; // Seg Fault when deleted ?!
2080    return tsName;
2081 }
2082
2083 // -------------------------------- Lookup Table related functions ------------
2084
2085 /**
2086   * \ingroup gdcmHeader
2087   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2088   * \           else 0
2089   * @return Lookup Table Length 
2090   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ] 
2091   */
2092   
2093 int gdcmHeader::GetLUTLength(void) {
2094    std::vector<std::string> tokens;
2095    int LutLength;
2096    //int LutDepth;
2097    //int LutNbits;
2098    // Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2099    std::string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
2100    if (LutDescriptionR == GDCM_UNFOUND)
2101       return 0;
2102    std::string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
2103    if (LutDescriptionG == GDCM_UNFOUND)
2104       return 0;
2105    std::string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
2106    if (LutDescriptionB == GDCM_UNFOUND)
2107       return 0;
2108    if( (LutDescriptionR != LutDescriptionG) || (LutDescriptionR != LutDescriptionB) ) {
2109       dbg.Verbose(0, "gdcmHeader::GetLUTLength: The CLUT R,G,B are not equal");
2110       return 0;   
2111    } 
2112    std::cout << "Lut Description " << LutDescriptionR <<std::endl;
2113    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2114    Tokenize (LutDescriptionR, tokens, "\\");
2115    LutLength=atoi(tokens[0].c_str());
2116    //LutDepth=atoi(tokens[1].c_str());
2117    //LutNbits=atoi(tokens[2].c_str());
2118    tokens.clear();
2119    return LutLength;
2120 }
2121
2122 /**
2123   * \ingroup gdcmHeader
2124   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2125   * \           else 0
2126   * @return Lookup Table nBit 
2127   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ] 
2128   */
2129   
2130 int gdcmHeader::GetLUTNbits(void) {
2131    std::vector<std::string> tokens;
2132    //int LutLength;
2133    //int LutDepth;
2134    int LutNbits;
2135    //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2136    // Consistency already checked in GetLUTLength
2137    std::string LutDescription = GetPubElValByNumber(0x0028,0x1101);
2138    if (LutDescription == GDCM_UNFOUND)
2139       return 0;
2140    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2141    Tokenize (LutDescription, tokens, "\\");
2142    //LutLength=atoi(tokens[0].c_str());
2143    //LutDepth=atoi(tokens[1].c_str());
2144    LutNbits=atoi(tokens[2].c_str());
2145    tokens.clear();
2146    return LutNbits;
2147 }
2148   
2149
2150 /**
2151   * \ingroup gdcmHeader
2152   * \brief gets the info from 0028,1201 : Lookup Table Red
2153   * \           else 0
2154   * @return Lookup Table Red 
2155   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ] 
2156   */ 
2157 void * gdcmHeader::GetLUTRed(void) {
2158    return GetPubElValVoidAreaByNumber(0x0028,0x1201);  
2159 }
2160
2161 /**
2162   * \ingroup gdcmHeader
2163   * \brief gets the info from 0028,1202 : Lookup Table Green
2164   * \           else 0
2165   * @return Lookup Table Red 
2166   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ] 
2167   */ 
2168   void * gdcmHeader::GetLUTGreen(void) {
2169    return GetPubElValVoidAreaByNumber(0x0028,0x1202);
2170 }
2171
2172 /**
2173   * \ingroup gdcmHeader
2174   * \brief gets the info from 0028,1202 : Lookup Table Blue
2175   * \           else 0
2176   * @return Lookup Table Blue 
2177   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ] 
2178   */ 
2179 void * gdcmHeader::GetLUTBlue(void) {
2180    return GetPubElValVoidAreaByNumber(0x0028,0x1203);
2181 }
2182
2183 /**
2184   * \ingroup gdcmHeader
2185   * \brief 
2186   * @return Lookup Table RGB
2187   * \       when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2188   * \        and (0028,1201),(0028,1202),(0028,1202) are found
2189   * \warning : hazardous ! Use better GetPubElValVoidAreaByNumber
2190   */ 
2191 void * gdcmHeader::GetLUTRGB(void) {
2192 // Not so easy : see 
2193 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
2194 // and  OT-PAL-8-face.dcm
2195
2196    if (GetPubElValByNumber(0x0028,0x0004) == GDCM_UNFOUND) {
2197    dbg.Verbose(0, "gdcmHeader::GetLUTRGB: unfound Photometric Interpretation");
2198         return NULL;
2199    }  
2200    void * LutR,*LutG,*LutB;
2201    int l;
2202      
2203   // Maybe, some day we get an image 
2204   // that respects the definition ...
2205   // Let's consider no ones does.
2206   
2207    l= GetLUTLength();  
2208    if(l==0) 
2209      return (NULL);     
2210    int nBits=GetLUTNbits();
2211
2212   // a virer quand on aura trouve UNE image 
2213   // qui correspond VRAIMENT à la definition !
2214     std::cout << "l " << l << " nBits " << nBits;
2215    
2216    l= l/(nBits/8);
2217     
2218    LutR =GetPubElValVoidAreaByNumber(0x0028,0x1201);
2219    LutG =GetPubElValVoidAreaByNumber(0x0028,0x1202);
2220    LutB =GetPubElValVoidAreaByNumber(0x0028,0x1203);
2221    
2222    // Warning : Any value for nBits  as to be considered as 8
2223    //           Any value for Length as to be considered as 256
2224    // That's DICOM ...
2225    
2226    // Just wait before removing the following code
2227    /*
2228    if (nBits == 16) {
2229       guint16 * LUTRGB, *rgb;
2230       LUTRGB = rgb = (guint16 *) malloc(3*l*sizeof( guint16));
2231       guint16 * r = (guint16 *)LutR;
2232       guint16 * g = (guint16 *)LutG;
2233       guint16 * b = (guint16 *)LutB;
2234       for(int i=0;i<l;i++) {
2235          *rgb++ = *r++;
2236          *rgb++ = *g++;
2237          *rgb++ = *b++;
2238       }
2239       return(LUTRGB); 
2240    } else
2241    
2242    */ {      // we assume it's always 8 Bits
2243       l=256; // we assume ...
2244       unsigned char * LUTRGB, *rgb;
2245       LUTRGB = rgb = (unsigned char *) malloc(3*l*sizeof( char));
2246       unsigned char * r = (unsigned char *)LutR;
2247       unsigned char * g = (unsigned char *)LutG;
2248       unsigned char * b = (unsigned char *)LutB;
2249       for(int i=0;i<l;i++) {
2250       //std::cout << "lut16 " << i << " : " << *r << " " << *g << " " << *b 
2251       //          << std::endl;
2252       printf("lut 8 %d : %d %d %d \n",i,*r,*g,*b);
2253          *rgb++ = *r++;
2254          *rgb++ = *g++;
2255          *rgb++ = *b++;
2256       } 
2257       free(LutR); free(LutB); free(LutG);
2258       return(LUTRGB);   
2259    } 
2260
2261 /*  Sorry for the comments. The code will be moved in a fonction
2262
2263         std::string x=GetPubElValByNumber(0x0028,0x1201);
2264         unsigned short int * lutR = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2265         unsigned short int * lutG = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2266         unsigned short int * lutB = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2267
2268          std::vector<std::string> tokens;
2269          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2270          Tokenize ((const std::string)x, tokens, "\\");
2271          for (unsigned int i=0; i<tokens.size();i++) {
2272             lutR[i] = atoi(tokens[i].c_str());
2273             printf("%d (%x)\n",lutR[i],lutR[i]);   
2274          }
2275
2276          std::string y=GetPubElValByNumber(0x0028,0x1202);
2277          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2278          Tokenize ((const std::string)y, tokens, "\\");
2279          for (unsigned int i=0; i<tokens.size();i++) {
2280             lutG[i] = atoi(tokens[i].c_str());   
2281          }
2282
2283          std::string z=GetPubElValByNumber(0x0028,0x1203);
2284          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2285          Tokenize ((const std::string)z, tokens, "\\");
2286          for (unsigned int i=0; i<tokens.size();i++) {
2287             lutB[i] = atoi(tokens[i].c_str());   
2288          }
2289          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2290          Tokenize ((const std::string)x, tokens, "\\");
2291          for (unsigned int i=0; i<tokens.size();i++) {
2292             lutB[i] = atoi(tokens[i].c_str()); 
2293          }
2294
2295  */
2296
2297 //int lgth=GetLUTLength();
2298 //cout << "lgth " << lgth << std::endl;;
2299 //for (int j=0;j<lgth;j++){
2300 //printf ("%d : %d (%x) %d (%x) %d (%x)\n",j,lutR[j],lutR[j],lutG[j],lutG[j],lutB[j],lutB[j]);
2301 //}
2302
2303
2304 }
2305