]> Creatis software - gdcm.git/blob - src/gdcmElValSet.cxx
*FIX: Forgot about missing flags for SunOs + old gcc
[gdcm.git] / src / gdcmElValSet.cxx
1 // gdcmElValSet.cxx
2
3 #include "gdcmUtil.h"
4 #include "gdcmElValSet.h"
5 #include "gdcmTS.h"
6 #ifdef GDCM_NO_ANSI_STRING_STREAM
7 #  include <strstream>
8 #  define  ostringstream ostrstream
9 # else
10 #  include <sstream>
11 #endif
12
13
14 gdcmElValSet::~gdcmElValSet() {
15    for (TagElValueHT::iterator tag = tagHt.begin(); tag != tagHt.end(); ++tag) {
16       gdcmElValue* EntryToDelete = tag->second;
17       if ( EntryToDelete )
18          delete EntryToDelete;
19    }
20    tagHt.clear();
21    // Since Add() adds symetrical in both tagHt and NameHt we can
22    // assume all the pointed gdcmElValues are already cleaned-up when
23    // we cleaned tagHt.
24    NameHt.clear();
25 }
26
27 /**
28  * \ingroup gdcmElValSet
29  * \brief   
30  * @param   newElValue
31  * @return  
32  */
33 void gdcmElValSet::Add(gdcmElValue * newElValue) {
34         tagHt [newElValue->GetKey()]  = newElValue;
35         NameHt[newElValue->GetName()] = newElValue;
36         
37 // WARNING : push_bash in listElem ONLY during ParseHeader
38 // TODO : something to allow further Elements addition 
39 // position to be taken care of !       
40         listElem.push_back(newElValue); 
41 }
42
43 /**
44  * \ingroup gdcmElValSet
45  * \brief   Checks if a given Dicom element exists
46  * \        within a ElValSet
47  * @param   Group
48  * @param   Elem
49  * @return  
50  */
51 int gdcmElValSet::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
52         std::string key = TranslateToKey(Group, Elem );
53         return (tagHt.count(key));
54 }
55
56 /**
57  * \ingroup gdcmElValSet
58  * \brief   
59  */
60 void gdcmElValSet::Print(std::ostream & os) {
61
62    size_t o;
63    unsigned short int g, e;
64    TSKey v;
65    std::string d2;
66    gdcmTS * ts = gdcmGlobal::GetTS();
67    
68    std::cout << "------------- using tagHt ---------------------" << std::endl;
69    
70    for (TagElValueHT::iterator tag = tagHt.begin();
71            tag != tagHt.end();
72            ++tag){
73       g = tag->second->GetGroup();
74       e = tag->second->GetElement();
75       v = tag->second->GetValue();
76       o = tag->second->GetOffset();
77       d2 = _CreateCleanString(v);  // replace non printable characters by '.'
78                  
79       os << tag->first << ": ";
80       os << " lgr : " << tag->second->GetLength();
81       os << ", Offset : " << o;
82       os << " x(" << std::hex << o << std::dec << ") ";
83       os << "\t[" << tag->second->GetVR()    << "]";
84       os << "\t[" << tag->second->GetName()  << "]";       
85       os << "\t[" << d2 << "]";
86       
87       // Display the UID value (instead of displaying the rough code)  
88       if (g == 0x0002) {  // Some more to be displayed ?
89          if ( (e == 0x0010) || (e == 0x0002) )     
90             os << "  ==>\t[" << ts->GetValue(v) << "]";   
91       } else {
92          if (g == 0x0008) {
93             if ( (e == 0x0016) || (e == 0x1150)  )         
94                os << "  ==>\t[" << ts->GetValue(v) << "]"; 
95          }
96       }              
97       os << std::endl;
98    }
99    
100    std::cout << "------------ using listElem -------------------" << std::endl;
101       
102   guint32 lgth;
103   char greltag[10];  //group element tag
104    
105   for (ListTag::iterator i = listElem.begin();  
106            i != listElem.end();
107            ++i){
108       g = (*i)->GetGroup();
109       e = (*i)->GetElement();
110       v = (*i)->GetValue();
111       o = (*i)->GetOffset();
112       sprintf(greltag,"%04x|%04x",g,e);           
113       d2 = _CreateCleanString(v);  // replace non printable characters by '.'
114       os << greltag << ": lgth : ";
115       lgth = (*i)->GetReadLength();
116       if ( lgth == 0xffffffff) 
117          os << std::hex << lgth << std::dec ;
118       else
119          os << lgth;
120       os << ", Offset : " << o;
121       os << " x(" << std::hex << o << std::dec << ") ";
122       os << "\t[" << (*i)->GetVR()    << "]";
123       os << "\t[" << (*i)->GetName()  << "]";       
124       os << "\t[" << d2 << "]";
125       
126       // Display the UID value (instead of displaying the rough code)  
127       if (g == 0x0002) {  // Any more to be displayed ?
128          if ( (e == 0x0010) || (e == 0x0002) )     
129             os << "  ==>\t[" << ts->GetValue(v) << "]";   
130       } else {
131          if (g == 0x0008) {
132             if ( (e == 0x0016) || (e == 0x1150)  )         
133                os << "  ==>\t[" << ts->GetValue(v) << "]"; 
134          }
135       }              
136       os << std::endl;
137    }       
138
139
140 /**
141  * \ingroup gdcmElValSet
142  * \brief   
143  */
144 void gdcmElValSet::PrintByName(std::ostream & os) {
145    for (TagElValueNameHT::iterator tag = NameHt.begin();
146           tag != NameHt.end();
147           ++tag){
148       os << tag->first << ": ";
149       os << "[" << tag->second->GetValue() << "]";
150       os << "[" << tag->second->GetKey()   << "]";
151       os << "[" << tag->second->GetVR()    << "]" << std::endl;
152    }
153 }
154
155 /**
156  * \ingroup gdcmElValSet
157  * \brief   
158  * @param   group 
159  * @param   element 
160  * @return  
161  */
162 gdcmElValue* gdcmElValSet::GetElementByNumber(guint16 group, guint16 element) {
163    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
164    if ( ! tagHt.count(key))
165       return (gdcmElValue*)0;
166    return tagHt.find(key)->second;
167 }
168
169 /**
170  * \ingroup gdcmElValSet
171  * \brief   
172  * @return  
173  */
174 gdcmElValue* gdcmElValSet::GetElementByName(std::string TagName) {
175    if ( ! NameHt.count(TagName))
176       return (gdcmElValue*)0;
177    return NameHt.find(TagName)->second;
178 }
179
180 /**
181  * \ingroup gdcmElValSet
182  * \brief   
183  * @param   group 
184  * @param   element 
185  * @return  
186  */
187 std::string gdcmElValSet::GetElValueByNumber(guint16 group, guint16 element) {
188    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
189    if ( ! tagHt.count(key))
190       return GDCM_UNFOUND;
191    return tagHt.find(key)->second->GetValue();
192 }
193
194 /**
195  * \ingroup gdcmElValSet
196  * \brief   
197  * @return  
198  */
199 std::string gdcmElValSet::GetElValueByName(std::string TagName) {
200    if ( ! NameHt.count(TagName))
201       return GDCM_UNFOUND;
202    return NameHt.find(TagName)->second->GetValue();
203 }
204
205 /**
206  * \ingroup gdcmElValSet
207  * \brief   
208  * @param   content
209  * @param   group 
210  * @param   element 
211  * @return  
212  */
213 int gdcmElValSet::SetElValueByNumber(std::string content,
214                                      guint16 group, guint16 element) {
215    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
216    if ( ! tagHt.count(key))
217       return 0;
218    int l = content.length();
219    if(l%2) {  // Odd length are padded with a space (020H).
220       l++;
221       content = content + '\0';
222    }
223    tagHt[key]->SetValue(content);
224
225    std::string vr = tagHt[key]->GetVR();
226    guint32 lgr;
227
228    if( (vr == "US") || (vr == "SS") ) 
229       lgr = 2;
230    else if( (vr == "UL") || (vr == "SL") )
231       lgr = 4;
232    else
233       lgr = l;     
234    tagHt[key]->SetLength(lgr); 
235    return 1;
236 }
237
238 /**
239  * \ingroup gdcmElValSet
240  * \brief   
241  * @param   content
242  * @param   TagName
243  * @return  
244  */
245 int gdcmElValSet::SetElValueByName(std::string content, std::string TagName) {
246    if ( ! NameHt.count(TagName))
247       return 0;
248    int l = content.length();
249    if(l%2) {  // Odd length are padded with a space (020H).
250       l++;
251       // Well. I know that '/0' is NOT a space
252       // but it doesn't work with a space. 
253       // Use hexedit and see 0002|0010 value (Transfer Syntax UID)
254       content = content + '\0';
255    }
256    NameHt[TagName]->SetValue(content);
257
258    std::string vr = NameHt[TagName]->GetVR();
259    guint32 lgr;
260
261    if( (vr == "US") || (vr == "SS") ) 
262       lgr = 2;
263    else if( (vr == "UL") || (vr == "SL") )
264       lgr = 4;     
265    else 
266       lgr = content.length();
267            
268 // TODO : WARNING: le cas de l'element des pixels (7fe0,0010) n'est pas traite
269 // par SetElValueByName
270 // il faudra utiliser SetElValueByNumber
271            
272    NameHt[TagName]->SetLength(lgr);
273    return 1;            
274 }
275
276 /**
277  * \ingroup gdcmElValSet
278  * \brief   Generate a free TagKey i.e. a TagKey that is not present
279  *          in the TagHt dictionary.
280  * @param   group The generated tag must belong to this group.  
281  * @return  The element of tag with given group which is fee.
282  */
283 guint32 gdcmElValSet::GenerateFreeTagKeyInGroup(guint16 group) {
284    for (guint32 elem = 0; elem < UINT32_MAX; elem++) {
285       TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
286       if (tagHt.count(key) == 0)
287          return elem;
288    }
289    return UINT32_MAX;
290 }
291
292 /**
293  * \ingroup gdcmElValSet
294  * \brief   
295  * @param   area
296  * @param   group 
297  * @param   element 
298  * @return  
299  */
300 int gdcmElValSet::SetVoidAreaByNumber(void * area,
301                                       guint16 group, guint16 element) {
302    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
303    if ( ! tagHt.count(key))
304       return 0;
305    tagHt[key]->SetVoidArea(area);        
306    return 1 ;           
307 }
308
309 /**
310  * \ingroup gdcmElValSet
311  * \brief   
312  * @param   length
313  * @param   group 
314  * @param   element 
315  * @return  int acts as a boolean
316  */
317 int gdcmElValSet::SetElValueLengthByNumber(guint32 length,
318                                            guint16 group, guint16 element) {
319    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
320    if ( ! tagHt.count(key))
321       return 0;
322    if (length%2) length++; // length must be even
323    tagHt[key]->SetLength(length);        
324    return 1 ;           
325 }
326 /**
327  * \ingroup gdcmElValSet
328  * \brief   
329  * @param   length
330  * @param   TagName
331  * @return  
332  */
333 int gdcmElValSet::SetElValueLengthByName(guint32 length, std::string TagName) {
334    if ( ! NameHt.count(TagName))
335       return 0;
336    if (length%2) length++; // length must be even
337    NameHt.find(TagName)->second->SetLength(length);      
338    return 1 ;           
339 }
340
341 /**
342  * \ingroup gdcmElValSet
343  * \brief   Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
344  * @param   SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
345  * @param   type
346  */
347 void gdcmElValSet::UpdateGroupLength(bool SkipSequence, FileType type) {
348    guint16 gr, el;
349    std::string vr;
350    
351    gdcmElValue *elem;
352    char trash[10];
353    std::string str_trash;
354    
355    GroupKey key;
356    GroupHT groupHt;  // to hold the length of each group
357    TagKey tk;
358    // remember :
359    // typedef std::map<GroupKey, int> GroupHT;
360    
361    gdcmElValue *elemZ;
362   
363    // for each Tag in the DCM Header
364    
365    for (TagElValueHT::iterator tag2 = tagHt.begin(); 
366         tag2 != tagHt.end();
367         ++tag2){
368
369       elem  = tag2->second;
370       gr = elem->GetGroup();
371       el = elem->GetElement();
372       vr = elem->GetVR(); 
373                  
374       sprintf(trash, "%04x", gr);
375       key = trash;              // generate 'group tag'
376       
377       // if the caller decided not to take SEQUENCEs into account 
378       // e.g : he wants to write an ACR-NEMA File 
379                 
380       if (SkipSequence && vr == "SQ") continue;
381       
382          // Still unsolved problem :
383          // we cannot find the 'Sequence Delimitation Item'
384          // since it's at the end of the Hash Table
385          // (fffe,e0dd) 
386              
387          // pas SEQUENCE en ACR-NEMA
388          // WARNING : 
389          // --> la descente a l'interieur' des SQ 
390          // devrait etre faite avec une liste chainee, pas avec une HTable...
391             
392       if ( groupHt.count(key) == 0) { // we just read the first elem of a given group
393          if (el == 0x0000) {          // the first elem is 0x0000
394             groupHt[key] = 0;         // initialize group length 
395          } else {
396             groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
397          } 
398       } else {   // any elem but the first    
399          if (type == ExplicitVR) {
400             if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) {
401                groupHt[key] +=  4; // explicit VR AND OB, OW, SQ : 4 more bytes
402             }
403          }
404          groupHt[key] += 2 + 2 + 4 + elem->GetLength(); 
405       } 
406    }
407
408    unsigned short int gr_bid;
409   
410    for (GroupHT::iterator g = groupHt.begin(); // for each group we found
411         g != groupHt.end();
412         ++g){ 
413       // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
414       //        warning: unsigned int format, different type arg
415       sscanf(g->first.c_str(),"%x",&gr_bid);
416       tk = g->first + "|0000";                  // generate the element full tag
417                      
418       if ( tagHt.count(tk) == 0) {              // if element 0x0000 not found
419          gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");       
420          elemZ = new gdcmElValue(tagZ);
421          elemZ->SetLength(4);
422          Add(elemZ);                            // create it
423       } else {
424          elemZ=GetElementByNumber(gr_bid, 0x0000);
425       }     
426       sprintf(trash ,"%d",g->second);
427       str_trash=trash;
428       elemZ->SetValue(str_trash);
429    }   
430 }
431
432 /**
433  * \ingroup gdcmElValSet
434  * \brief   writes on disc according to the requested format
435  * \        (ACR-NEMA, DICOM, RAW) the image
436  * \ warning does NOT add the missing elements in the header :
437  * \         it's up to the user doing it !
438  * \         (function CheckHeaderCoherence to be written)
439  * @param   type type of the File to be written 
440  *          (ACR-NEMA, DICOM, RAW)
441  * @param   _fp already open file pointer
442  * @return  
443  */
444 void gdcmElValSet::WriteElements(FileType type, FILE * _fp) {
445    guint16 gr, el;
446    guint32 lgr;
447    const char * val;
448    std::string vr;
449    guint32 val_uint32;
450    guint16 val_uint16;
451    
452    std::vector<std::string> tokens;
453    
454    // TODO : use listElem to iterate, not TagHt!
455    //        pb : gdcmElValSet.Add does NOT update listElem
456    //        find a trick in STL to do it, at low cost !
457
458    void *ptr;
459
460    // Tout ceci ne marche QUE parce qu'on est sur un proc Little Endian 
461    // restent a tester les echecs en ecriture (apres chaque fwrite)
462
463    for (TagElValueHT::iterator tag2=tagHt.begin();
464         tag2 != tagHt.end();
465         ++tag2){
466
467       gr =  tag2->second->GetGroup();
468       el =  tag2->second->GetElement();
469       lgr = tag2->second->GetLength();
470       val = tag2->second->GetValue().c_str();
471       vr =  tag2->second->GetVR();
472       
473      // std::cout << "Tag "<< std::hex << gr << " " << el << std::endl;
474
475       if ( type == ACR ) { 
476          if (gr < 0x0008)   continue; // ignore pure DICOM V3 groups
477          if (gr %2)         continue; // ignore shadow groups
478          if (vr == "SQ" )   continue; // ignore Sequences
479          if (gr == 0xfffe ) continue; // ignore delimiters
480       } 
481
482       fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp);  //group
483       fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp);  //element
484
485       if ( (type == ExplicitVR) && (gr <= 0x0002) ) {
486          // EXPLICIT VR
487          guint16 z=0, shortLgr;
488          fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
489
490          if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) {
491             fwrite ( &z,  (size_t)2 ,(size_t)1 ,_fp);
492             fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
493
494          } else {
495             shortLgr=lgr;
496             fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
497          }
498       } else { // IMPLICIT VR
499          fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
500       }
501
502       if (vr == "US" || vr == "SS") {
503          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
504          Tokenize (tag2->second->GetValue(), tokens, "\\");
505          for (unsigned int i=0; i<tokens.size();i++) {
506             val_uint16 = atoi(tokens[i].c_str());
507             ptr = &val_uint16;
508             fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
509          }
510          tokens.clear();
511          continue;
512       }
513       if (vr == "UL" || vr == "SL") {
514          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
515          Tokenize (tag2->second->GetValue(), tokens, "\\");
516          for (unsigned int i=0; i<tokens.size();i++) {
517             val_uint32 = atoi(tokens[i].c_str());
518             ptr = &val_uint32;
519             fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
520          }
521          tokens.clear();
522          continue;
523       }     
524       // Pixels are never loaded in the element !
525       if ((gr == 0x7fe0) && (el == 0x0010) ) break;
526
527       fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
528    }
529 }
530
531 /**
532  * \ingroup gdcmElValSet
533  * \brief   
534  * @param   _fp
535  * @param   type
536  * @return  
537  */
538 int gdcmElValSet::Write(FILE * _fp, FileType type) {
539
540         // Question :
541         // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
542         // (FileType est un champ de gdcmHeader ...)
543         // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
544         // no way 
545         // a moins de se livrer a un tres complique ajout des champs manquants.
546         // faire un CheckAndCorrectHeader (?)
547
548    if ( (type == ImplicitVR) || (type == ExplicitVR) )
549       UpdateGroupLength(false,type);
550    if ( type == ACR)
551       UpdateGroupLength(true,ACR);
552
553    WriteElements(type, _fp);
554    return(1);
555 }