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