]> Creatis software - creaBruker.git/blob - lib/src1/bruker2dicom.cxx
*** empty log message ***
[creaBruker.git] / lib / src1 / bruker2dicom.cxx
1 #include "bruker2dicom.h"
2
3 #ifndef PATH_MAX // If not defined yet : do it 
4         #define PATH_MAX 2048
5 #endif 
6
7
8
9 bool Bruker2Dicom::Execute()
10 {
11    // ----- Begin Processing -----
12
13    bool bigEndian = GDCM_NAME_SPACE::Util::IsCurrentProcessorBigEndian();
14  
15    if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(InputDirName) )
16    {
17       std::cout << "KO : [" << InputDirName << "] is not a Directory." << std::endl;
18       return 0;
19    }
20    else
21    {
22       if (verbose)
23          std::cout << "OK : [" << InputDirName << "] is a Directory." << std::endl;
24    }
25
26    std::string strDirNameOut(OutputDirName); 
27    bool res=CreateDirectory(strDirNameOut);
28    if (!res) {
29       std::cout << "[" << OutputDirName << "] Directory creation failure " << std::endl;
30       exit (0);
31    }
32
33    std::string strDirNamein(InputDirName);
34    GDCM_NAME_SPACE::DirList dirList(strDirNamein, false, true); // DON'T get recursively the list of files
35    std::string strDirNameout(OutputDirName);   
36
37 /*   
38    if (listonly)
39    {
40       std::cout << "------------List of found files ------------" << std::endl;
41       dirList.Print();
42       std::cout << std::endl;
43       return 1;
44    }
45 */
46
47 //
48 // e.g : at level 0, in : B67d1.Bp1
49 //
50 //           1  2  3  4  5  6  AdjStatePerStudy  subject
51 //
52
53    GDCM_NAME_SPACE::DirListType fileNames;
54    fileNames = dirList.GetFilenames();
55    bool canOpen;
56    std::string outputFileName;
57
58   // BrukerDataSet br_subject;
59    std::string subject;
60    subject = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
61              GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
62              "subject";
63    if (verbose)
64         std::cout << " Subject : [" <<  subject << "]" << std::endl;
65    canOpen =br_subject.LoadFile(subject);
66
67    if (!canOpen)
68    {
69       std::cout << "Hopeless! no 'subject' found" << std::endl;
70       exit(0);  /// \TODO throw an exception !     
71    }
72    else
73    { 
74       br_subject.FillMap(); 
75    }
76    //br_subject.PrintSelf();
77
78   // get info for 'Study Description'
79   
80   /*
81          BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
82          acqp_protocol_location = b_protocol_location.GetStringValue()[0];
83          cleanString(acqp_protocol_location);
84 */
85          BrukerFieldData b_name=br_subject.GetFieldData("SUBJECT_name_string");
86          std::string subject_name = b_name.GetStringValue()[0];
87          strPatientName = subject_name;
88          cleanString(subject_name);
89          
90          BrukerFieldData b_entry=br_subject.GetFieldData("SUBJECT_entry");
91          std::string subject_entry = b_entry.GetStringValue()[0];
92          //cleanString(subject_entry);
93          subject_entry = subject_entry.substr(11, subject_entry.size()-11);
94          
95          BrukerFieldData b_position=br_subject.GetFieldData("SUBJECT_position");
96          std::string subject_position = b_position.GetStringValue()[0];
97          //cleanString(subject_position);
98          subject_position = subject_position.substr(9, subject_position.size()-9);
99                          
100          BrukerFieldData b_date=br_subject.GetFieldData("SUBJECT_date");
101          std::string subject_date = b_date.GetStringValue()[0];
102          strStudyTimeDate = subject_date;
103          cleanString(subject_date);
104          
105          BrukerFieldData b_study_name=br_subject.GetFieldData("SUBJECT_study_name");
106          std::string subject_study_name = b_study_name.GetStringValue()[0];
107          subject_study_name = subject_study_name.substr(1, subject_study_name.size()-2);         
108          cleanString(subject_date);
109          
110    strStudyDescr = subject_name + "-" + subject_study_name + "-" + subject_entry + "-" + subject_position + "-" + subject_date;
111                  
112    char outputDirName[(unsigned int) PATH_MAX+2];
113
114    strStudyUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
115    
116    // -----------------------------------------------------
117    // Iterate to ALL the objets(files/directories) found in the input directory
118    // (this is level ZERO)
119    // -----------------------------------------------------
120            
121    GDCM_NAME_SPACE::DirListType::iterator it;
122
123    for (it = fileNames.begin();
124          it != fileNames.end();
125        ++it)
126    {
127       if ( GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
128       { 
129          if (verbose)
130             std::cout << "[" << *it << "] is a directory" << std::endl;
131
132          //BrukerDataSet br_acqp;
133          std::string strAcqp;
134          strAcqp = (*it) +
135                    GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
136                    "acqp";
137
138          br_acqp.LoadFile(strAcqp);
139          br_acqp.FillMap();
140
141          std::string acqp_scan_name;
142          std::string acqp_method;
143          std::string acqp_protocol_location; 
144  
145          BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
146          acqp_protocol_location = b_protocol_location.GetStringValue()[0];
147          cleanString(acqp_protocol_location);
148     
149          BrukerFieldData b_scan_name=br_acqp.GetFieldData("ACQ_scan_name");
150          acqp_scan_name = b_scan_name.GetStringValue()[0];
151          cleanString(acqp_scan_name);
152   
153          BrukerFieldData b_method=br_acqp.GetFieldData("ACQ_method"); 
154          acqp_method = b_method.GetStringValue()[0]; 
155          cleanString(acqp_method);
156
157          BrukerFieldData b_list_size = br_acqp.GetFieldData("ACQ_O1_list_size");
158          b_list_size.PrintSelf(); //JP
159  
160          nbSlices =  b_list_size.GetIntValue()[0];
161
162          strSerieDescr = GDCM_NAME_SPACE::Util::GetName(*it)
163                          + "-" + acqp_protocol_location
164                          + "-" + acqp_scan_name
165                          + "-" + acqp_method.c_str();
166
167          sprintf(outputDirName, "%s%c%s", OutputDirName.c_str(), 
168                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
169                           strSerieDescr.c_str() );
170                           
171          std::cout << " ================================================================================\n"
172                    << " ========================= [" << GDCM_NAME_SPACE::Util::GetName(*it).c_str()
173                    << acqp_protocol_location.c_str()
174                    << acqp_scan_name.c_str()
175                    << acqp_method.c_str()
176                    << "]\n"
177                    << " ================================================================================"
178                    << std::endl;
179
180         if (verbose)
181            printf ("outputDirName [%s]\n", outputDirName);   
182
183         DealWithNiveau1(*it, outputDirName);
184       }
185    } // end of : for (GDCM_NAME_SPACE::DirListType::iterator it
186 }
187
188
189 // =====================================================================
190
191 void Bruker2Dicom::DealWithNiveau1(std::string level1Directory, std::string currentOutputDirName) {
192 //
193 // e.g. : at level 1, in B67d1.Bp1/6
194 //
195 // acqp  fid  imnd  pdata  pulseprogram  spnam0  spnam1
196
197    bool res = CreateDirectory(currentOutputDirName); 
198
199    if (!res) {
200       std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
201       exit (0);
202    }
203    GDCM_NAME_SPACE::DirList dirList(level1Directory, false, true); // DON'T get recursively the list of files
204    GDCM_NAME_SPACE::DirListType fileNames;
205    fileNames = dirList.GetFilenames();
206    // -----------------------------------------------------
207    // Iterate to ALL the objets(files/directories) found in the input directory
208    // -----------------------------------------------------
209    GDCM_NAME_SPACE::DirListType::iterator it;
210
211    for (it = fileNames.begin();
212         it != fileNames.end();
213       ++it)
214    {
215       if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
216       {
217          if (verbose)
218             std::cout << "--- [" << *it << "] is a file" << std::endl;
219       }  
220    }
221
222    char outputDirName[(unsigned int) PATH_MAX+2];
223    //std::string firstName;
224    bool canOpen;
225    for (it = fileNames.begin();
226         it != fileNames.end();
227       ++it)
228    {
229       if ( GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
230       {
231          // will be always "pdata" ...
232          if (verbose)
233             std::cout << "--- [" << *it << "] is a directory" << std::endl;
234
235               /* a recuperer :
236               if (FileLine.startsWith("##$ACQ_size=")) {
237               if (FileLine.startsWith("##$NI=")) {
238               if (FileLine.startsWith("##$NR=")) {
239               if (FileLine.startsWith("##$ACQ_obj_order=")) {
240               if (FileLine.startsWith("##$ACQ_word_size=")) {
241               if (FileLine.startsWith("##$BYTORDA=")) {
242               if (FileLine.startsWith("##$PULPROG=")) {
243               */
244
245          sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
246                                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
247                                           GDCM_NAME_SPACE::Util::GetName(*it).c_str());
248          //br1.PrintSelf();
249
250           std::string strMethod;
251           //std::string firstName = *(fileNames.begin());
252
253           strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin())) +
254                       GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
255                       "method";
256             // std::cout << "---strMethod (for method)=> [" << strMethod << "]" << std::endl;        
257           canOpen = br_method.LoadFile(strMethod);
258           if (!canOpen)
259           {
260              strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
261                          GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
262                          "imnd";
263              //std::cout << "---strMethod (for imnd) => [" << strMethod << "]" << std::endl;
264              canOpen = br_method.LoadFile(strMethod);
265              if (!canOpen)
266              {
267                 std::cout << "Hopeless! neither 'method' nor 'imnd' found" << std::endl;
268                 exit(0);  /// \TODO throw an exception !
269              }
270           }
271           if (verbose)
272              std::cout << "open => [" << strMethod << "] successfully" << std::endl; 
273           br_method.FillMap();
274
275           /* a recuperer :
276              ##$PVM_Fov (dimension)
277           */
278   /*
279           dans method (pour perfusion  seulement?) :
280           ##$PVM_ObjOrderList=( 8 )
281           0 2 4 6 1 3 5 7
282           ##$PVM_NSPacks=2
283           ##$PVM_SPackArrNSlices=( 2 )
284           7 1  
285   */    
286          DealWithNiveau2(*it,outputDirName );
287       }
288    }
289 }
290
291 // =====================================================================
292
293 void Bruker2Dicom::DealWithNiveau2(std::string level2Directory, std::string currentOutputDirName) {
294   
295 // e.g. : at level 2 in B67d1.Bp1/6/pdata
296 //
297 // acqp  fid  imnd  pdata  pulseprogram  spnam0  spnam1
298 //
299
300    bool res = CreateDirectory(currentOutputDirName); 
301
302    if (!res) {
303       std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
304       exit (0);
305    }
306   
307    GDCM_NAME_SPACE::DirList dirList(level2Directory, false, true); // DON'T get recursively the list of files
308
309    GDCM_NAME_SPACE::DirListType fileNames;
310    fileNames = dirList.GetFilenames();
311
312    char outputDirName[(unsigned int) PATH_MAX+2];
313
314    // -----------------------------------------------------
315    // Iterate to ALL the objets(files/directories) found in the input directory
316    // -----------------------------------------------------
317    GDCM_NAME_SPACE::DirListType::iterator it;
318    bool canOpen;
319
320    if (verbose)
321    for (it = fileNames.begin();
322         it != fileNames.end();
323       ++it)
324    {
325       if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
326       { 
327          std::cout << "--- --- [" << *it << "] is a file" << std::endl;
328       }
329       
330    }
331   
332    for (it = fileNames.begin();
333          it != fileNames.end();
334        ++it)
335    {
336       if ( GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
337       { 
338   
339          if (verbose)
340             std::cout << "--- --- [" << *it << "] is a directory" << std::endl;
341  
342         // sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(), 
343         //                          GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
344         //                                GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
345   // MUST be 'pdata'!
346
347 //
348 // (interest of previous method :
349 // If unaware user changed the pdata name, it goes on working   
350 //
351           std::string str_isa;
352           str_isa = (*it) + 
353                     GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
354                    "isa";
355
356           std::string str_isa_func_name;    
357           canOpen = br_isa.LoadFile(str_isa);
358           if (!canOpen)
359           {
360              sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(), 
361                                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
362                                           GDCM_NAME_SPACE::Util::GetName(*it).c_str() );        
363           }
364           else
365           {
366              br_isa.FillMap();
367              BrukerFieldData b_isa_func_name = br_isa.GetFieldData("ISA_func_name");
368     
369              str_isa_func_name = b_isa_func_name.GetStringValue()[0];
370              cleanString(str_isa_func_name);
371
372              sprintf(outputDirName, "%s%c%s-%s", currentOutputDirName.c_str(), 
373                                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
374                                           GDCM_NAME_SPACE::Util::GetName(*it).c_str(),
375              str_isa_func_name.c_str());
376           } 
377           DealWithNiveau3(*it, outputDirName);
378       }
379    }
380 }
381
382
383 //
384 // =====================================================================
385 //
386
387 void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string currentOutputDirName){
388
389 //
390 // e.g. at level 3, in
391
392    // just to be able to go on checking // JP
393    if ( GDCM_NAME_SPACE::Util::GetName(level3Directory) != "1")
394       return;
395
396    bool res = CreateDirectory(currentOutputDirName);
397
398    if (!res)
399    {
400       std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
401       exit (0);
402    }
403
404    GDCM_NAME_SPACE::DirList dirList(level3Directory, false, true); // DON'T get recursively the list of files
405    GDCM_NAME_SPACE::DirListType::iterator it;
406    GDCM_NAME_SPACE::DirListType fileNames;
407    fileNames = dirList.GetFilenames();
408
409    char original2dseqName       [(unsigned int) PATH_MAX+2];
410    char currentOutputMhdDirName [(unsigned int) PATH_MAX+2];
411
412    char outputMhdFileName       [(unsigned int) PATH_MAX+2];
413    char output2dseqSliceFileName[(unsigned int) PATH_MAX+6]; // think about extra '.dcm'
414    char output2dseqName         [(unsigned int) PATH_MAX+6];
415    char output2dseqCartoName    [(unsigned int) PATH_MAX+6];
416
417    char copyFile[PATH_MAX + PATH_MAX + 5]; // Should be enough!
418    bool canOpen;
419  
420    //-------------- try d3proc;
421    char char_d3proc[(unsigned int) PATH_MAX+2];
422
423    sprintf(char_d3proc,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"d3proc" );     
424    
425    if (verbose)
426       std::cout << "--- => [" << char_d3proc << "]" << std::endl;
427    std::string str_d3proc(char_d3proc);       
428    canOpen = br_d3proc.LoadFile(str_d3proc);
429
430    if (!canOpen)
431    {
432       std::cout << "Hopeless! no 'd3proc' found" << std::endl;
433       exit(0);  /// \TODO throw an exception ! 
434    }
435
436    canOpen = br_d3proc.FillMap();
437    if (!canOpen)
438    {
439       std::cout << "Hopeless! FillMap failed on 'd3proc'" << std::endl;
440       exit(0);  /// \TODO throw an exception !     
441    }
442  
443    //-------------- end try d3proc;
444     
445  
446  // -------------------try reco
447
448    char char_reco[(unsigned int) PATH_MAX+2];
449
450    sprintf(char_reco,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );     
451     //str_d3proc = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
452     //             GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
453     //             "d3proc";
454    if (verbose)
455       std::cout << "--- => [" << char_reco << "]" << std::endl;
456    std::string str_reco(char_reco);       
457    canOpen = br_reco.LoadFile(str_reco);
458
459    if (!canOpen) // we try in directory ../1
460    {
461       if (verbose)
462          std::cout << "[" << str_reco << "] not found " << std::endl;
463       std::string lastDirName = GDCM_NAME_SPACE::Util::GetPath(level3Directory);
464       //lastDirName = GDCM_NAME_SPACE::Util::GetPath(lastDirName);
465       sprintf(char_reco,"%s%c1%c%s", lastDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
466       str_reco=char_reco;
467       canOpen = br_reco.LoadFile(str_reco);
468       if (!canOpen)
469       {
470          std::cout << "Hopeless! cannot find 'reco' in [" << str_reco << "]"  << std::endl;
471          exit(0);  /// \TODO throw an exception !    
472       }
473    }
474
475    canOpen = br_reco.FillMap();
476    if (!canOpen)
477    {
478       std::cout << "Hopeless! FillMap failed on [" << str_reco << "]" << std::endl;
479       exit(0);  /// \TODO throw an exception !     
480    }
481    //std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
482    // br_reco.PrintSelf();
483    // std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
484        
485    // -------------------end try reco
486
487
488    BrukerFieldData bX = br_d3proc.GetFieldData("IM_SIX");
489    int NX = bX.GetIntValue()[0];
490
491    std::cout << "IM_SIX " << NX << std::endl;
492    BrukerFieldData bY=br_d3proc.GetFieldData("IM_SIY"); 
493    int NY = bY.GetIntValue()[0];
494
495    std::cout << "IM_SIY " << NY << std::endl;
496    /// \todo : check if there are actually 3 dimensions or only 2
497   
498    BrukerFieldData bZ= br_d3proc.GetFieldData("IM_SIZ");
499    int nbFrames = bZ.GetIntValue()[0]; 
500    std::cout << "IM_SIZ " << nbFrames << std::endl;
501
502         // WARNING DATTYPE is, either in {ip_short, ip_int, ip_char, ...}, or in {1, 2, 3, ...}
503  
504    BrukerFieldData bDPT = br_d3proc.GetFieldData("DATTYPE");
505  
506    std::string mhdDataPixelType;
507    int pixelSize;
508    getImhDataType(bDPT, mhdDataPixelType, pixelSize);
509  
510    BrukerFieldData fov = br_method.GetFieldData("PVM_Fov");
511    double fovX = fov.GetDoubleValue()[0];
512    double fovY = fov.GetDoubleValue()[1];
513    if (verbose)
514       std::cout << "FOV (ds method) " << fovX << " " << fovY << std::endl;
515
516    /// \TODO probabely a more sophisticated accessor will be necessary :
517    ///  (cf : non contiguous slices, overlapping, slice thickness, space between clices, etc)
518    BrukerFieldData bsliceDistance = br_method.GetFieldData("PVM_SPackArrSliceDistance");
519    double sliceDistance = bsliceDistance.GetDoubleValue()[0];
520
521    if (mhd)
522    {
523       sprintf(currentOutputMhdDirName, "%s%c%s", currentOutputDirName.c_str(),
524                                GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "MhdFiles");
525       res = CreateDirectory( currentOutputMhdDirName );
526       if (!res) {
527          std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
528          exit (0);
529       } 
530
531       if (verbose)
532          std::cout << "Directory creation [" <<  currentOutputDirName << "]" << std::endl;
533    }  // end if mhd
534
535    std::cout << "nbFrames " << nbFrames << std::endl;
536    std::cout << "nbSlices " << nbSlices << std::endl;
537    int k;
538    int nbInstants = nbFrames/nbSlices;
539    std::cout << "nbInstants (deduced )" << nbInstants << std::endl;    
540    int instantNb;
541    int sliceNb; 
542    FILE *fp;  // for MHD files
543
544    sprintf( original2dseqName, "%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "2dseq");
545
546 /**/   
547   // \TODO : tenir compte du bazar precedent 
548
549     // load 2dseq in memory
550
551    fp = fopen(original2dseqName, "rb");
552    if (!fp) 
553    {
554       std::cout << "Cannot open [" << original2dseqName << "] for reading" << std::endl;
555       exit (0);
556    }
557    
558    unsigned char * buffer_2dseq = new unsigned char[NX*NY*pixelSize*nbSlices*nbInstants];   
559    ///\ TODO : find a safer way to be sure to read everything!
560    size_t lgr = fread(buffer_2dseq, 1, NX*NY*pixelSize*nbSlices*nbInstants, fp);
561
562    // This one will be important!
563    // ---------------------------
564    imageSet = CreateImageSet ( );
565    
566    strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
567    if (nbInstants==1) // creer un seul fichier .mhd  pour toutes les Slices! (images natives)
568    {
569        std::cout << "Single instant : do not split" << std::endl;
570        if (mhd)
571        {
572              sprintf(outputMhdFileName, "%s%cMhdData_Toutes_les_Slices.mhd", currentOutputMhdDirName,
573                                          GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
574              fp=fopen(outputMhdFileName, "w");
575              if (!fp)
576              {
577                 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
578                 exit(0);
579              }
580              else
581              {
582                fprintf(fp, "ObjectType = Image\n");
583                fprintf(fp, "NDims = 3\n" );
584                fprintf(fp, "BinaryData = True \n" );
585                fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
586                fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices );
587                fprintf(fp, "HeaderSize = %d\n", 0);
588                fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
589                fprintf(fp, "Position = 0 0 %d\n", 0 );
590                fprintf(fp, "Offset = 0 0 0\n" );
591                fprintf(fp, "CenterOfRotation = 0 0 0\n" );
592                fprintf(fp, "ElementNumberOfChannels = 1\n" );
593                fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );  
594                fprintf(fp, "ElementDataFile = %s\n", "../2dseq_toutes_les_Slices" );
595                fclose(fp);     
596              }
597              sprintf(output2dseqSliceFileName, "%s%c2dseq_toutes_les_Slices", 
598                                        currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
599              fp=fopen(output2dseqSliceFileName, "wb");
600              if (!fp)
601              {
602                 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
603              }
604              else
605              {
606                 fwrite( buffer_2dseq, NX*NY*pixelSize, nbSlices, fp);     
607              }
608              fclose(fp);
609              strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
610        }  // end if mhd
611        if (dicom)
612        {
613              sprintf(output2dseqSliceFileName, "%s%c2dseq_toutes_les_Slices.dcm", 
614                                        currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
615               
616             /* ----------- Write Dicom Image  ---------------*/
617              MakeDicomImage(buffer_2dseq,
618                NX,
619                NY,
620                nbFrames,
621                pixelSize,
622                fovX/NY, fovY/NY, sliceDistance,
623                output2dseqSliceFileName,
624                strPatientName,
625                day,
626                strStudyUID,
627                strSerieUID,
628                strStudyDescr,
629                strSerieDescr,
630                strStudyTimeDate,
631                0,// index frame number
632                GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
633              );
634        }  // end if dicom
635    }  // end if nbInstants = 1
636    
637    else  // more than ONE instant
638    {
639           // Interleaved !
640           // it's (slice1,slide2, ...)t1 ; (slice1,slide2, ...)t2 ; ...
641
642          unsigned char * pixelsForCurrentSlice = new unsigned char[NX*NY*pixelSize*nbInstants];
643
644          k = 0;
645          for (sliceNb=0; sliceNb<nbSlices; sliceNb++)
646          {
647             if (mhd)
648             {
649                sprintf(outputMhdFileName, "%s%cMhdData_%03d.mhd", currentOutputMhdDirName, 
650                                         GDCM_NAME_SPACE::GDCM_FILESEPARATOR, k  );
651                if (verbose)
652                   std::cout << "--- Output MHD file [" << outputMhdFileName << "]" << std::endl;
653                fp=fopen(outputMhdFileName, "w");
654                if (!fp)
655                {
656                    std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
657                    exit(0);
658                }
659                else
660                {
661             /* ----------- Write MHD Image  ---------------*/
662                 //if (verbose)
663                 //   std::cout << "Open sucessfully[" << outputMhdFileName << "] for writting" << std::endl; 
664                    fprintf(fp, "ObjectType = Image\n");
665                    fprintf(fp, "NDims = 3\n" );  
666                    fprintf(fp, "BinaryData = True \n" );  
667                    fprintf(fp, "BinaryDataByteOrderMSB = False\n" );    
668                    fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbInstants);  
669                    fprintf(fp, "HeaderSize = %d\n", 0); 
670                    fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, 1.0 ); // slice distance : no meaning for temporal serie
671                    fprintf(fp, "Position = 0 0 %d\n", sliceNb );  
672                    fprintf(fp, "Offset = 0 0 0\n" );  
673                    fprintf(fp, "CenterOfRotation = 0 0 0\n" );
674                    fprintf(fp, "ElementNumberOfChannels = 1\n" );  
675                    fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );  
676                    fprintf(fp, "ElementDataFile = ..%c2dseq_Slice_%d\n", GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb ); 
677                    fclose(fp);
678                } // end write MHD
679
680                sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d", 
681                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,sliceNb);
682                fp=fopen(output2dseqSliceFileName, "wb");
683                if (!fp)
684                {     
685                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
686                    exit (0);
687                }
688                int frameSize = NX*NY*pixelSize;
689                for (instantNb=0; instantNb<nbInstants; instantNb++)
690                {
691 // std::cout << "------------SN " << sliceNb << " IN " << instantNb <<  " T " << nbSlices*instantNb + sliceNb << std::endl;
692                     fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
693                             frameSize,
694                             1, fp);
695                }
696                fclose(fp);
697 // std::cout << "end writting[" << output2dseqSliceFileName << "]" << std::endl;
698             }  // end if mhd
699             
700             if (dicom)
701             {
702                // desperate try !
703                /* 
704                sprintf(output2dseqSliceFileName, "%sdummy_buffer", 
705                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
706                fp=fopen(output2dseqSliceFileName, "wb");
707                if (!fp)
708                {     
709                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
710                    exit (0);
711                }
712                int frameSize = NX*NY*pixelSize;
713                for (instantNb=0; instantNb<nbInstants; instantNb++)
714                {
715 // std::cout << "------------SN " << sliceNb << " IN " << instantNb <<  " T " << nbSlices*instantNb + sliceNb << std::endl;
716                     fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
717                             frameSize,
718                             1, fp);
719                }
720                fclose(fp);
721                
722                fp=fopen(output2dseqSliceFileName, "rb");
723                if (!fp)
724                {     
725                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for reading" << std::endl;
726                    exit (0);
727                }               
728                fread( pixelsForCurrentSlice,
729                             frameSize*nbInstants,
730                             1, fp);
731                fclose(fp);
732               // end of desperate try !
733                */
734
735                /* ----------- Write Dicom Image  ---------------*/
736                
737                int frameSize = NX*NY*pixelSize;
738                for (instantNb=0; instantNb<nbInstants; instantNb++)
739                {
740                   memcpy(pixelsForCurrentSlice + frameSize*instantNb, buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize, frameSize);
741                }
742
743                int indOfFirsImageWithinImageSet =  nbSlices*instantNb;
744                sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d.dcm", 
745                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb);
746
747                MakeDicomImage(
748                   pixelsForCurrentSlice,
749                   NX,
750                   NY,
751                   nbInstants,
752                   pixelSize,
753                   fovX/NY, fovY/NY, sliceDistance,
754                   output2dseqSliceFileName,
755                   strPatientName,
756                   day,
757                   strStudyUID,
758                   strSerieUID,
759                   strStudyDescr,
760                   strSerieDescr,
761                   strStudyTimeDate,
762                   sliceNb*nbInstants,
763                   GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
764                );
765                if (verbose)
766                   std::cout << "--- Output DCM file [" << output2dseqSliceFileName << "]" << std::endl;      
767
768             } // en if dicom
769
770         k++;
771         }
772         delete [] pixelsForCurrentSlice;  
773      }  // end nbInstants == 1
774    delete [] buffer_2dseq;
775 /**/
776   
777  
778    // -----------------------------------------------------
779    //  deal with MatLab-generated Carto file.
780    // -----------------------------------------------------
781    
782    dealWithCarto(fileNames,  NX,  NY,  nbSlices, fovX, fovY, sliceDistance,
783                    copyFile, currentOutputDirName, outputMhdFileName, output2dseqCartoName);
784 }
785
786
787 // ===========================================================================================
788
789 void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX, int NY, int nbSlices, 
790                                  double fovX, double fovY, double sliceDistance,
791                                  char *copyFile, std::string &currentOutputDirName, 
792                                  char *outputMhdFileName, char *output2dseqCartoName)
793 {
794    // -----------------------------------------------------
795    //  deal with MatLab-generated Carto file.
796    // -----------------------------------------------------
797    
798    char *code[] ={ "ADC", "adc", "TTP", "ttp", "PEAK", "peak" , ""};  // add more carto file name identifiers if necessary; end with ""
799    int icode; 
800    GDCM_NAME_SPACE::DirListType::iterator it;
801    char file_name_ident[500];
802    FILE *fp;
803       
804    // Iterate to ALL the objets(files/directories) found in the input directory    
805    for (it = fileNames.begin();
806         it != fileNames.end();
807       ++it)
808    {
809       if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(*it) )
810       {         
811          if (verbose)
812             std::cout << "--- [" << *it << "] is a file" << std::endl;
813
814          icode = 0;
815
816          while (code[icode][0] != 0)
817          {
818             sprintf(file_name_ident, "2dseq_%s",code[icode]); // e.g  "2dseq_ADC"
819             std::string::size_type loc = (*it).rfind(file_name_ident); 
820
821             if ( loc != std::string::npos )
822             {
823  
824        ///\ TODO : find a safer way to be sure to read everything!
825               unsigned char *buffer_carto = new unsigned char[NX*NY*sizeof(double)*nbSlices];
826               fp = fopen ( (*it).c_str(), "rb");
827               if (!fp){
828                  std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
829
830                }
831                fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
832
833                std::cout << "Deal with Carto file :[" <<*it << "], computed length : "
834                          << NX*NY*sizeof(double)*nbSlices << std::endl;
835                   std::string lastFileName = GDCM_NAME_SPACE::Util::GetName((*it).c_str());
836                if (mhd)
837                {
838                   // Copy the data file in the new directory
839                   sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
840                             currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str()); 
841                   system(copyFile);
842                   sprintf(outputMhdFileName, "%s%c%s%s",
843                                        currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".mhd" );
844                   if (verbose)
845                     std::cout << "--- Output Carto MHD file [" << outputMhdFileName << "]" << std::endl;
846  
847                   FILE *fp;
848                   fp=fopen(outputMhdFileName, "w");
849                   if (!fp)
850                   {
851                      std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
852                   }
853                   else
854                   {
855                      fprintf(fp, "ObjectType = Image\n");
856                      fprintf(fp, "NDims = 3\n" );
857                      fprintf(fp, "BinaryData = True \n" );
858                      fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
859                      fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices);
860                      fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
861                      fprintf(fp, "HeaderSize = %d\n", 0 );
862                      fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
863                      fprintf(fp, "Position = 0 0 0\n" );
864                      fprintf(fp, "Offset = 0 0 0\n" );
865                      fprintf(fp, "CenterOfRotation = 0 0 0\n" );
866                      fprintf(fp, "ElementNumberOfChannels = 1\n" );
867                      fprintf(fp, "ElementType = %s\n", "MET_DOUBLE" );
868                      fprintf(fp, "ElementDataFile = %s\n", lastFileName.c_str() );
869
870                      fclose(fp);
871                   }
872                   if (verbose)
873                      std::cout << "--- end write Carto MHD file [" << outputMhdFileName << "]" << std::endl;
874                }  // end if mhd
875
876             // ----------- Write Dicom Image  ---------------
877
878                if (dicom)
879                {
880                   sprintf(output2dseqCartoName, "%s%c%s%s",
881                                        currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".dcm" );
882                   if (verbose)
883                      std::cout << "--- end create name output2dseqCartoName file [" << output2dseqCartoName << "]" << std::endl;
884
885                   strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID(); //New SerieUID for each carto.
886                   std::string strNewSerieDescr(strSerieDescr+ "_" +GDCM_NAME_SPACE::Util::GetName((*it).c_str()));
887                   MakeDicomImage(buffer_carto,
888                      NX,
889                      NY,
890                      nbSlices,
891                      8, // pixelSize
892                      fovX/NY, fovY/NY, sliceDistance,
893                      output2dseqCartoName,
894                      strPatientName,
895                      day,
896                      strStudyUID,
897                      strSerieUID,
898                      strStudyDescr,
899                      strNewSerieDescr,
900                      strStudyTimeDate,
901                      0,
902                      GDCM_NAME_SPACE::CREATED_IMAGE
903                   );
904                }  // end if dicom
905
906                delete [] buffer_carto;
907                if (verbose) 
908                      std::cout << "--- End writing Carto DICOM file [" << output2dseqCartoName << "]" << std::endl;
909                break; // don't check for more ident on same file name!
910
911             }
912             icode++;
913          } 
914       }
915    } // end iterate on files
916 }
917
918
919 // ==========================================================================================================
920   
921 bool Bruker2Dicom::CreateDirectory(std::string OutputDirName)
922 {
923    std::string systemCommand;
924    
925    if (verbose)
926       std::cout << "Check for output directory :[" << OutputDirName << "]."
927                 <<std::endl;
928    if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(OutputDirName) )    // dirout not found
929    {
930       std::string strDirNameout(OutputDirName);          // to please gcc 4
931       systemCommand = "mkdir " + strDirNameout;        // create it!
932       if (verbose)
933          std::cout << systemCommand << std::endl;
934       system (systemCommand.c_str());
935       if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(OutputDirName) ) // be sure it worked
936       {
937          if (verbose) 
938             std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
939          return 0;
940          /// \todo : THROW AN EXCEPTION
941       }
942       else
943       {
944          if (verbose) 
945            std::cout << "Directory [" << OutputDirName << "] created." << std::endl;
946       }
947    }
948    else
949    {
950        if (verbose)
951           std::cout << "Output Directory [" << OutputDirName << "] already exists; Used as is." << std::endl;
952    }
953    
954    return 1;
955
956 }
957
958
959 // ===========================================================================================
960
961 /// \TODO move cleanString to 'crea' ?
962
963 void Bruker2Dicom::cleanString(std::string &s)
964 {
965    int l = s.size();
966    if (s[l-1] == 0x0A || s[l-1] == 0x0D ) // CR or NL
967    {
968       l--;
969       s = s.substr(0, l);
970    }
971    if (s[l-1] == ' ' ) // blank space
972    {
973       l--;
974       s = s.substr(0, l);
975    }   
976    
977    if (s[0] == '<')      
978       s= s.substr(1,l-2);
979    std::string repChar("_");   
980    GDCM_NAME_SPACE::Util::ReplaceSpecChar(s, repChar);
981 }
982
983
984
985 // ===========================================================================================
986
987
988 void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPixelType, int &pixelSize)
989
990    if(bDPT.GetDataType() == "string")
991    {         
992          std::string brukerDataPixelType = bDPT.GetStringValue()[0];
993          std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
994          //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
995          
996          if (brukerDataPixelType ==  "ip_short") {
997             mhdDataPixelType = "MET_USHORT";
998             pixelSize = 2;
999          }
1000          if (brukerDataPixelType ==  "ip_int") {
1001             mhdDataPixelType = "MET_UINT";
1002             pixelSize = 4;
1003          }
1004          if (brukerDataPixelType ==  "ip_char") {
1005              mhdDataPixelType = "MET_UCHAR";
1006              pixelSize = 1;
1007          }
1008                   /// \TODO : finish the list
1009     /*
1010     case 0 : fp << "ElementType = MET_CHAR" << std::endl;
1011       break;
1012     case 1 : fp << "ElementType = MET_UCHAR" << std::endl;
1013       break;
1014     case 2 : fp << "ElementType = MET_SHORT" << std::endl;
1015       break;
1016     case 3 : fp << "ElementType = MET_USHORT" << std::endl;
1017       break;
1018     case 4 : fp << "ElementType = MET_INT" << std::endl;
1019       break;
1020     case 5 : fp << "ElementType = MET_UINT" << std::endl;
1021       break;
1022     case 6 : fp << "ElementType = MET_FLOAT" << std::endl;
1023       break;
1024     case 7 : fp << "ElementType = MET_DOUBLE" << std::endl;  
1025     */
1026     }
1027     else
1028     {
1029          int brukerDataPixelType = bDPT.GetIntValue()[0];
1030          std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
1031          //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1032  
1033 // Cross your fingers !!!
1034
1035 // pb : found values : 2, 3, 5
1036          
1037          if (brukerDataPixelType ==  2) {
1038             mhdDataPixelType = "MET_USHORT";
1039             pixelSize = 2;
1040          }
1041          if (brukerDataPixelType ==  3) {
1042             mhdDataPixelType = "MET_USHORT";
1043             pixelSize = 2;
1044          }    
1045          if (brukerDataPixelType ==  1) {
1046             mhdDataPixelType = "MET_UCHAR";
1047             pixelSize = 1;
1048          }     
1049     }
1050 }
1051
1052 // ===========================================================================================
1053
1054 std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
1055 {
1056          std::vector<BrukerImage> imageSet;      
1057          br_acqp.SetLoopStructure();
1058          std::vector<int> tempVect                      = br_acqp.GetLoopStructure() ;
1059          std::map<std::string, BrukerFieldData> map     = br_acqp.GetBrukerHeaderMap();
1060          bool result                                    = br_acqp.ObjectVaryingProperties.init(map,tempVect);
1061
1062          br_acqp.SetImageLoopStructure();
1063          br_acqp.SetBrukerImageList();
1064          std::vector<std::vector<int> > brukerImageList = br_acqp.GetBrukerImageList();
1065
1066          BrukerImage image(br_acqp,br_reco);
1067          image.Init(br_acqp,br_reco,1); 
1068  
1069          for(int i=0;i<brukerImageList.size();i++)
1070          {
1071             image.Init(br_acqp,br_reco,i);    
1072             imageSet.push_back(image);
1073          }
1074  
1075  // Just for checking
1076  /*
1077  
1078          std::vector<std::vector <double> > imageOrientation;
1079          std::vector <double> imagePosition; 
1080          for(int i=0;i<brukerImageList.size();i++)
1081          {
1082            // fread(buffer_2dseq, NX*NY*pixelSize*nbSlices*nbInstants, 1, fp);   
1083    
1084            imagePosition = imageSet[i].getTranslationVectorRPS2XYZ();
1085            std::cout << "Position " << imagePosition[0] << " " 
1086                      << imagePosition[1] << " "  << imagePosition[2] ;
1087            imageOrientation =  imageSet[i].getRotationMatrixRPS2XYZ();
1088            std::cout << "\t  Orientation " ;
1089            for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
1090               std::cout << imageOrientation[i1][i2] << " ";
1091        
1092            //std::cout << "\t  Abs Time " << imageSet[i].getAbsoluteTimePosition();
1093            std::cout << "\t  Relat Time " << imageSet[i].getRelativeTimePosition();
1094
1095            std::cout << "\t [";
1096            for (int i3=0; i3<imageSet[i].getLoopStamp().size();i3++)
1097               std::cout << " " << imageSet[i].getLoopStamp()[i3];
1098            std::cout << "]" << std::endl;       
1099          } 
1100 */
1101    return imageSet;
1102 }
1103
1104
1105 // ===========================================================================================
1106
1107 void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels, 
1108               int X, 
1109               int Y,
1110               int nbFrames,
1111               int pixelSize,
1112               double spacingX, double spacingY, double sliceDistance, 
1113               std::string dcmImageName,
1114               const std::string &patientName,
1115               const char *day,
1116               std::string &studyUID,
1117               std::string &serieUID,
1118               std::string &studyDescr,
1119               std::string &serieDescr,
1120               std::string &strStudyTimeDate,
1121               int imgNum,
1122               GDCM_NAME_SPACE::ImageContentType contentType 
1123       )
1124 {  
1125    std::ostringstream str;
1126
1127    GDCM_NAME_SPACE::File *file;
1128    file = GDCM_NAME_SPACE::File::New();       
1129       
1130   // Set the image size
1131    str.str(""); 
1132    str << X;
1133    file->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
1134    str.str("");
1135    str << Y;
1136    file->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
1137
1138    if (nbFrames != 1)
1139    {
1140       str.str("");
1141       str << nbFrames;
1142       file->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames  
1143    }
1144
1145   // Set the pixel type
1146   //      //8, 16, 32, 64 (for double ?)
1147    str.str("");
1148    str << pixelSize*8;     
1149    file->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
1150
1151    file->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
1152
1153    str.str("");
1154    str << pixelSize*8-1;     
1155    file->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
1156
1157   // Set the pixel representation // 0/1 , 0=unsigned
1158    file->InsertEntryString("1",0x0028,0x0103, "US"); // Pixel Representation
1159    
1160   // Set the samples per pixel // 1:Grey level, 3:RGB
1161    file->InsertEntryString("1",0x0028,0x0002, "US"); // Samples per Pixel
1162
1163 //  0028 0030 DS 2 Pixel Spacing
1164    str.str("");
1165    str << spacingX << "\\" << spacingY;
1166    file->InsertEntryString(str.str(),0x0028,0x0030, "DS"); // Pixel Spacing     
1167    
1168  //   0018 0050 DS 1 Slice Thickness 
1169    str.str("");    
1170    str << sliceDistance;
1171    file->InsertEntryString(str.str(),0x0018,0x0050, "DS");     
1172      
1173   // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
1174  //  file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
1175   // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI");  // [SOP Class UID]
1176
1177
1178 // OK : MR is NOT multiframe, but I want just a quick an dirty solution
1179 // 1.2.840.10008.5.1.4.1.1.4         MR Image Storage
1180    file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
1181    file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI");  // [SOP Class UID]     
1182
1183   // if (strlen(patientName) != 0)
1184    file->InsertEntryString(patientName.c_str(),0x0010,0x0010, "PN"); // Patient's Name
1185
1186    file->InsertEntryString(studyUID, 0x0020, 0x000d, "UI");
1187    file->InsertEntryString(serieUID, 0x0020, 0x000e, "UI");
1188    
1189 //  0008 0020 DA 1 Study Date
1190 //  0008 0030 TM 1 Study Time
1191
1192 /// \TODO split into 2 strings!
1193    file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
1194    file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),0x0008,0x0030, "TM");
1195
1196    file->InsertEntryString(studyDescr,0x0008,0x1030, "LO");  // Study Description  
1197    file->InsertEntryString(serieDescr,0x0008,0x103e, "LO");  // Series Description 
1198
1199 //0008|0060 [CS] [Modality] 
1200    file->InsertEntryString("MR",0x0008,0x0060, "CS");
1201
1202 // 0020 0037 DS 6 Image Orientation (Patient)
1203    char charImageOrientation[256];
1204
1205 /*
1206 std::cout << "try charImageOrientation  " << 
1207                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0] << " " <<
1208                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1] << " " <<
1209                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2] << " " <<
1210                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0] << " " <<
1211                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1] << " " <<
1212                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] << std::endl ;
1213 */      
1214    sprintf(charImageOrientation,"%f\\%f\\%f \\ %f\\%f\\%f",
1215                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0],
1216                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1],
1217                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2],
1218                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0],
1219                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1],
1220                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] ) ;
1221     
1222    file->InsertEntryString(charImageOrientation,0x0020,0x0037, "DS");
1223
1224
1225 // 0020 0032 DS 3 Image Position (Patient) 
1226
1227    char charImagePosition[256];   
1228    sprintf(charImagePosition,"%f\\%f\\%f", 
1229                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[0], 
1230                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[1],
1231                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[2]);
1232   
1233    file->InsertEntryString(charImagePosition,0x0020,0x0032, "DS");  //0020 0032 DS 3 Image Position (Patient) 
1234          
1235
1236
1237 // 0020 0x1041 DS 1 Slice Location 
1238 //        sprintf(charImagePosition,"%f",float(imgNum));
1239 //        file->InsertEntryString(charImagePosition,0x0020,0x1041, "DS");   
1240 /*
1241   // Set Rescale Intercept
1242         str.str("");
1243         str << div;  
1244         file->InsertEntryString(str.str(),0x0028,0x1052,"DS");
1245
1246   // Set Rescale Slope
1247         str.str("");
1248         str << mini;  
1249         file->InsertEntryString(str.str(),0x0028,0x1053,"DS");
1250 */
1251
1252    GDCM_NAME_SPACE::FileHelper *fileH;
1253    fileH = GDCM_NAME_SPACE::FileHelper::New(file);
1254    fileH->SetContentType(contentType);   
1255     
1256    // cast is just to avoid warnings (*no* conversion is performed)
1257    //fileH->SetImageData((uint8_t *)img,int(maxX*maxY)*sizeof(uint16_t)); // troubles when maxX, mayY are *actually* float!
1258
1259 //std::cout << "--------------------------------  X*Y*nbFrames*pixelSize " << X << " " << Y << " " << nbFrames << " " << pixelSize << std::endl; 
1260
1261    fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
1262    fileH->SetWriteModeToRaw(); 
1263    fileH->SetWriteTypeToDcmExplVR();
1264    if( !fileH->Write(dcmImageName))
1265       std::cout << "Failed for [" << dcmImageName << "]\n"
1266                 << "           File is unwrittable" << std::endl;
1267
1268    if (verbose)
1269       file->Print();
1270
1271    file->Delete();
1272    fileH->Delete();  
1273 }
1274
1275