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