]> Creatis software - creaBruker.git/blob - lib/src1/bruker2dicom.cxx
0473bb3ac3be310019cbbc36da201c6b931604c2
[creaBruker.git] / lib / src1 / bruker2dicom.cxx
1 #include "bruker2dicom.h"
2 #include <boost/filesystem/path.hpp>
3 #include <boost/filesystem/operations.hpp>
4
5 #ifndef PATH_MAX // If not defined yet : do it 
6    #define PATH_MAX 2048
7 #endif 
8
9
10
11 bool Bruker2Dicom::Execute()
12 {
13    // ----- Check input values -----
14
15    bool bigEndian = GDCM_NAME_SPACE::Util::IsCurrentProcessorBigEndian();
16  
17    //if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(InputDirName) )
18    if ( ! boost::filesystem::is_directory(InputDirName) )
19    {
20       std::cout << "KO : [" << InputDirName << "] is not a Directory." << std::endl;
21       return 0;
22    }
23    else
24    {
25       if (verbose)
26          std::cout << "OK : [" << InputDirName << "] is a Directory." << std::endl;
27    }
28
29    std::string strDirNameOut(OutputDirName); 
30    bool res=CreateDirectory(strDirNameOut);
31    if (!res) {
32       std::cout << "[" << OutputDirName << "] Directory creation failure " << std::endl;
33       exit (0);
34    }
35
36    std::string strDirNamein(InputDirName);
37    GDCM_NAME_SPACE::DirList dirList(strDirNamein, false, true); // DON'T get recursively the list of files
38    std::string strDirNameout(OutputDirName);   
39
40 /*
41    if (listonly)
42    {
43       std::cout << "------------List of found files ------------" << std::endl;
44       dirList.Print();
45       std::cout << std::endl;
46       return 1;
47    }
48 */
49
50 //
51 // e.g : at level 0, in : B67d1.Bp1
52 //
53 //           1  2  3  4  5  6  AdjStatePerStudy  subject
54 //
55
56    GDCM_NAME_SPACE::DirListType fileNames;
57    fileNames = dirList.GetFilenames();
58    bool canOpen;
59    std::string outputFileName;
60
61
62   // BrukerDataSet br_subject;
63    std::string subject;
64    subject = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
65              GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
66              "subject";
67    if (verbose)
68         std::cout << " Subject : [" <<  subject << "]" << std::endl;
69    canOpen =br_subject.LoadFile(subject);
70
71    if (!canOpen)
72    {
73       std::cout << "Hopeless! no 'subject' found" << std::endl;
74       exit(0);  /// \TODO throw an exception !     
75    }
76    else
77    { 
78       br_subject.FillMap(); 
79    }
80    //br_subject.PrintSelf();
81
82   // get info for 'Study Description'
83   
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    // subject_name is already in 'Patient Name' 
111    strStudyDescr = /*subject_name + "." + */ subject_study_name + "." + subject_entry + "." + subject_position + "." + subject_date;
112
113    char outputDirName[(unsigned int) PATH_MAX+2];
114
115    strStudyUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
116    serieNumber = 0;
117    // -----------------------------------------------------
118    // Iterate to ALL the objets(files/directories) found in the input directory
119    // (this is level ZERO)
120    // each Directory (name : 1, 2, 3, ...) will be a Dicom Serie
121    // -----------------------------------------------------
122            
123    GDCM_NAME_SPACE::DirListType::iterator it;
124
125    for (it = fileNames.begin();
126          it != fileNames.end();
127        ++it)
128    {
129       if ( boost::filesystem::is_directory(*it) )
130       { 
131          if (verbose)
132             std::cout << "[" << *it << "] is a directory" << std::endl;
133
134          //BrukerDataSet br_acqp;
135          std::string strAcqp;
136          strAcqp = (*it) +
137                    GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
138                    "acqp";
139
140          br_acqp.LoadFile(strAcqp);
141          br_acqp.FillMap();
142
143          std::string acqp_scan_name;
144          std::string acqp_method;
145          std::string acqp_protocol_location; 
146  
147          BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
148          acqp_protocol_location = b_protocol_location.GetStringValue()[0];
149          cleanString(acqp_protocol_location);
150     
151          BrukerFieldData b_scan_name=br_acqp.GetFieldData("ACQ_scan_name");
152          acqp_scan_name = b_scan_name.GetStringValue()[0];
153          cleanString(acqp_scan_name);
154   
155          BrukerFieldData b_method=br_acqp.GetFieldData("ACQ_method"); 
156          acqp_method = b_method.GetStringValue()[0]; 
157          cleanString(acqp_method);
158
159          BrukerFieldData b_list_size = br_acqp.GetFieldData("ACQ_O1_list_size");
160          b_list_size.PrintSelf(); //JP
161  
162          nbSlices =  b_list_size.GetIntValue()[0];
163
164          strSerieDescr = GDCM_NAME_SPACE::Util::GetName(*it)
165                        /*  + "." + acqp_protocol_location */ // always the same (in each acquisition)
166                          + "." + acqp_scan_name
167                          + "." + acqp_method.c_str();
168
169          sprintf(outputDirName, "%s%c%s", OutputDirName.c_str(), 
170                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
171                           strSerieDescr.c_str() );
172   
173          std::cout << " ================================================================================\n"
174                    << " === [" << GDCM_NAME_SPACE::Util::GetName(*it) << "] -> [" << strSerieDescr << "]\n"
175                    << " ================================================================================"
176                    << std::endl;
177
178
179         if (verbose)
180            printf ("outputDirName [%s]\n", outputDirName);   
181
182         DealWithNiveau1(*it, outputDirName);
183       }
184    } // end of : for (GDCM_NAME_SPACE::DirListType::iterator it
185 }
186
187
188 // =====================================================================
189
190 void Bruker2Dicom::DealWithNiveau1(std::string level1Directory, std::string currentOutputDirName) {
191 //
192 // e.g. : at level 1, in B67d1.Bp1/6
193 //
194 // acqp  fid  imnd  pdata  pulseprogram  spnam0  spnam1
195
196    bool res = CreateDirectory(currentOutputDirName); 
197
198    if (!res) {
199       std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
200       exit (0);
201    }
202    GDCM_NAME_SPACE::DirList dirList(level1Directory, false, true); // DON'T get recursively the list of files
203    GDCM_NAME_SPACE::DirListType fileNames;
204    fileNames = dirList.GetFilenames();
205    // -----------------------------------------------------
206    // Iterate to ALL the objets(files/directories) found in the input directory
207    // -----------------------------------------------------
208    GDCM_NAME_SPACE::DirListType::iterator it;
209
210    for (it = fileNames.begin();
211         it != fileNames.end();
212       ++it)
213    {
214       if ( boost::filesystem::is_regular(*it) ) 
215       //if ( ! boost::filesystem::is_directory(*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 ( boost::filesystem::is_directory(*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 ( ! boost::filesystem::is_directory(*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 ( boost::filesystem::is_directory(*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 << "try d3proc: --- => [" << 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 << "try reco --- => [" << 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 slices, 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    serieNumber++;
567    strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
568    if (nbInstants==1) // creer un seul fichier .mhd  pour toutes les Slices! (images natives)
569    {
570        std::cout << "Single instant : do not split" << std::endl;
571        if (mhd)
572        {
573              sprintf(outputMhdFileName, "%s%cMhdData_All_the_Slices.mhd", currentOutputMhdDirName,
574                                          GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
575              fp=fopen(outputMhdFileName, "w");
576              if (!fp)
577              {
578                 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
579                 exit(0);
580              }
581              else
582              {
583                fprintf(fp, "ObjectType = Image\n");
584                fprintf(fp, "NDims = 3\n" );
585                fprintf(fp, "BinaryData = True \n" );
586                fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
587                fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices );
588                fprintf(fp, "HeaderSize = %d\n", 0);
589                fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
590                fprintf(fp, "Position = 0 0 %d\n", 0 );
591                fprintf(fp, "Offset = 0 0 0\n" );
592                fprintf(fp, "CenterOfRotation = 0 0 0\n" );
593                fprintf(fp, "ElementNumberOfChannels = 1\n" );
594                fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );  
595                fprintf(fp, "ElementDataFile = %s\n", "../2dseq_All_the_Slices" );
596                fclose(fp);     
597              }
598              sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices", 
599                                        currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
600              fp=fopen(output2dseqSliceFileName, "wb");
601              if (!fp)
602              {
603                 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
604              }
605              else
606              {
607                 fwrite( buffer_2dseq, NX*NY*pixelSize, nbSlices, fp);     
608              }
609              fclose(fp);
610              serieNumber ++;
611              strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
612        }  // end if mhd
613        if (dicom)
614        {
615              sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices.dcm", 
616                                        currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
617               
618             /* ----------- Write Dicom Image  ---------------*/
619              MakeDicomImage(buffer_2dseq,
620                NX,
621                NY,
622                nbFrames,
623                pixelSize,
624                fovX/NY, fovY/NY, sliceDistance,
625                output2dseqSliceFileName,
626                strPatientName,
627                day,
628                strStudyUID,
629                strSerieUID,
630                strStudyDescr,
631                strSerieDescr,
632                strStudyTimeDate,
633                0,// index frame number
634                GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
635              );
636        }  // end if dicom
637    }  // end if nbInstants = 1
638    
639    else  // more than ONE instant
640    {
641           // Interleaved !
642           // it's (slice1,slide2, ...)t1 ; (slice1,slide2, ...)t2 ; ...
643
644          unsigned char *pixelsForCurrentSlice = new unsigned char[NX*NY*pixelSize*nbInstants];
645
646          k = 0;
647          for (sliceNb=0; sliceNb<nbSlices; sliceNb++)
648          {
649             if (mhd)
650             {
651                sprintf(outputMhdFileName, "%s%cMhdData_%03d.mhd", currentOutputMhdDirName, 
652                                         GDCM_NAME_SPACE::GDCM_FILESEPARATOR, k  );
653                if (verbose)
654                   std::cout << "--- Output MHD file [" << outputMhdFileName << "]" << std::endl;
655                fp=fopen(outputMhdFileName, "w");
656                if (!fp)
657                {
658                    std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
659                    exit(0);
660                }
661                else
662                {
663             /* ----------- Write MHD Image  ---------------*/
664                 //if (verbose)
665                 //   std::cout << "Open sucessfully[" << outputMhdFileName << "] for writting" << std::endl; 
666                    fprintf(fp, "ObjectType = Image\n");
667                    fprintf(fp, "NDims = 3\n" );  
668                    fprintf(fp, "BinaryData = True \n" );  
669                    fprintf(fp, "BinaryDataByteOrderMSB = False\n" );    
670                    fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbInstants);  
671                    fprintf(fp, "HeaderSize = %d\n", 0); 
672                    fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, 1.0 ); // slice distance : no meaning for temporal serie
673                    fprintf(fp, "Position = 0 0 %d\n", sliceNb );  
674                    fprintf(fp, "Offset = 0 0 0\n" );  
675                    fprintf(fp, "CenterOfRotation = 0 0 0\n" );
676                    fprintf(fp, "ElementNumberOfChannels = 1\n" );  
677                    fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );  
678                    fprintf(fp, "ElementDataFile = ..%c2dseq_Slice_%d\n", GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb ); 
679                    fclose(fp);
680                } // end write MHD
681
682                sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d", 
683                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,sliceNb);
684                fp=fopen(output2dseqSliceFileName, "wb");
685                if (!fp)
686                {     
687                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
688                    exit (0);
689                }
690                int frameSize = NX*NY*pixelSize;
691                for (instantNb=0; instantNb<nbInstants; instantNb++)
692                {
693 // std::cout << "------------SN " << sliceNb << " IN " << instantNb <<  " T " << nbSlices*instantNb + sliceNb << std::endl;
694                     fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
695                             frameSize,
696                             1, fp);
697                }
698                fclose(fp);
699 // std::cout << "end writting[" << output2dseqSliceFileName << "]" << std::endl;
700             }  // end if mhd
701    
702             if (dicom)
703             {
704                // desperate try !
705              /* 
706                sprintf(output2dseqSliceFileName, "%sdummy_buffer", 
707                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
708                fp=fopen(output2dseqSliceFileName, "wb");
709                if (!fp)
710                {     
711                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
712                    exit (0);
713                }
714                int frameSize = NX*NY*pixelSize;
715                for (instantNb=0; instantNb<nbInstants; instantNb++)
716                {
717 // std::cout << "------------SN " << sliceNb << " IN " << instantNb <<  " T " << nbSlices*instantNb + sliceNb << std::endl;
718                     fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
719                             frameSize,
720                             1, fp);
721                }
722                fclose(fp);
723        
724                fp=fopen(output2dseqSliceFileName, "rb");
725                if (!fp)
726                {     
727                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for reading" << std::endl;
728                    exit (0);
729                }       
730                fread( pixelsForCurrentSlice,
731                             frameSize*nbInstants,
732                             1, fp);
733                fclose(fp);
734               // end of desperate try !
735               */
736
737                /* ----------- Write Dicom Image  ---------------*/
738        
739                int frameSize = NX*NY*pixelSize;
740                for (instantNb=0; instantNb<nbInstants; instantNb++)
741                {
742                   memcpy(pixelsForCurrentSlice + frameSize*instantNb, buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize, frameSize);
743                }
744
745                int indOfFirsImageWithinImageSet =  nbSlices*instantNb;
746                sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d.dcm", 
747                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb);
748
749                MakeDicomImage(
750                   pixelsForCurrentSlice,
751                   NX,
752                   NY,
753                   nbInstants,
754                   pixelSize,
755                   fovX/NY, fovY/NY, sliceDistance,
756                   output2dseqSliceFileName,
757                   strPatientName,
758                   day,
759                   strStudyUID,
760                   strSerieUID,
761                   strStudyDescr,
762                   strSerieDescr,
763                   strStudyTimeDate,
764                   sliceNb*nbInstants,
765                   GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
766                );
767                if (verbose)
768                   std::cout << "--- Output DCM file [" << output2dseqSliceFileName << "]" << std::endl;      
769
770            } // en if dicom
771
772         k++;
773         }
774         delete [] pixelsForCurrentSlice;  
775      }  // end nbInstants == 1
776    delete [] buffer_2dseq;
777 /**/
778   
779  
780    // -----------------------------------------------------
781    //  deal with MatLab-generated Carto file.
782    // -----------------------------------------------------
783    
784    dealWithCarto(fileNames,  NX,  NY,  nbSlices, fovX, fovY, sliceDistance,
785                    copyFile, currentOutputDirName, outputMhdFileName, output2dseqCartoName);
786 }
787
788
789 // ===========================================================================================
790
791 void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX, int NY, int nbSlices, 
792                                  double fovX, double fovY, double sliceDistance,
793                                  char *copyFile, std::string &currentOutputDirName, 
794                                  char *outputMhdFileName, char *output2dseqCartoName)
795 {
796    // -----------------------------------------------------
797    //  deal with MatLab-generated Carto file.
798    // -----------------------------------------------------
799    
800    char *code[] ={ "ADC", "adc", "TTP", "ttp", "PEAK", "peak" , ""};  // add more carto file name identifiers if necessary; end with ""
801    int icode; 
802    GDCM_NAME_SPACE::DirListType::iterator it;
803    char file_name_ident[500];
804    FILE *fp;
805       
806    // Iterate to ALL the objets(files/directories) found in the input directory    
807    for (it = fileNames.begin();
808         it != fileNames.end();
809       ++it)
810    {
811       if ( boost::filesystem::is_regular(*it) )
812       //if ( ! boost::filesystem::is_directory(*it) )
813       {         
814          if (verbose)
815             std::cout << "--- [" << *it << "] is a file..." << std::endl;
816
817          icode = 0;
818
819          while (code[icode][0] != 0)
820          {
821             sprintf(file_name_ident, "2dseq_%s",code[icode]); // e.g  "2dseq_ADC"
822             std::string::size_type loc = (*it).rfind(file_name_ident); 
823
824             if ( loc != std::string::npos )
825             {
826  
827        ///\ TODO : find a safer way to be sure to read everything!
828               unsigned char *buffer_carto = new unsigned char[NX*NY*sizeof(double)*nbSlices];
829               fp = fopen ( (*it).c_str(), "rb");
830               if (!fp){
831                  std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
832
833                }
834                fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
835
836                std::cout << "Deal with Carto file :[" <<*it << "], computed length : "
837                          << NX*NY*sizeof(double)*nbSlices << std::endl;
838                   std::string lastFileName = GDCM_NAME_SPACE::Util::GetName((*it).c_str());
839                if (mhd)
840                {
841                   // Copy the data file in the new directory
842                   sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
843                             currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str()); 
844                   system(copyFile);
845                   sprintf(outputMhdFileName, "%s%c%s%s",
846                                        currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".mhd" );
847                   if (verbose)
848                     std::cout << "--- Output Carto MHD file [" << outputMhdFileName << "]" << std::endl;
849  
850                   FILE *fp;
851                   fp=fopen(outputMhdFileName, "w");
852                   if (!fp)
853                   {
854                      std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
855                   }
856                   else
857                   {
858                      fprintf(fp, "ObjectType = Image\n");
859                      fprintf(fp, "NDims = 3\n" );
860                      fprintf(fp, "BinaryData = True \n" );
861                      fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
862                      fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices);
863                      fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
864                      fprintf(fp, "HeaderSize = %d\n", 0 );
865                      fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
866                      fprintf(fp, "Position = 0 0 0\n" );
867                      fprintf(fp, "Offset = 0 0 0\n" );
868                      fprintf(fp, "CenterOfRotation = 0 0 0\n" );
869                      fprintf(fp, "ElementNumberOfChannels = 1\n" );
870                      fprintf(fp, "ElementType = %s\n", "MET_DOUBLE" );
871                      fprintf(fp, "ElementDataFile = %s\n", lastFileName.c_str() );
872
873                      fclose(fp);
874                   }
875                   if (verbose)
876                      std::cout << "--- end write Carto MHD file [" << outputMhdFileName << "]" << std::endl;
877                }  // end if mhd
878
879             // ----------- Write Dicom Image  ---------------
880
881                if (dicom)
882                {
883                   sprintf(output2dseqCartoName, "%s%c%s%s",
884                                        currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".dcm" );
885                   if (verbose)
886                      std::cout << "--- end create name output2dseqCartoName file [" << output2dseqCartoName << "]" << std::endl;
887
888                   strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID(); //New SerieUID for each carto.
889                   std::string strNewSerieDescr(strSerieDescr+ "_" +GDCM_NAME_SPACE::Util::GetName((*it).c_str()));
890                   MakeDicomImage(buffer_carto,
891                      NX,
892                      NY,
893                      nbSlices,
894                      8, // pixelSize
895                      fovX/NY, fovY/NY, sliceDistance,
896                      output2dseqCartoName,
897                      strPatientName,
898                      day,
899                      strStudyUID,
900                      strSerieUID,
901                      strStudyDescr,
902                      strNewSerieDescr,
903                      strStudyTimeDate,
904                      0,
905                      GDCM_NAME_SPACE::CREATED_IMAGE
906                   );
907                }  // end if dicom
908
909                delete [] buffer_carto;
910                if (verbose) 
911                   std::cout << "--- End writing Carto DICOM file [" << output2dseqCartoName << "]" << std::endl;
912                break; // don't check for more ident on same file name!
913
914             }
915             icode++;
916          } 
917       }
918    } // end iterate on files
919 }
920
921
922 // ==========================================================================================================
923   
924 bool Bruker2Dicom::CreateDirectory(std::string OutputDirName)
925 {
926    std::string systemCommand;
927    
928    if (verbose)
929       std::cout << "Check for output directory :[" << OutputDirName << "]."
930                 <<std::endl;
931    if ( ! boost::filesystem::is_directory(OutputDirName) )    // dirout not found
932    {
933       std::string strDirNameout(OutputDirName);        // to please gcc 4
934       systemCommand = "mkdir " + strDirNameout;        // create it!
935       if (verbose)
936          std::cout << systemCommand << std::endl;
937       system (systemCommand.c_str());
938       if ( ! boost::filesystem::is_directory(OutputDirName) ) // be sure it worked
939       {
940          if (verbose) 
941             std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
942          return 0;
943          /// \todo : THROW AN EXCEPTION
944       }
945       else
946       {
947          if (verbose) 
948            std::cout << "Directory [" << OutputDirName << "] created." << std::endl;
949       }
950    }
951    else
952    {
953        if (verbose)
954           std::cout << "Output Directory [" << OutputDirName << "] already exists; Used as is." << std::endl;
955    }
956    
957    return 1;
958
959 }
960
961
962 // ===========================================================================================
963
964 /// \TODO move cleanString to 'crea' ?
965
966 void Bruker2Dicom::cleanString(std::string &s)
967 {
968    int l = s.size();
969    if (s[l-1] == 0x0A || s[l-1] == 0x0D ) // CR or NL
970    {
971       l--;
972       s = s.substr(0, l);
973    }
974    if (s[l-1] == ' ' ) // blank space
975    {
976       l--;
977       s = s.substr(0, l);
978    }   
979    
980    if (s[0] == '<')      
981       s= s.substr(1,l-2);
982    std::string repChar("_");   
983    GDCM_NAME_SPACE::Util::ReplaceSpecChar(s, repChar);
984 }
985
986
987
988 // ===========================================================================================
989
990
991 void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPixelType, int &pixelSize)
992
993    if(bDPT.GetDataType() == "string")
994    {         
995          std::string brukerDataPixelType = bDPT.GetStringValue()[0];
996          std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
997          //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
998          
999          if (brukerDataPixelType ==  "ip_short") {
1000             mhdDataPixelType = "MET_USHORT";
1001             pixelSize = 2;
1002          }
1003          if (brukerDataPixelType ==  "ip_int") {
1004             mhdDataPixelType = "MET_UINT";
1005             pixelSize = 4;
1006          }
1007          if (brukerDataPixelType ==  "ip_char") {
1008              mhdDataPixelType = "MET_UCHAR";
1009              pixelSize = 1;
1010          }
1011                   /// \TODO : finish the list
1012     /*
1013     case 0 : fp << "ElementType = MET_CHAR" << std::endl;
1014       break;
1015     case 1 : fp << "ElementType = MET_UCHAR" << std::endl;
1016       break;
1017     case 2 : fp << "ElementType = MET_SHORT" << std::endl;
1018       break;
1019     case 3 : fp << "ElementType = MET_USHORT" << std::endl;
1020       break;
1021     case 4 : fp << "ElementType = MET_INT" << std::endl;
1022       break;
1023     case 5 : fp << "ElementType = MET_UINT" << std::endl;
1024       break;
1025     case 6 : fp << "ElementType = MET_FLOAT" << std::endl;
1026       break;
1027     case 7 : fp << "ElementType = MET_DOUBLE" << std::endl;  
1028     */
1029     }
1030     else
1031     {
1032          int brukerDataPixelType = bDPT.GetIntValue()[0];
1033          std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
1034          //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1035  
1036 // Cross your fingers !!!
1037
1038 // pb : found values : 2, 3, 5
1039          
1040          if (brukerDataPixelType ==  2) {
1041             mhdDataPixelType = "MET_USHORT";
1042             pixelSize = 2;
1043          }
1044          if (brukerDataPixelType ==  3) {
1045             mhdDataPixelType = "MET_USHORT";
1046             pixelSize = 2;
1047          }    
1048          if (brukerDataPixelType ==  1) {
1049             mhdDataPixelType = "MET_UCHAR";
1050             pixelSize = 1;
1051          }     
1052     }
1053 }
1054
1055 // ===========================================================================================
1056
1057 std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
1058 {
1059          std::vector<BrukerImage> imageSet;      
1060          br_acqp.SetLoopStructure();
1061          std::vector<int> tempVect                      = br_acqp.GetLoopStructure() ;
1062          std::map<std::string, BrukerFieldData> map     = br_acqp.GetBrukerHeaderMap();
1063          bool result                                    = br_acqp.ObjectVaryingProperties.init(map,tempVect);
1064
1065          br_acqp.SetImageLoopStructure();
1066          br_acqp.SetBrukerImageList();
1067          std::vector<std::vector<int> > brukerImageList = br_acqp.GetBrukerImageList();
1068
1069          BrukerImage image(br_acqp,br_reco);
1070          image.Init(br_acqp,br_reco,1); 
1071  
1072          for(int i=0;i<brukerImageList.size();i++)
1073          {
1074             image.Init(br_acqp,br_reco,i);    
1075             imageSet.push_back(image);
1076          }
1077  
1078  // Just for checking
1079  /*
1080  
1081          std::vector<std::vector <double> > imageOrientation;
1082          std::vector <double> imagePosition; 
1083          for(int i=0;i<brukerImageList.size();i++)
1084          {
1085            // fread(buffer_2dseq, NX*NY*pixelSize*nbSlices*nbInstants, 1, fp);   
1086    
1087            imagePosition = imageSet[i].getTranslationVectorRPS2XYZ();
1088            std::cout << "Position " << imagePosition[0] << " " 
1089                      << imagePosition[1] << " "  << imagePosition[2] ;
1090            imageOrientation =  imageSet[i].getRotationMatrixRPS2XYZ();
1091            std::cout << "\t  Orientation " ;
1092            for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
1093               std::cout << imageOrientation[i1][i2] << " ";
1094        
1095            //std::cout << "\t  Abs Time " << imageSet[i].getAbsoluteTimePosition();
1096            std::cout << "\t  Relat Time " << imageSet[i].getRelativeTimePosition();
1097
1098            std::cout << "\t [";
1099            for (int i3=0; i3<imageSet[i].getLoopStamp().size();i3++)
1100               std::cout << " " << imageSet[i].getLoopStamp()[i3];
1101            std::cout << "]" << std::endl;       
1102          } 
1103 */
1104    return imageSet;
1105 }
1106
1107 // ===========================================================================================
1108
1109 void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels, 
1110               int X, 
1111               int Y,
1112               int nbFrames,
1113               int pixelSize,
1114               double spacingX, double spacingY, double sliceDistance, 
1115               std::string dcmImageName,
1116               const std::string &patientName,
1117               const char *day,
1118               std::string &studyUID,
1119               std::string &serieUID,
1120               std::string &studyDescr,
1121               std::string &serieDescr,
1122               std::string &strStudyTimeDate,
1123               int imgNum,
1124               GDCM_NAME_SPACE::ImageContentType contentType 
1125       )
1126 {  
1127    std::ostringstream str;
1128
1129    GDCM_NAME_SPACE::File *file;
1130    file = GDCM_NAME_SPACE::File::New();       
1131       
1132   // Set the image size
1133    str.str(""); 
1134    str << X;
1135    file->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
1136    str.str("");
1137    str << Y;
1138    file->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
1139
1140    if (nbFrames != 1)
1141    {
1142       str.str("");
1143       str << nbFrames;
1144       file->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames  
1145    }
1146
1147   // Set the pixel type
1148   //      //8, 16, 32, 64 (for double ?)
1149    str.str("");
1150    str << pixelSize*8;     
1151    file->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
1152
1153    file->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
1154
1155    str.str("");
1156    str << pixelSize*8-1;     
1157    file->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
1158
1159   // Set the pixel representation // 0/1 , 0=unsigned
1160    file->InsertEntryString("1",0x0028,0x0103, "US"); // Pixel Representation
1161    
1162   // Set the samples per pixel // 1:Grey level, 3:RGB
1163    file->InsertEntryString("1",0x0028,0x0002, "US"); // Samples per Pixel
1164
1165 //  0028 0030 DS 2 Pixel Spacing
1166    str.str("");
1167    str << spacingX << "\\" << spacingY;
1168    file->InsertEntryString(str.str(),0x0028,0x0030, "DS"); // Pixel Spacing     
1169    
1170  //   0018 0050 DS 1 Slice Thickness 
1171    str.str("");    
1172    str << sliceDistance;
1173    file->InsertEntryString(str.str(),0x0018,0x0050, "DS");     
1174      
1175   // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
1176  //  file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
1177   // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI");  // [SOP Class UID]
1178
1179
1180 // OK : MR is NOT multiframe, but I want just a quick an dirty solution
1181 // 1.2.840.10008.5.1.4.1.1.4         MR Image Storage
1182    file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
1183    file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI");  // [SOP Class UID]     
1184
1185   // if (strlen(patientName) != 0)
1186    file->InsertEntryString(patientName.c_str(),0x0010,0x0010, "PN"); // Patient's Name
1187
1188    file->InsertEntryString(studyUID, 0x0020, 0x000d, "UI");
1189    file->InsertEntryString(serieUID, 0x0020, 0x000e, "UI");
1190    
1191 //  0008 0020 DA 1 Study Date
1192 //  0008 0030 TM 1 Study Time
1193
1194 /// \TODO split into 2 strings!
1195    file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
1196    file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),0x0008,0x0030, "TM");
1197
1198    file->InsertEntryString(studyDescr,0x0008,0x1030, "LO");  // Study Description  
1199    file->InsertEntryString(serieDescr,0x0008,0x103e, "LO");  // Series Description 
1200
1201 //0008|0060 [CS] [Modality] 
1202    file->InsertEntryString("MR",0x0008,0x0060, "CS");
1203
1204 // 0020 0037 DS 6 Image Orientation (Patient)
1205    char charImageOrientation[256];
1206
1207 /*
1208 std::cout << "try charImageOrientation  " << 
1209                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0] << " " <<
1210                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1] << " " <<
1211                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2] << " " <<
1212                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0] << " " <<
1213                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1] << " " <<
1214                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] << std::endl ;
1215 */      
1216    sprintf(charImageOrientation,"%f\\%f\\%f \\ %f\\%f\\%f",
1217                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0],
1218                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1],
1219                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2],
1220                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0],
1221                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1],
1222                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] ) ;
1223     
1224    file->InsertEntryString(charImageOrientation,0x0020,0x0037, "DS");
1225
1226
1227 // 0020 0032 DS 3 Image Position (Patient) 
1228
1229    char charImagePosition[256];   
1230    sprintf(charImagePosition,"%f\\%f\\%f", 
1231                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[0], 
1232                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[1],
1233                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[2]);
1234   
1235    file->InsertEntryString(charImagePosition,0x0020,0x0032, "DS");  //0020 0032 DS 3 Image Position (Patient) 
1236          
1237
1238
1239 // 0020 0x1041 DS 1 Slice Location 
1240 //        sprintf(charImagePosition,"%f",float(imgNum));
1241 //        file->InsertEntryString(charImagePosition,0x0020,0x1041, "DS");   
1242 /*
1243   // Set Rescale Intercept
1244         str.str("");
1245         str << div;  
1246         file->InsertEntryString(str.str(),0x0028,0x1052,"DS");
1247
1248   // Set Rescale Slope
1249         str.str("");
1250         str << mini;  
1251         file->InsertEntryString(str.str(),0x0028,0x1053,"DS");
1252 */
1253
1254    GDCM_NAME_SPACE::FileHelper *fileH;
1255    fileH = GDCM_NAME_SPACE::FileHelper::New(file);
1256    fileH->SetContentType(contentType);   
1257     
1258    // cast is just to avoid warnings (*no* conversion is performed)
1259    //fileH->SetImageData((uint8_t *)img,int(maxX*maxY)*sizeof(uint16_t)); // troubles when maxX, mayY are *actually* float!
1260
1261 //std::cout << "--------------------------------  X*Y*nbFrames*pixelSize " << X << " " << Y << " " << nbFrames << " " << pixelSize << std::endl; 
1262
1263    fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
1264    fileH->SetWriteModeToRaw(); 
1265    fileH->SetWriteTypeToDcmExplVR();
1266    if( !fileH->Write(dcmImageName))
1267       std::cout << "Failed for [" << dcmImageName << "]\n"
1268                 << "           File is unwrittable" << std::endl;
1269
1270    if (verbose)
1271       file->Print();
1272
1273    file->Delete();
1274    fileH->Delete();  
1275 }
1276
1277