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