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