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