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