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