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