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