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