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