]> Creatis software - gdcm.git/blob - src/gdcmElValSet.cxx
Remaining \n in std::cout and std::cerr replaced by std::endl
[gdcm.git] / src / gdcmElValSet.cxx
1 // gdcmElValSet.cxx
2
3 #ifdef _MSC_VER
4 // 'identifier' : class 'type' needs to have dll-interface to be used by
5 // clients of class 'type2'
6 #pragma warning ( disable : 4251 )
7 // 'identifier' : identifier was truncated to 'number' characters in the
8 // debug information
9 #pragma warning ( disable : 4786 )
10 #endif //_MSC_VER
11
12 #include <sstream>
13 #include "gdcmUtil.h"
14 #include "gdcmElValSet.h"
15 #include "gdcmTS.h"
16
17 gdcmElValSet::~gdcmElValSet() {
18    for (TagElValueHT::iterator tag = tagHt.begin(); tag != tagHt.end(); ++tag) {
19       gdcmElValue* EntryToDelete = tag->second;
20       if ( EntryToDelete )
21          delete EntryToDelete;
22    }
23    tagHt.clear();
24    // Since Add() adds symetrical in both tagHt and NameHt we can
25    // assume all the pointed gdcmElValues are already cleaned-up when
26    // we cleaned tagHt.
27    NameHt.clear();
28 }
29
30 TagElValueHT & gdcmElValSet::GetTagHt(void) {
31         return tagHt;
32 }
33
34 /**
35  * \ingroup gdcmElValSet
36  * \brief   
37  * @param   newElValue
38  * @return  
39  */
40 void gdcmElValSet::Add(gdcmElValue * newElValue) {
41         tagHt [newElValue->GetKey()]  = newElValue;
42         NameHt[newElValue->GetName()] = newElValue;
43 }
44
45 /**
46  * \ingroup gdcmElValSet
47  * \brief   Checks if a given Dicom element exists
48  * \        within a ElValSet
49  * @param   Group
50  * @param   Elem
51  * @return  
52  */
53 int gdcmElValSet::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
54         std::string key = TranslateToKey(Group, Elem );
55         return (tagHt.count(key));
56 }
57
58 /**
59  * \ingroup gdcmElValSet
60  * \brief   
61  */
62 void gdcmElValSet::Print(ostream & os) {
63
64    size_t o;
65    short int g, e;
66    TSKey v;
67    std::string d2;
68    gdcmTS * ts = gdcmGlobal::GetTS();
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(" << hex << o << 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
101 /**
102  * \ingroup gdcmElValSet
103  * \brief   
104  */
105 void gdcmElValSet::PrintByName(ostream & os) {
106    for (TagElValueNameHT::iterator tag = NameHt.begin();
107           tag != NameHt.end();
108           ++tag){
109       os << tag->first << ": ";
110       os << "[" << tag->second->GetValue() << "]";
111       os << "[" << tag->second->GetKey()   << "]";
112       os << "[" << tag->second->GetVR()    << "]" << std::endl;
113    }
114 }
115
116 /**
117  * \ingroup gdcmElValSet
118  * \brief   
119  * @param   group 
120  * @param   element 
121  * @return  
122  */
123 gdcmElValue* gdcmElValSet::GetElementByNumber(guint16 group, guint16 element) {
124    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
125    if ( ! tagHt.count(key))
126       return (gdcmElValue*)0;
127    return tagHt.find(key)->second;
128 }
129
130 /**
131  * \ingroup gdcmElValSet
132  * \brief   
133  * @return  
134  */
135 gdcmElValue* gdcmElValSet::GetElementByName(std::string TagName) {
136    if ( ! NameHt.count(TagName))
137       return (gdcmElValue*)0;
138    return NameHt.find(TagName)->second;
139 }
140
141 /**
142  * \ingroup gdcmElValSet
143  * \brief   
144  * @param   group 
145  * @param   element 
146  * @return  
147  */
148 std::string gdcmElValSet::GetElValueByNumber(guint16 group, guint16 element) {
149    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
150    if ( ! tagHt.count(key))
151       return GDCM_UNFOUND;
152    return tagHt.find(key)->second->GetValue();
153 }
154
155 /**
156  * \ingroup gdcmElValSet
157  * \brief   
158  * @return  
159  */
160 std::string gdcmElValSet::GetElValueByName(std::string TagName) {
161    if ( ! NameHt.count(TagName))
162       return GDCM_UNFOUND;
163    return NameHt.find(TagName)->second->GetValue();
164 }
165
166 /**
167  * \ingroup gdcmElValSet
168  * \brief   
169  * @param   content
170  * @param   group 
171  * @param   element 
172  * @return  
173  */
174 int gdcmElValSet::SetElValueByNumber(std::string content,
175                                      guint16 group, guint16 element) {
176    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
177    if ( ! tagHt.count(key))
178       return 0;
179    tagHt[key]->SetValue(content);       
180    std::string vr = tagHt[key]->GetVR();
181    guint32 lgr;
182
183    if( (vr == "US") || (vr == "SS") ) 
184       lgr = 2;
185    else if( (vr == "UL") || (vr == "SL") )
186       lgr = 4;
187    else
188       lgr = content.length();      
189    tagHt[key]->SetLength(lgr); 
190    return 1;
191 }
192
193 /**
194  * \ingroup gdcmElValSet
195  * \brief   
196  * @param   content
197  * @param   TagName
198  * @return  
199  */
200 int gdcmElValSet::SetElValueByName(std::string content, std::string TagName) {
201    if ( ! NameHt.count(TagName))
202       return 0;
203    NameHt[TagName]->SetValue(content);
204    std::string vr = NameHt[TagName]->GetVR();
205    guint32 lgr;
206
207    if( (vr == "US") || (vr == "SS") ) 
208       lgr = 2;
209    else if( (vr == "UL") || (vr == "SL") )
210       lgr = 4;     
211    else 
212       lgr = content.length();
213            
214 // TODO : WARNING: le cas de l'element des pixels (7fe0,0010) n'est pas traite
215 // par SetElValueByName
216 // il faudra utiliser SetElValueByNumber
217            
218    NameHt[TagName]->SetLength(lgr);
219    return 1;            
220 }
221
222 /**
223  * \ingroup gdcmElValSet
224  * \brief   Generate a free TagKey i.e. a TagKey that is not present
225  *          in the TagHt dictionary.
226  * @param   group The generated tag must belong to this group.  
227  * @return  The element of tag with given group which is fee.
228  */
229 guint32 gdcmElValSet::GenerateFreeTagKeyInGroup(guint16 group) {
230    for (guint32 elem = 0; elem < UINT32_MAX; elem++) {
231       TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
232       if (tagHt.count(key) == 0)
233          return elem;
234    }
235    return UINT32_MAX;
236 }
237
238 /**
239  * \ingroup gdcmElValSet
240  * \brief   
241  * @param   area
242  * @param   group 
243  * @param   element 
244  * @return  
245  */
246 int gdcmElValSet::SetVoidAreaByNumber(void * area,
247                                       guint16 group, guint16 element) {
248    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
249    if ( ! tagHt.count(key))
250       return 0;
251    tagHt[key]->SetVoidArea(area);        
252    return 1 ;           
253 }
254
255 /**
256  * \ingroup gdcmElValSet
257  * \brief   
258  * @param   length
259  * @param   group 
260  * @param   element 
261  * @return  int acts as a boolean
262  */
263 int gdcmElValSet::SetElValueLengthByNumber(guint32 length,
264                                            guint16 group, guint16 element) {
265    TagKey key = gdcmDictEntry::TranslateToKey(group, element);
266    if ( ! tagHt.count(key))
267       return 0;
268    tagHt[key]->SetLength(length);        
269    return 1 ;           
270 }
271 /**
272  * \ingroup gdcmElValSet
273  * \brief   
274  * @param   length
275  * @param   TagName
276  * @return  
277  */
278 int gdcmElValSet::SetElValueLengthByName(guint32 length, std::string TagName) {
279    if ( ! NameHt.count(TagName))
280       return 0;
281    NameHt.find(TagName)->second->SetLength(length);      
282    return 1 ;           
283 }
284
285 /**
286  * \ingroup gdcmElValSet
287  * \brief   Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
288  * @param   SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
289  * @param   type
290  */
291 void gdcmElValSet::UpdateGroupLength(bool SkipSequence, FileType type) {
292    guint16 gr, el;
293    std::string vr;
294    
295    gdcmElValue *elem;
296    char trash[10];
297    std::string str_trash;
298    
299    GroupKey key;
300    GroupHT groupHt;  // to hold the length of each group
301    TagKey tk;
302    // remember :
303    // typedef std::map<GroupKey, int> GroupHT;
304    
305    gdcmElValue *elemZ;
306   
307    // for each Tag in the DCM Header
308    
309    for (TagElValueHT::iterator tag2 = tagHt.begin(); 
310         tag2 != tagHt.end();
311         ++tag2){
312
313       elem  = tag2->second;
314       gr = elem->GetGroup();
315       el = elem->GetElement();
316       vr = elem->GetVR(); 
317                  
318       sprintf(trash, "%04x", gr);
319       key = trash;              // generate 'group tag'
320       
321       // if the caller decided not to take SEQUENCEs into account 
322       // e.g : he wants to write an ACR-NEMA File 
323                 
324       if (SkipSequence && vr == "SQ") continue;
325       
326          // Still unsolved problem :
327          // we cannot find the 'Sequence Delimitation Item'
328          // since it's at the end of the Hash Table
329          // (fffe,e0dd) 
330              
331          // pas SEQUENCE en ACR-NEMA
332          // WARNING : 
333          // --> la descente a l'interieur' des SQ 
334          // devrait etre faite avec une liste chainee, pas avec une HTable...
335             
336       if ( groupHt.count(key) == 0) { // we just read the first elem of a given group
337          if (el == 0x0000) {          // the first elem is 0x0000
338             groupHt[key] = 0;         // initialize group length 
339          } else {
340             groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
341          } 
342       } else {   // any elem but the first    
343          if (type == ExplicitVR) {
344             if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) {
345                groupHt[key] +=  4; // explicit VR AND OB, OW, SQ : 4 more bytes
346             }
347          }
348          groupHt[key] += 2 + 2 + 4 + elem->GetLength(); 
349       } 
350    }
351
352    unsigned short int gr_bid;
353   
354    for (GroupHT::iterator g = groupHt.begin(); // for each group we found
355         g != groupHt.end();
356         ++g){ 
357       // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
358       //        warning: unsigned int format, different type arg
359       sscanf(g->first.c_str(),"%x",&gr_bid);
360       tk = g->first + "|0000";                  // generate the element full tag
361                      
362       if ( tagHt.count(tk) == 0) {              // if element 0x0000 not found
363          gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");       
364          elemZ = new gdcmElValue(tagZ);
365          elemZ->SetLength(4);
366          Add(elemZ);                            // create it
367       } else {
368          elemZ=GetElementByNumber(gr_bid, 0x0000);
369       }     
370       sprintf(trash ,"%d",g->second);
371       str_trash=trash;
372       elemZ->SetValue(str_trash);
373    }   
374 }
375
376 /**
377  * \ingroup gdcmElValSet
378  * \brief   
379  * @param   type
380  * @param   _fp 
381  * @return  
382  */
383 void gdcmElValSet::WriteElements(FileType type, FILE * _fp) {
384    guint16 gr, el;
385    guint32 lgr;
386    const char * val;
387    std::string vr;
388    guint32 val_uint32;
389    guint16 val_uint16;
390    
391    vector<std::string> tokens;
392
393    void *ptr;
394
395    // Tout ceci ne marche QUE parce qu'on est sur un proc Little Endian 
396    // restent à tester les echecs en écriture (apres chaque fwrite)
397
398    for (TagElValueHT::iterator tag2=tagHt.begin();
399         tag2 != tagHt.end();
400         ++tag2){
401
402       gr =  tag2->second->GetGroup();
403       el =  tag2->second->GetElement();
404       lgr = tag2->second->GetLength();
405       val = tag2->second->GetValue().c_str();
406       vr =  tag2->second->GetVR();
407       
408      // cout << "Tag "<< hex << gr << " " << el << std::endl;
409
410       if ( type == ACR ) { 
411          if (gr < 0x0008)   continue; // ignore pure DICOM V3 groups
412          if (gr %2)         continue; // ignore shadow groups
413          if (vr == "SQ" )   continue; // ignore Sequences
414          if (gr == 0xfffe ) continue; // ignore delimiters
415       } 
416
417       fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp);  //group
418       fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp);  //element
419
420       if ( (type == ExplicitVR) && (gr <= 0x0002) ) {
421          // EXPLICIT VR
422          guint16 z=0, shortLgr;
423          fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
424
425          if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) {
426             fwrite ( &z,  (size_t)2 ,(size_t)1 ,_fp);
427             fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
428
429          } else {
430             shortLgr=lgr;
431             fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
432          }
433       } else { // IMPLICIT VR
434          fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
435       }
436
437       if (vr == "US" || vr == "SS") {
438          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
439          Tokenize (tag2->second->GetValue(), tokens, "\\");
440          for (unsigned int i=0; i<tokens.size();i++) {
441             val_uint16 = atoi(tokens[i].c_str());
442             ptr = &val_uint16;
443             fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
444          }
445          tokens.clear();
446          continue;
447       }
448       if (vr == "UL" || vr == "SL") {
449          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
450          Tokenize (tag2->second->GetValue(), tokens, "\\");
451          for (unsigned int i=0; i<tokens.size();i++) {
452             val_uint32 = atoi(tokens[i].c_str());
453             ptr = &val_uint32;
454             fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
455          }
456          tokens.clear();
457          continue;
458       }     
459       // Pixels are never loaded in the element !
460       if ((gr == 0x7fe0) && (el == 0x0010) ) break;
461
462       fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
463    }
464 }
465
466 /**
467  * \ingroup gdcmElValSet
468  * \brief   
469  * @param   _fp
470  * @param   type
471  * @return  
472  */
473 int gdcmElValSet::Write(FILE * _fp, FileType type) {
474
475    if (type == ImplicitVR) {
476       std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
477       SetElValueByNumber(implicitVRTransfertSyntax, 0x0002, 0x0010);
478       
479       //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
480       //      values with a VR of UI shall be padded with a single trailing null
481       //      Dans le cas suivant on doit pader manuellement avec un 0
482       
483       SetElValueLengthByNumber(18, 0x0002, 0x0010);
484    }  
485         // Question :
486         // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non ,
487         // (FileType est un champ de gdcmHeader ...)
488         // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
489         // no way
490         
491    if (type == ExplicitVR) {
492       std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
493       SetElValueByNumber(explicitVRTransfertSyntax, 0x0002, 0x0010);
494       // See above comment 
495       SetElValueLengthByNumber(20, 0x0002, 0x0010);
496    }
497
498    if ( (type == ImplicitVR) || (type == ExplicitVR) )
499       UpdateGroupLength(false,type);
500    if ( type == ACR)
501       UpdateGroupLength(true,ACR);
502
503    WriteElements(type, _fp);
504    return(1);
505 }