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