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