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