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