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