]> Creatis software - creaBruker.git/blob - lib/src1/bruker2dicom.cxx
4f8cd20ff636cf088e0b024cadd5935845387a86
[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    BrukerFieldData bsliceDistance = br_method.GetFieldData("PVM_SPackArrSliceDistance");
627    
628    double sliceDistance = bsliceDistance.GetDoubleValue()[0];     
629 */
630
631 // Better we use 'get' accessors from BrukerImage class, as Denis wrote them
632
633    BrukerFieldData fov = br_reco.GetFieldData("RECO_Fov");
634    double fovX = fov.GetDoubleValue()[0];
635    double fovY = fov.GetDoubleValue()[1];
636    if (verbose)
637       std::cout << "FOV (ds method) " << fovX << " " << fovY << std::endl;
638
639    BrukerFieldData spatResol = br_reco.GetFieldData("RECO_SpatResol");
640    double spatResolX = spatResol.GetDoubleValue()[0];
641    double spatResolY = spatResol.GetDoubleValue()[1];
642    if (verbose)
643       std::cout << "SpatResol (ds method) " << spatResolX << " " << spatResolY << std::endl;
644
645    /// \TODO probabely a more sophisticated accessor will be necessary :
646    ///  (cf : non contiguous slices, overlapping, slice thickness, space between slices, etc)
647    
648    BrukerFieldData bsliceDistance = br_method.GetFieldData("RECO_SPackArrSliceDistance");
649    double sliceDistance = bsliceDistance.GetDoubleValue()[0];
650
651 // ----------------------------------------------------------------------------------------
652
653    if (mhd)
654    {
655       sprintf(currentOutputMhdDirName, "%s%c%s", currentOutputDirName.c_str(),
656                                GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "MhdFiles");
657       res = CreateDirectory( currentOutputMhdDirName );
658       if (!res) {
659          std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
660          throw ( BrukerHopelessException ("Hopeless!FillMap failed on 'reco'"));  
661          //exit (0);
662       } 
663
664       if (verbose)
665          std::cout << "Directory creation [" <<  currentOutputDirName << "]" << std::endl;
666    }  // end if mhd
667
668    if (verbose)
669          std::cout << "nbFrames " << nbFrames << std::endl;
670    if (verbose)
671          std::cout << "nbSlices " << nbSlices << std::endl;
672    int k;
673    int nbInstants = nbFrames/nbSlices;
674    if (verbose)
675          std::cout << "nbInstants (deduced )" << nbInstants << std::endl;    
676    int instantNb;
677    int sliceNb; 
678    FILE *fp;  // for MHD files
679
680    sprintf( original2dseqName, "%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "2dseq");
681
682 /**/   
683   // \TODO : tenir compte du bazar precedent 
684
685     // load 2dseq in memory
686
687    fp = fopen(original2dseqName, "rb");
688    if (!fp) 
689    {
690       // try 2dseq_Angio2D ?!?
691
692       sprintf( original2dseqName_XXX, "%s%s", original2dseqName, "_Angio2D");
693       fp = fopen(original2dseqName_XXX, "rb");
694       if (!fp)
695       {
696          std::cout << "Cannot open [" << original2dseqName << "] nor [" <<  original2dseqName_XXX << "] for reading" << std::endl;
697          fclose(fp);     
698          throw ( BrukerHopelessException ("Hopeless! Cannot open '2dseq'"));
699          //exit (0);
700       }
701    }
702
703    unsigned char *buffer_2dseq = new unsigned char[NX*NY*pixelSize*nbSlices*nbInstants];   
704    ///\ TODO : find a safer way to be sure to read everything!
705    size_t lgr = fread(buffer_2dseq, 1, NX*NY*pixelSize*nbSlices*nbInstants, fp);
706
707    // This one will be important!
708    // ---------------------------
709    try {
710       imageSet = CreateImageSet ( );
711    }
712    catch (BrukerInitException& e)
713    {
714       if (verbose)
715          std::cout <<  "an Init Exception was thrown in CreateImageSet ( ); " << e.what() 
716                    <<  "catched in DealWithNiveau3" << std::endl;
717       //return;
718       throw (e);
719    }
720
721    serieNumber++;
722    strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
723    if (nbInstants==1) // creer un seul fichier .mhd  pour toutes les Slices! (images natives)
724    {
725        if (verbose)
726           std::cout << "Single instant : do not split" << std::endl;
727        if (mhd)
728        {
729              sprintf(outputMhdFileName, "%s%cMhdData_All_the_Slices.mhd", currentOutputMhdDirName,
730                                          GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
731              fp=fopen(outputMhdFileName, "w");
732              if (!fp)
733              {
734                 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
735                 throw ( BrukerHopelessException ("Hopeless! Cannot open  mhd file for writting"));
736                 //exit(0);
737              }
738              else
739              {
740                fprintf(fp, "ObjectType = Image\n");
741                fprintf(fp, "NDims = 3\n" );
742                fprintf(fp, "BinaryData = True \n" );
743                fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
744                fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices );
745                fprintf(fp, "HeaderSize = %d\n", 0);
746                //fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
747                fprintf(fp, "ElementSpacing = %lf %lf %lf\n", spatResolX, spatResolY, sliceDistance );
748                fprintf(fp, "Position = 0 0 %d\n", 0 );
749                fprintf(fp, "Offset = 0 0 0\n" );
750                fprintf(fp, "CenterOfRotation = 0 0 0\n" );
751                fprintf(fp, "ElementNumberOfChannels = 1\n" );
752                fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );  
753                fprintf(fp, "ElementDataFile = %s\n", "../2dseq_All_the_Slices" );
754                fclose(fp);     
755              }
756              sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices", 
757                                        currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
758              fp=fopen(output2dseqSliceFileName, "wb");
759              if (!fp)
760              {
761                 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
762                 throw ( BrukerHopelessException ("Hopeless! Cannot open 2dseq file for writting"));             
763              }
764              else
765              {
766                 fwrite( buffer_2dseq, NX*NY*pixelSize, nbSlices, fp);     
767              }
768              fclose(fp);
769              serieNumber ++;
770              strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
771        }  // end if mhd
772        if (dicom)
773        {
774              sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices.dcm", 
775                                        currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
776
777             /* ----------- Write Dicom Image  ---------------*/
778              MakeDicomImage(buffer_2dseq,
779                NX,
780                NY,
781                nbFrames,
782                pixelSize,
783                //fovX/NY, fovY/NY, sliceDistance,
784                spatResolX, spatResolY, sliceDistance,
785                output2dseqSliceFileName,
786                subject_name,
787                day,
788                strStudyUID,
789                strSerieUID,
790                strStudyDescr,
791                strSerieDescr,
792                strStudyTimeDate,
793                0,// index frame number
794                GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
795              );
796        }  // end if dicom
797    }  // end if nbInstants = 1
798
799    else  // more than ONE instant
800    {
801           // Interleaved !
802           // it's (slice1,slide2, ...)t1 ; (slice1,slide2, ...)t2 ; ...
803          unsigned char *pixelsForCurrentSlice = new unsigned char[NX*NY*pixelSize*nbInstants];
804
805          k = 0;
806          for (sliceNb=0; sliceNb<nbSlices; sliceNb++)
807          {
808             if (mhd)
809             {
810                sprintf(outputMhdFileName, "%s%cMhdData_%03d.mhd", currentOutputMhdDirName, 
811                                         GDCM_NAME_SPACE::GDCM_FILESEPARATOR, k  );
812                if (verbose)
813                   std::cout << "--- Output MHD file [" << outputMhdFileName << "]" << std::endl;
814                fp=fopen(outputMhdFileName, "w");
815                if (!fp)
816                {
817                    std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
818                    throw ( BrukerHopelessException ("Hopeless! Cannot open  mhd file for writting"));
819                    //exit(0);
820                }
821                else
822                {
823             /* ----------- Write MHD Image  ---------------*/
824                 //if (verbose)
825                 //   std::cout << "Open sucessfully[" << outputMhdFileName << "] for writting" << std::endl; 
826                    fprintf(fp, "ObjectType = Image\n");
827                    fprintf(fp, "NDims = 3\n" );  
828                    fprintf(fp, "BinaryData = True \n" );  
829                    fprintf(fp, "BinaryDataByteOrderMSB = False\n" );    
830                    fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbInstants);  
831                    fprintf(fp, "HeaderSize = %d\n", 0); 
832                    //fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, 1.0 ); // 
833                    fprintf(fp, "ElementSpacing = %lf %lf %lf\n",spatResolX, spatResolY, 1.0 ); //slice distance : no meaning for temporal serie
834                    fprintf(fp, "Position = 0 0 %d\n", sliceNb );  
835                    fprintf(fp, "Offset = 0 0 0\n" );  
836                    fprintf(fp, "CenterOfRotation = 0 0 0\n" );
837                    fprintf(fp, "ElementNumberOfChannels = 1\n" );  
838                    fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );  
839                    fprintf(fp, "ElementDataFile = ..%c2dseq_Slice_%d\n", GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb ); 
840                    fclose(fp);
841                } // end write MHD
842
843                sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d", 
844                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,sliceNb);
845                fp=fopen(output2dseqSliceFileName, "wb");
846                if (!fp)
847                {     
848                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
849                    throw ( BrukerHopelessException ("Hopeless! Cannot open 2dseqSliceFile file for writting"));            
850                    //exit (0);
851                }
852                int frameSize = NX*NY*pixelSize;
853                for (instantNb=0; instantNb<nbInstants; instantNb++)
854                {
855 // std::cout << "------------SN " << sliceNb << " IN " << instantNb <<  " T " << nbSlices*instantNb + sliceNb << std::endl;
856                     fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
857                             frameSize,
858                             1, fp);
859                }
860                fclose(fp);
861 // std::cout << "end writting[" << output2dseqSliceFileName << "]" << std::endl;
862             }  // end if mhd
863    
864             if (dicom)
865             {
866                // desperate try !
867              /* 
868                sprintf(output2dseqSliceFileName, "%sdummy_buffer", 
869                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
870                fp=fopen(output2dseqSliceFileName, "wb");
871                if (!fp)
872                {     
873                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
874                    exit (0);
875                }
876                int frameSize = NX*NY*pixelSize;
877                for (instantNb=0; instantNb<nbInstants; instantNb++)
878                {
879 // std::cout << "------------SN " << sliceNb << " IN " << instantNb <<  " T " << nbSlices*instantNb + sliceNb << std::endl;
880                     fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
881                             frameSize,
882                             1, fp);
883                }
884                fclose(fp);
885        
886                fp=fopen(output2dseqSliceFileName, "rb");
887                if (!fp)
888                {     
889                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for reading" << std::endl;
890                    exit (0);
891                }       
892                fread( pixelsForCurrentSlice,
893                             frameSize*nbInstants,
894                             1, fp);
895                fclose(fp);
896               // end of desperate try !
897               */
898
899                /* ----------- Write Dicom Image  ---------------*/
900        
901                int frameSize = NX*NY*pixelSize;
902                for (instantNb=0; instantNb<nbInstants; instantNb++)
903                {
904                   memcpy(pixelsForCurrentSlice + frameSize*instantNb, buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize, frameSize);
905                }
906
907                int indOfFirsImageWithinImageSet =  nbSlices*instantNb;
908                sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d.dcm", 
909                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb);
910
911                MakeDicomImage(
912                   pixelsForCurrentSlice,
913                   NX,
914                   NY,
915                   nbInstants,
916                   pixelSize,
917                   spatResolX, spatResolY, sliceDistance,
918                   //fovX/NY, fovY/NY, sliceDistance,
919                   output2dseqSliceFileName,
920                   subject_name,
921                   day,
922                   strStudyUID,
923                   strSerieUID,
924                   strStudyDescr,
925                   strSerieDescr,
926                   strStudyTimeDate,
927                   sliceNb*nbInstants,
928                   GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
929                );
930                if (verbose)
931                   std::cout << "--- Output DCM file [" << output2dseqSliceFileName << "]" << std::endl;      
932
933            } // en if dicom
934
935         k++;
936         }
937         delete [] pixelsForCurrentSlice;  
938      }  // end nbInstants == 1
939    delete [] buffer_2dseq;
940 /**/
941
942
943    // -----------------------------------------------------
944    //  deal with MatLab-generated Carto file.
945    // -----------------------------------------------------
946
947    dealWithCarto(fileNames,  NX,  NY,  nbSlices, /*fovX, fovY,*/ spatResolX, spatResolY, sliceDistance,
948                    copyFile, currentOutputDirName, outputMhdFileName, output2dseqCartoName);
949 }
950
951
952 // ===========================================================================================
953
954 void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX, int NY, int nbSlices, 
955                                  /*double fovX, double fovY, */
956                                  double spatResolX, double spatResolY, double sliceDistance,
957                                  char *copyFile, std::string &currentOutputDirName, 
958                                  char *outputMhdFileName, char *output2dseqCartoName)
959 {
960    // -----------------------------------------------------
961    //  deal with MatLab-generated Carto file.
962    // -----------------------------------------------------
963    
964    char *code[] = { "ADC", "adc", "TTP", "ttp", "PEAK", "peak", "" };  // add more carto file name identifiers if necessary; end with ""
965    char *separator[] =  { "_", ".", "-", "" }; //  add more, if necessary, to ckeck for 2dseq.ADC, 2dseq_ADC, 2dseq-ADC, etc; end with ""
966    int icode;
967    int iseparator; 
968    GDCM_NAME_SPACE::DirListType::iterator it;
969    char file_name_ident[500];
970    FILE *fp;
971
972    // Iterate to ALL the objets(files/directories) found in the input directory    
973    for (it = fileNames.begin();
974         it != fileNames.end();
975       ++it)
976    {
977       if ( boost::filesystem::is_regular(*it) )
978       //if ( ! boost::filesystem::is_directory(*it) )
979       {         
980          if (verbose)
981             std::cout << "--- [" << *it << "] is a file..." << std::endl;
982
983          icode      = 0;
984          while (code[icode][0] != 0)
985          { 
986          iseparator = 0;       
987          while (separator[iseparator][0] != 0)
988          {
989             sprintf(file_name_ident, "2dseq%s%s",separator[iseparator],code[icode]); // e.g  "2dseq_ADC"
990             //if (verbose)
991             //   std::cout << "check name ["<<(*it) << "] for string [" << file_name_ident << "]" << std::endl;
992             std::string::size_type loc = (*it).rfind(file_name_ident); 
993
994             if ( loc != std::string::npos )
995             {
996
997        ///\ TODO : find a safer way to be sure to read everything!
998               unsigned char *buffer_carto = new unsigned char[NX*NY*sizeof(double)*nbSlices];
999               fp = fopen ( (*it).c_str(), "rb");
1000               if (!fp){
1001                  std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
1002                  throw ( BrukerHopelessException ("Level 1 Unable to open 'carto' file "));
1003                }
1004                fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
1005
1006                     // ?!?  sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
1007                std::cout << "Deal with Carto file :[" <<*it << "], computed length : "
1008                          << NX*NY*sizeof(double)*nbSlices << std::endl;
1009                std::string lastFileName = GDCM_NAME_SPACE::Util::GetName((*it).c_str());
1010                if (mhd)
1011                {
1012                   // Copy the data file in the new directory
1013                   sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
1014                             currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str()); 
1015                   system(copyFile);
1016                   sprintf(outputMhdFileName, "%s%c%s%s",
1017                                          currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".mhd" );
1018                   if (verbose)
1019                     std::cout << "--- Output Carto MHD file [" << outputMhdFileName << "]" << std::endl;
1020
1021                   FILE *fp;
1022                   fp=fopen(outputMhdFileName, "w");
1023                   if (!fp)
1024                   {
1025                      std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
1026                   }
1027                   else
1028                   {
1029                      fprintf(fp, "ObjectType = Image\n");
1030                      fprintf(fp, "NDims = 3\n" );
1031                      fprintf(fp, "BinaryData = True \n" );
1032                      fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
1033                      fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices);
1034                      fprintf(fp, "HeaderSize = %d\n", 0 );
1035                      fprintf(fp, "ElementSpacing = %lf %lf %lf\n",spatResolX, spatResolY, sliceDistance );
1036                      fprintf(fp, "Position = 0 0 0\n" );
1037                      fprintf(fp, "Offset = 0 0 0\n" );
1038                      fprintf(fp, "CenterOfRotation = 0 0 0\n" );
1039                      fprintf(fp, "ElementNumberOfChannels = 1\n" );
1040                      fprintf(fp, "ElementType = %s\n", "MET_DOUBLE" );
1041                      fprintf(fp, "ElementDataFile = %s\n", lastFileName.c_str() );
1042
1043                      fclose(fp);
1044                   }
1045                   if (verbose)
1046                      std::cout << "--- end write Carto MHD file [" << outputMhdFileName << "]" << std::endl;
1047                }  // end if mhd
1048
1049             // ----------- Write Dicom Image  ---------------
1050
1051                if (dicom)
1052                {
1053                   sprintf(output2dseqCartoName, "%s%c%s%s",
1054                                        currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".dcm" );
1055                   if (verbose)
1056                      std::cout << "--- end create name output2dseqCartoName file [" << output2dseqCartoName << "]" << std::endl;
1057
1058                   strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID(); //New SerieUID for each carto.
1059                   std::string strNewSerieDescr(strSerieDescr+ "_" +GDCM_NAME_SPACE::Util::GetName((*it).c_str()));
1060                   MakeDicomImage(buffer_carto,
1061                      NX,
1062                      NY,
1063                      nbSlices,
1064                      8, // pixelSize
1065                      //fovX/NY, fovY/NY, sliceDistance,
1066                      spatResolX, spatResolY, sliceDistance,
1067                      output2dseqCartoName,
1068                      subject_name,
1069                      day,
1070                      strStudyUID,
1071                      strSerieUID,
1072                      strStudyDescr,
1073                      strNewSerieDescr,
1074                      strStudyTimeDate,
1075                      0,
1076                      GDCM_NAME_SPACE::CREATED_IMAGE
1077                   );
1078                }  // end if dicom
1079
1080                delete [] buffer_carto;
1081                if (verbose) 
1082                   std::cout << "--- End writing Carto DICOM file [" << output2dseqCartoName << "]" << std::endl;
1083                break; // don't check for more ident on same file name!
1084             
1085             }  // end deal with _ADC, -adc, etc
1086           iseparator ++;
1087           }  // end iterate speparators
1088           icode++;
1089           } // end iterate code
1090       } // end boost::filesystem::is_regular(*it)
1091    } // end iterate on all objects (files, dir, etc)
1092 } // end method
1093
1094
1095 // ==========================================================================================================
1096   
1097 bool Bruker2Dicom::CreateDirectory(std::string OutputDirName)
1098 {
1099    std::string systemCommand;
1100    
1101    if (verbose)
1102       std::cout << "Check for output directory :[" << OutputDirName << "]."
1103                 <<std::endl;
1104    if ( ! boost::filesystem::is_directory(OutputDirName) )    // dirout not found
1105    {
1106       std::string strDirNameout(OutputDirName);        // to please gcc 4
1107       systemCommand = "mkdir " + strDirNameout;        // create it!
1108       if (verbose)
1109          std::cout << systemCommand << std::endl;
1110       system (systemCommand.c_str());
1111       if ( ! boost::filesystem::is_directory(OutputDirName) ) // be sure it worked
1112       {
1113          if (verbose) 
1114             std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
1115          //return 0;
1116          throw ( BrukerHopelessException ("Level 1 output directory creation failure "));
1117       }
1118       else
1119       {
1120          if (verbose) 
1121            std::cout << "Directory [" << OutputDirName << "] created." << std::endl;
1122       }
1123    }
1124    else
1125    {
1126        if (verbose)
1127             std::cout << "Output Directory [" << OutputDirName << "] already exists; Used as is." << std::endl;
1128    }
1129    
1130    return 1;
1131
1132 }
1133
1134
1135 // ===========================================================================================
1136
1137 /// \TODO move cleanString to 'crea' ?
1138
1139 void Bruker2Dicom::cleanString(std::string &s)
1140 {
1141    int l = s.size();
1142    if (s[l-1] == 0x0A || s[l-1] == 0x0D ) // CR or NL
1143    {
1144       l--;
1145       s = s.substr(0, l);
1146    }
1147    if (s[l-1] == ' ' ) // blank space
1148    {
1149       l--;
1150       s = s.substr(0, l);
1151    }   
1152    
1153    if (s[0] == '<')      
1154       s= s.substr(1,l-2);
1155    std::string repChar("_");   
1156    GDCM_NAME_SPACE::Util::ReplaceSpecChar(s, repChar);
1157 }
1158
1159
1160
1161 // ===========================================================================================
1162
1163
1164 void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPixelType, int &pixelSize)
1165
1166    if(bDPT.GetDataType() == "string")
1167    {         
1168          std::string brukerDataPixelType = bDPT.GetStringValue()[0];
1169          if (verbose)
1170             std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
1171          //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1172          
1173          if (brukerDataPixelType ==  "ip_short") {
1174             mhdDataPixelType = "MET_USHORT";
1175             pixelSize = 2;
1176          }
1177          if (brukerDataPixelType ==  "ip_int") {
1178             mhdDataPixelType = "MET_UINT";
1179             pixelSize = 4;
1180          }
1181          if (brukerDataPixelType ==  "ip_char") {
1182              mhdDataPixelType = "MET_UCHAR";
1183              pixelSize = 1;
1184          }
1185                   /// \TODO : finish the list
1186     /*
1187     case 0 : fp << "ElementType = MET_CHAR" << std::endl;
1188       break;
1189     case 1 : fp << "ElementType = MET_UCHAR" << std::endl;
1190       break;
1191     case 2 : fp << "ElementType = MET_SHORT" << std::endl;
1192       break;
1193     case 3 : fp << "ElementType = MET_USHORT" << std::endl;
1194       break;
1195     case 4 : fp << "ElementType = MET_INT" << std::endl;
1196       break;
1197     case 5 : fp << "ElementType = MET_UINT" << std::endl;
1198       break;
1199     case 6 : fp << "ElementType = MET_FLOAT" << std::endl;
1200       break;
1201     case 7 : fp << "ElementType = MET_DOUBLE" << std::endl;  
1202     */
1203     }
1204     else
1205     {
1206          int brukerDataPixelType = bDPT.GetIntValue()[0];
1207          if (verbose)
1208             std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
1209          //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1210  
1211 // Cross your fingers !!!
1212
1213 // pb : found values : 2, 3, 5
1214          
1215          if (brukerDataPixelType ==  2) {
1216             mhdDataPixelType = "MET_USHORT";
1217             pixelSize = 2;
1218          }
1219          if (brukerDataPixelType ==  3) {
1220             mhdDataPixelType = "MET_USHORT";
1221             pixelSize = 2;
1222          }    
1223          if (brukerDataPixelType ==  1) {
1224             mhdDataPixelType = "MET_UCHAR";
1225             pixelSize = 1;
1226          }     
1227     }
1228 }
1229
1230 // ===========================================================================================
1231
1232 std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
1233 {
1234          std::vector<BrukerImage> imageSet;      
1235          br_acqp.SetLoopStructure();
1236          std::vector<int> tempVect                      = br_acqp.GetLoopStructure() ;
1237          std::map<std::string, BrukerFieldData> map     = br_acqp.GetBrukerHeaderMap();
1238          
1239          bool result                                    = br_acqp.ObjectVaryingProperties.init(map,tempVect);
1240  
1241          if (result == false)
1242          {
1243             throw ( BrukerInitException  ("ObjectVaryingProperties.init() failure in Bruker2Dicom::CreateImageSet()") );
1244          }
1245
1246          br_acqp.SetImageLoopStructure();
1247          br_acqp.SetBrukerImageList();
1248          std::vector<std::vector<int> > brukerImageList = br_acqp.GetBrukerImageList();
1249
1250          BrukerImage image(br_acqp,br_reco);
1251          image.Init(br_acqp,br_reco,1); 
1252  
1253          for(int i=0;i<brukerImageList.size();i++)
1254          {
1255             image.Init(br_acqp,br_reco,i);    
1256             imageSet.push_back(image);
1257          }
1258  
1259  // Just for checking
1260  /*
1261  
1262          std::vector<std::vector <double> > imageOrientation;
1263          std::vector <double> imagePosition; 
1264          for(int i=0;i<brukerImageList.size();i++)
1265          {
1266            // fread(buffer_2dseq, NX*NY*pixelSize*nbSlices*nbInstants, 1, fp);   
1267    
1268            imagePosition = imageSet[i].getTranslationVectorRPS2XYZ();
1269            std::cout << "Position " << imagePosition[0] << " " 
1270                      << imagePosition[1] << " "  << imagePosition[2] ;
1271            imageOrientation =  imageSet[i].getRotationMatrixRPS2XYZ();
1272            std::cout << "\t  Orientation " ;
1273            for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
1274               std::cout << imageOrientation[i1][i2] << " ";CreateImageSet
1275        
1276            //std::cout << "\t  Abs Time " << imageSet[i].getAbsoluteTimePosition();
1277            std::cout << "\t  Relat Time " << imageSet[i].getRelativeTimePosition();
1278
1279            std::cout << "\t [";
1280            for (int i3=0; i3<imageSet[i].getLoopStamp().size();i3++)
1281               std::cout << " " << imageSet[i].getLoopStamp()[i3];
1282            std::cout << "]" << std::endl;       
1283          } 
1284 */
1285    return imageSet;
1286 }
1287
1288 // ===========================================================================================
1289
1290 void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels, 
1291               int X, 
1292               int Y,
1293               int nbFrames,
1294               int pixelSize,
1295               double spacingX, double spacingY, double sliceDistance, 
1296               std::string dcmImageName,
1297               const std::string &patientName,
1298               const char *day,
1299               std::string &studyUID,
1300               std::string &serieUID,
1301               std::string &studyDescr,
1302               std::string &serieDescr,
1303               std::string &strStudyTimeDate,
1304               int imgNum,
1305               GDCM_NAME_SPACE::ImageContentType contentType 
1306       )
1307 {  
1308    std::ostringstream str;
1309
1310    GDCM_NAME_SPACE::File *file;
1311    file = GDCM_NAME_SPACE::File::New();       
1312       
1313   // Set the image size
1314    str.str(""); 
1315    str << X;
1316    file->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
1317    str.str("");
1318    str << Y;
1319    file->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
1320
1321    if (nbFrames != 1)
1322    {
1323       str.str("");
1324       str << nbFrames;
1325       file->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames  
1326    }
1327
1328   // Set the pixel type
1329   //      //8, 16, 32, 64 (for double ?)
1330    str.str("");
1331    str << pixelSize*8;     
1332    file->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
1333
1334    file->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
1335
1336    str.str("");
1337    str << pixelSize*8-1;     
1338    file->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
1339
1340   // Set the pixel representation // 0/1 , 0=unsigned
1341    file->InsertEntryString("1",0x0028,0x0103, "US"); // Pixel Representation
1342    
1343   // Set the samples per pixel // 1:Grey level, 3:RGB
1344    file->InsertEntryString("1",0x0028,0x0002, "US"); // Samples per Pixel
1345
1346 //  0028 0030 DS 2 Pixel Spacing
1347    str.str("");
1348    str << spacingX << "\\" << spacingY;
1349    file->InsertEntryString(str.str(),0x0028,0x0030, "DS"); // Pixel Spacing     
1350    
1351  //   0018 0050 DS 1 Slice Thickness 
1352    str.str("");    
1353    str << sliceDistance;
1354    file->InsertEntryString(str.str(),0x0018,0x0050, "DS"); 
1355    
1356 //    0020 0011 IS 1 Series Number
1357    str.str("");    
1358    str << serieNumber;
1359    file->InsertEntryString(str.str(),0x0020,0x0011, "IS");
1360       
1361 //    0020|0013 [IS]  [Instance Number] 
1362    instanceNumber++;
1363    str.str("");    
1364    str << instanceNumber;
1365    file->InsertEntryString(str.str(),0x0020,0x0013, "IS");
1366    
1367        
1368   // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
1369  //  file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
1370   // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI");  // [SOP Class UID]
1371
1372
1373 // OK : MR is NOT multiframe, but I want just a quick an dirty solution
1374
1375 // 1.2.840.10008.5.1.4.1.1.4         MR Image Storage
1376    file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
1377    file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI");  // [SOP Class UID]     
1378
1379   // if (strlen(patientName) != 0)
1380    file->InsertEntryString(patientName.c_str(),0x0010,0x0010, "PN"); // Patient's Name
1381
1382    file->InsertEntryString(studyUID, 0x0020, 0x000d, "UI");
1383    file->InsertEntryString(serieUID, 0x0020, 0x000e, "UI");
1384    
1385 //  0008 0020 DA 1 Study Date
1386 //  0008 0030 TM 1 Study Time
1387
1388 /// \TODO split into 2 strings!
1389    file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
1390    file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),  0x0008,0x0030, "TM");
1391
1392    file->InsertEntryString(studyDescr, 0x0008,0x1030, "LO");  // Study Description  
1393    file->InsertEntryString(serieDescr, 0x0008,0x103e, "LO");  // Series Description 
1394
1395 //0008|0060 [CS] [Modality] 
1396    file->InsertEntryString("MR",0x0008,0x0060, "CS");
1397
1398 // 0020 0037 DS 6 Image Orientation (Patient)
1399    char charImageOrientation[256];
1400
1401 /*
1402 std::cout << "charImageOrientation  " << 
1403                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0] << " " <<
1404                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1] << " " <<
1405                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2] << " " <<
1406                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0] << " " <<
1407                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1] << " " <<
1408                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] << std::endl ;
1409 */      
1410    sprintf(charImageOrientation,"%f\\%f\\%f \\ %f\\%f\\%f",
1411                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0],
1412                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1],
1413                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2],
1414                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0],
1415                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1],
1416                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] ) ;
1417     
1418    file->InsertEntryString(charImageOrientation,0x0020,0x0037, "DS");
1419
1420
1421 // 0020 0032 DS 3 Image Position (Patient) 
1422
1423    char charImagePosition[256];   
1424    sprintf(charImagePosition,"%f\\%f\\%f", 
1425                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[0], 
1426                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[1],
1427                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[2]);
1428   
1429    file->InsertEntryString(charImagePosition,0x0020,0x0032, "DS");  //0020 0032 DS 3 Image Position (Patient) 
1430          
1431
1432
1433 // 0020 0x1041 DS 1 Slice Location 
1434 //        sprintf(charImagePosition,"%f",float(imgNum));
1435 //        file->InsertEntryString(charImagePosition,0x0020,0x1041, "DS");   
1436 /*
1437   // Set Rescale Intercept
1438         str.str("");
1439         str << div;  
1440         file->InsertEntryString(str.str(),0x0028,0x1052,"DS");
1441
1442   // Set Rescale Slope
1443         str.str("");
1444         str << mini;  
1445         file->InsertEntryString(str.str(),0x0028,0x1053,"DS");
1446 */
1447
1448    GDCM_NAME_SPACE::FileHelper *fileH;
1449    fileH = GDCM_NAME_SPACE::FileHelper::New(file);
1450    fileH->SetContentType(contentType);   
1451     
1452    // cast is just to avoid warnings (*no* conversion is performed)
1453    //fileH->SetImageData((uint8_t *)img,int(maxX*maxY)*sizeof(uint16_t)); // troubles when maxX, mayY are *actually* float!
1454
1455 //std::cout << "--------------------------------  X*Y*nbFrames*pixelSize " << X << " " << Y << " " << nbFrames << " " << pixelSize << std::endl; 
1456
1457    fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
1458    fileH->SetWriteModeToRaw(); 
1459    fileH->SetWriteTypeToDcmExplVR();
1460    if( !fileH->Write(dcmImageName)) {
1461       std::cout << "Failed for [" << dcmImageName << "]\n"
1462                 << "           File is unwrittable" << std::endl;               
1463       file->Delete();
1464       fileH->Delete();          
1465       throw ( BrukerHopelessException ("Level 1 Unable to write Dicom file "));
1466    }
1467    //if (verbose)
1468    //   file->Print();
1469
1470    file->Delete();
1471    fileH->Delete();  
1472 }
1473
1474