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