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