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