]> Creatis software - creaBruker.git/blob - lib/src1/bruker2dicom.cxx
Ass some comments
[creaBruker.git] / lib / src1 / bruker2dicom.cxx
1 #include "bruker2dicom.h"
2 #include <boost/filesystem/path.hpp>
3 #include <boost/filesystem/operations.hpp>
4 #include "brukerexception.h"
5
6 #ifndef PATH_MAX // If not defined yet : do it 
7    #define PATH_MAX 2048
8 #endif 
9
10 bool Bruker2Dicom::Execute()
11 {
12    // ----- Check input directory name -----
13
14    bool bigEndian = GDCM_NAME_SPACE::Util::IsCurrentProcessorBigEndian();
15
16    //if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(InputDirName) )
17    if ( ! boost::filesystem::is_directory(InputDirName) )
18    {
19       std::cout << "KO : [" << InputDirName << "] is not a Directory." << std::endl;
20       return 0;
21    }
22    else
23    {
24       if (verbose)
25          std::cout << "OK : [" << InputDirName << "] is a Directory." << std::endl;
26    }
27
28    // ----- Check output directory name -----
29
30    std::string strDirNameOut(OutputDirName); 
31    bool res=CreateDirectory(strDirNameOut);
32    if (!res) {
33       std::cout << "[" << OutputDirName << "] Directory creation failure " << std::endl;
34       //exit (0);
35       throw ( BrukerHopelessException ("Output directory creation failure "));
36    }
37
38 //
39 // e.g : at level 0, in : B67d1.Bp1
40 //
41 //           1  2  3  4  5  6  AdjStatePerStudy  subject
42 //
43
44    std::string strDirNamein(InputDirName);
45
46 /* */
47    GDCM_NAME_SPACE::DirList dirList(strDirNamein, false, true); // DON'T get recursively the list of files
48
49    GDCM_NAME_SPACE::DirListType fileNames;
50    fileNames = dirList.GetFilenames();
51
52    std::string path = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()));
53
54    std::string subject =  path +
55                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
56                           "subject";
57
58     std::string acqp = path +
59                        GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
60                        "acqp";
61
62     if ( boost::filesystem::is_regular(subject) )
63        subjectFound = true;
64     else
65        subjectFound = false; // user passed only a 'serie', not a 'study 
66
67     if ( boost::filesystem::is_regular(acqp) )
68        acqpFound= true;
69     else
70        acqpFound = false; // user passed a 'non study' directory; Hope it's a 'set of studies' directory!
71
72    int type;
73    if  (subjectFound )  type = 1; // user passed a 'study
74    else if  (acqpFound) type = 2; // user passed a 'serie' 
75    else                 type = 3; // user passed a 'non study' directory; Hope it's a 'set of studies' directory!
76  /* */
77
78    // 1 : if subjectFound                       : user passed a Single Study Directory
79    // 2 : if NOT subjectFound and acqpFound     : user passed a Serie Directory
80    // 3 : if NOT subjectFound and NOT acqpFound : user passed a 'non Study Directory' (Hope it's a set of Single Study Directories)
81
82    //int type = CheckUserDirectory(InputDirName);
83  
84    switch (type)
85    {
86       case 1: {
87          bool canOpen = br_subject.LoadFile(subject);
88          if (!canOpen)
89          {
90             std::cout << "Hopeless! 'subject' found / cannot be open" << std::endl;
91             throw ( BrukerHopelessException ("Hopeless! 'subject' found in root input directory / cannot be open"));
92          }
93          else
94          {
95             br_subject.FillMap();
96
97             // get info for 'Study Description'  
98             BrukerFieldData b_name=br_subject.GetFieldData("SUBJECT_name_string");
99             subject_name = b_name.GetStringValue()[0];
100             strPatientName = subject_name;
101             cleanString(subject_name);
102             DealWithSingleStudyDirectory (fileNames);
103          }
104          break;
105       }
106
107       case 2: {
108          subject_name = "defaultPatName";
109          strPatientName = subject_name;
110          DealWithSingleStudyDirectory (fileNames);
111          break;
112       }
113
114       case 3: {
115          std::cout << " User passed a 'non study' directory; Hope it's a *non recursive* 'set of studies' directory! (recursive not yet dealt with)" << std::endl;
116          DealWithMultiStudyDirectory (fileNames);
117          break;
118       }
119    }
120 }
121
122 // ----------------------------------------------------------------------------------------------------------
123
124 void Bruker2Dicom::DealWithMultiStudyDirectory (GDCM_NAME_SPACE::DirListType &dirNames)
125 {
126    GDCM_NAME_SPACE::DirListType::iterator it;
127
128    for (it = dirNames.begin();
129          it != dirNames.end();
130        ++it)
131    {
132       if ( boost::filesystem::is_directory(*it) )
133       {
134          subjectFound = false;
135          if (verbose)
136             std::cout << "in 'DealWithMultiStudyDirectory' [" << *it << "] is a directory" << std::endl;
137
138          GDCM_NAME_SPACE::DirList dirList(*it, false, true); // DON'T get recursively the list of files
139          GDCM_NAME_SPACE::DirListType fileNames;
140          fileNames = dirList.GetFilenames();
141
142          std::string path = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()));
143          std::string subject =  path +
144                                 GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
145                                 "subject";
146          if (! boost::filesystem::is_regular(subject) )
147          {
148             std::cout << "no [" << subject << "] file found" << std::endl;
149             continue;
150          }
151
152          bool canOpen = br_subject.LoadFile(subject);
153          if (!canOpen)
154          {
155             std::cout << "Hopeless! 'subject' found / cannot be open" << std::endl;
156             throw ( BrukerHopelessException ("Hopeless! 'subject' found in root input directory / cannot be open"));
157          }
158          else
159          {
160             br_subject.FillMap();
161             subjectFound = true; // Hope so! (full checking needed!)
162
163             BrukerFieldData b_name=br_subject.GetFieldData("SUBJECT_name_string");
164             subject_name = b_name.GetStringValue()[0];
165             strPatientName = subject_name;
166             cleanString(subject_name);   
167             DealWithSingleStudyDirectory(fileNames);
168          }  
169       }
170       else
171       {
172          if (verbose)
173             std::cout << "[" << *it << "] is NOT a directory; skipped!" << std::endl; 
174       }   
175    } 
176 }
177
178 // ----------------------------------------------------------------------------------------------------------
179
180 void Bruker2Dicom::DealWithSingleStudyDirectory (GDCM_NAME_SPACE::DirListType &fileNames)
181 {
182      bool res;   
183     // creation directory : 'nom du patient'
184     std::string tempStringPatDir(OutputDirName);
185     tempStringPatDir = tempStringPatDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR + subject_name;
186
187     res=CreateDirectory(tempStringPatDir);
188     if (!res) {
189        std::cout << "[" << tempStringPatDir << "] Directory creation failure " << std::endl;
190        throw ( BrukerHopelessException ("Patient directory creation failure "));
191     }
192
193     if (subjectFound)
194     {
195        BrukerFieldData b_entry=br_subject.GetFieldData("SUBJECT_entry");
196        subject_entry = b_entry.GetStringValue()[0];
197        //cleanString(subject_entry);
198        subject_entry = subject_entry.substr(11, subject_entry.size()-11);
199   
200        BrukerFieldData b_position=br_subject.GetFieldData("SUBJECT_position");
201        subject_position = b_position.GetStringValue()[0];
202        //cleanString(subject_position);
203        subject_position = subject_position.substr(9, subject_position.size()-9);
204  
205        BrukerFieldData b_date=br_subject.GetFieldData("SUBJECT_date");
206        subject_date = b_date.GetStringValue()[0];
207        strStudyTimeDate = subject_date;
208        cleanString(subject_date);
209  
210        BrukerFieldData b_study_name=br_subject.GetFieldData("SUBJECT_study_name");
211        subject_study_name = b_study_name.GetStringValue()[0];
212        subject_study_name = subject_study_name.substr(1, subject_study_name.size()-2);
213        cleanString(subject_study_name);
214    }
215    else  // Desperate trick when file 'subject' is missing
216    {
217       subject_entry      = "HeadFirst";            // Why not?
218       subject_position   = "Supine";               // Why not?
219       strStudyTimeDate   = "06_06_06_6_June_1666"; // Why not?
220       subject_date       = "6_June_1666";          // Why not?
221       subject_study_name = "defStudyName";         // Why not? 
222    }
223     // subject_name is already in 'Patient Name' 
224     if (0) // We don't realy need so much information for 'Study'
225         strStudyDescr = /*subject_name + "." + */ subject_study_name + "." + subject_entry + "." + subject_position + "." + subject_date;
226     else
227        strStudyDescr = /*subject_name + "." + */ subject_study_name /*+ "." + subject_entry + "." + subject_position + "." + subject_date*/;
228
229     // creation directory : 'nom de la Study'
230
231     std::string tempStringStudyDir(OutputDirName);
232     tempStringStudyDir = tempStringPatDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR + strStudyDescr;
233
234     res=CreateDirectory(tempStringStudyDir);
235     if (!res) {
236        std::cout << "[" << tempStringStudyDir << "] Directory creation failure " << std::endl;
237        throw ( BrukerHopelessException ("Study directory creation failure "));
238     }     
239
240    char outputDirName[(unsigned int) PATH_MAX+2];
241
242    strStudyUID    = GDCM_NAME_SPACE::Util::CreateUniqueUID();
243    serieNumber    = 0;
244    instanceNumber = 0;
245
246    // -----------------------------------------------------
247    // Iterate to ALL the objets(files/directories) found in the input directory
248    // (this is level ZERO)
249    // each Directory (name : 1, 2, 3, ...) will be a Dicom Serie
250    // -----------------------------------------------------
251
252    /// \TODO better use directory iterator, from boost! // JPR
253    GDCM_NAME_SPACE::DirListType::iterator it;
254
255    for (it = fileNames.begin();
256          it != fileNames.end();
257        ++it)
258    {
259       if ( boost::filesystem::is_directory(*it) )
260       { 
261          if (verbose)
262             std::cout << "[" << *it << "] is a directory" << std::endl;
263
264          //if((*it) == "AdjResult")  // avoid trouble with new version 'AdjResult' directory
265          if(GDCM_NAME_SPACE::Util::GetName(*it) == "AdjResult")
266             continue;
267
268          //BrukerDataSet br_acqp;
269          std::string strAcqp;
270          strAcqp = (*it) +
271                    GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
272                    "acqp";
273
274          br_acqp.LoadFile(strAcqp);
275          br_acqp.FillMap();
276
277 //std::cout << "out of br_acqp.FillMap " << std::endl;
278          std::string acqp_scan_name;
279          std::string acqp_method;
280          std::string acqp_protocol_location; 
281  
282          BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
283          acqp_protocol_location = b_protocol_location.GetStringValue()[0];
284          cleanString(acqp_protocol_location);
285
286 //std::cout << "out of br_acqp.FillMap 1" << std::endl;    
287          BrukerFieldData b_scan_name=br_acqp.GetFieldData("ACQ_scan_name");
288 //std::cout << "out of br_acqp.FillMap 11" << std::endl;         
289          acqp_scan_name = b_scan_name.GetStringValue()[0];
290 //std::cout << "out of br_acqp.FillMap 12 [" << acqp_scan_name << "]" << std::endl;      
291          cleanString(acqp_scan_name);
292 //std::cout << "out of br_acqp.FillMap 2" << std::endl;  
293          BrukerFieldData b_method=br_acqp.GetFieldData("ACQ_method");
294          b_method.PrintSelf();
295          acqp_method = b_method.GetStringValue()[0];
296
297          cleanString(acqp_method);
298 //std::cout << "out of br_acqp.FillMap 3" << std::endl;
299          BrukerFieldData b_list_size = br_acqp.GetFieldData("ACQ_O1_list_size");
300 //std::cout << "out of br_acqp.FillMap 4" << std::endl;        
301          //b_list_size.PrintSelf(); //JP
302
303          nbSlices =  b_list_size.GetIntValue()[0];
304 //std::cout << "out of br_acqp.FillMap 5" << std::endl;
305          strSerieDescr = GDCM_NAME_SPACE::Util::GetName(*it)
306                        /*  + "." + acqp_protocol_location */ // always the same (in each acquisition)
307                          + "." + acqp_scan_name
308                          + "." + acqp_method.c_str();
309
310          sprintf(outputDirName, "%s%c%s", tempStringStudyDir.c_str(),      //OutputDirName.c_str(), 
311                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
312                           strSerieDescr.c_str() );
313
314          std::cout << " ================================================================================\n"
315                    << " === [" << GDCM_NAME_SPACE::Util::GetName(*it) << "] -> [" << strSerieDescr << "]\n"
316                    << " ================================================================================"
317                    << std::endl;
318         std::string strOutputDirName(outputDirName);
319         if (verbose)
320            printf ("outputDirName [%s]\n", outputDirName);
321         try {
322            DealWithNiveau1(*it, strOutputDirName);
323         }
324         catch (BrukerHopelessException &e)
325         {
326          std::cout << "And Exception was thrown in DealWithNiveau1 (" << e.what() << ") " << std::endl;
327          continue;
328         }
329       }
330    } // end of : for (GDCM_NAME_SPACE::DirListType::iterator it
331 }
332
333 // =====================================================================
334
335 void Bruker2Dicom::DealWithNiveau1(std::string &level1Directory, std::string &currentOutputDirName) {
336 //
337 // e.g. : at level 1, in B67d1.Bp1/6
338 //
339 // acqp  fid  imnd  pdata  pulseprogram  spnam0  spnam1
340
341    bool res = CreateDirectory(currentOutputDirName); 
342
343    if (!res) {
344       std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
345       throw ( BrukerHopelessException ("Level 1 output directory creation failure "));    
346      // exit (0);
347    }
348    GDCM_NAME_SPACE::DirList dirList(level1Directory, false, true); // DON'T get recursively the list of files
349    GDCM_NAME_SPACE::DirListType fileNames;
350    fileNames = dirList.GetFilenames();
351    // -----------------------------------------------------
352    // Iterate to ALL the objets(files/directories) found in the input directory
353    // -----------------------------------------------------
354    GDCM_NAME_SPACE::DirListType::iterator it;
355
356    for (it = fileNames.begin();
357         it != fileNames.end();
358       ++it)
359    {
360       if ( boost::filesystem::is_regular(*it) ) 
361       //if ( ! boost::filesystem::is_directory(*it) )
362       {
363          if (verbose)
364             std::cout << "--- [" << *it << "] is a file." << std::endl;
365       }  
366    }
367
368    char outputDirName[(unsigned int) PATH_MAX+2];
369    //std::string firstName;
370    bool canOpen;
371    for (it = fileNames.begin();
372         it != fileNames.end();
373       ++it)
374    {
375       if ( boost::filesystem::is_directory(*it) )
376       {
377          // will be always "pdata" ...
378          if (verbose)
379             std::cout << "--- [" << *it << "] is a directory" << std::endl;
380
381               /* a recuperer :
382               if (FileLine.startsWith("##$ACQ_size=")) {
383               if (FileLine.startsWith("##$NI=")) {
384               if (FileLine.startsWith("##$NR=")) {
385               if (FileLine.startsWith("##$ACQ_obj_order=")) {
386               if (FileLine.startsWith("##$ACQ_word_size=")) {
387               if (FileLine.startsWith("##$BYTORDA=")) {
388               if (FileLine.startsWith("##$PULPROG=")) {
389               */
390
391          sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
392                                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
393                                           GDCM_NAME_SPACE::Util::GetName(*it).c_str());
394          std::string strOutputDirName(outputDirName);
395          //br1.PrintSelf();
396
397           std::string strMethod;
398           //std::string firstName = *(fileNames.begin());
399
400           strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin())) +
401                       GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
402                       "method";
403             // std::cout << "---strMethod (for method)=> [" << strMethod << "]" << std::endl;        
404           canOpen = br_method.LoadFile(strMethod);
405           if (!canOpen)
406           {
407              strMethod = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
408                          GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
409                          "imnd";
410              //std::cout << "---strMethod (for imnd) => [" << strMethod << "]" << std::endl;
411              canOpen = br_method.LoadFile(strMethod);
412              if (!canOpen)
413              {
414                 std::cout << "Hopeless! neither 'method' nor 'imnd' found in ["
415                           << level1Directory  << "]; we skip it!" << std::endl;
416                 continue;
417                 //throw ( BrukerHopelessException ("Hopeless! neither 'method' nor 'imnd' found "));            
418                 //exit(0);  /// \TODO throw an exception !
419              }
420           }
421           if (verbose)
422              std::cout << "open => [" << strMethod << "] successfully" << std::endl; 
423           br_method.FillMap();
424
425           /* a recuperer :
426              ##$PVM_Fov (dimension)  // ou plutot RECO_fov !
427           */
428   /*
429           dans method (pour perfusion  seulement?) :
430           ##$PVM_ObjOrderList=( 8 )
431           0 2 4 6 1 3 5 7
432           ##$PVM_NSPacks=2
433           ##$PVM_SPackArrNSlices=( 2 )
434           7 1  
435   */
436          try {
437             DealWithNiveau2(*it, strOutputDirName);
438          }
439          catch (BrukerHopelessException &e)
440          {
441             std::cout << "And Exception was thrown in DealWithNiveau2 (" << e.what() << ") " << std::endl;
442             continue;
443          }
444       }
445    }
446 }
447
448 // =====================================================================
449
450 void Bruker2Dicom::DealWithNiveau2(std::string &level2Directory, std::string &currentOutputDirName) {
451
452 // e.g. : at level 2 in B67d1.Bp1/6/pdata
453 //
454 // acqp  fid  imnd  pdata  pulseprogram  spnam0  spnam1
455 //
456
457    bool res = CreateDirectory(currentOutputDirName); 
458
459    if (!res) {
460       std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
461       throw ( BrukerHopelessException ("Hopeless! Level2 output directory creation failure"));        
462       //exit (0);
463    }
464
465    GDCM_NAME_SPACE::DirList dirList(level2Directory, false, true); // DON'T get recursively the list of files
466
467    GDCM_NAME_SPACE::DirListType fileNames;
468    fileNames = dirList.GetFilenames();
469
470    char outputDirName[(unsigned int) PATH_MAX+2];
471
472    // -----------------------------------------------------
473    // Iterate to ALL the objets(files/directories) found in the input directory
474    // -----------------------------------------------------
475    GDCM_NAME_SPACE::DirListType::iterator it;
476    bool canOpen;
477
478    if (verbose)
479    for (it = fileNames.begin();
480         it != fileNames.end();
481       ++it)
482    {
483       if ( ! boost::filesystem::is_directory(*it) )
484       { 
485          std::cout << "--- --- [" << *it << "] is a file.." << std::endl;
486       }
487    }
488
489    for (it = fileNames.begin();
490          it != fileNames.end();
491        ++it)
492    {
493       if ( boost::filesystem::is_directory(*it) )
494       {
495
496          if (verbose)
497             std::cout << "--- --- [" << *it << "] is a directory" << std::endl;
498
499         // sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(),
500         //                          GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
501         //                                GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
502   // MUST be 'pdata'!
503
504 //
505 // (interest of previous method :
506 // If unaware user changed the pdata name, it goes on working
507 //
508           std::string str_isa;
509           str_isa = (*it) + 
510                     GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
511                    "isa";
512
513           std::string str_isa_func_name;
514           canOpen = br_isa.LoadFile(str_isa);
515           if (!canOpen)
516           {
517              sprintf(outputDirName, "%s%c%s", currentOutputDirName.c_str(), 
518                                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
519                                           GDCM_NAME_SPACE::Util::GetName(*it).c_str() );
520           }
521           else
522           {
523              br_isa.FillMap();
524              BrukerFieldData b_isa_func_name = br_isa.GetFieldData("ISA_func_name");
525     
526              str_isa_func_name = b_isa_func_name.GetStringValue()[0];
527              cleanString(str_isa_func_name);
528
529              sprintf(outputDirName, "%s%c%s.%s", currentOutputDirName.c_str(), 
530                                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
531                                           GDCM_NAME_SPACE::Util::GetName(*it).c_str(),
532              str_isa_func_name.c_str());
533           }
534           std::string strOutputDirName(outputDirName);
535           try {
536              DealWithNiveau3(*it, strOutputDirName);
537           }
538           catch (BrukerHopelessException &e)
539           {
540              std::cout << "And Exception was thrown in DealWithNiveau3 (" << e.what() << "); " 
541                        << " We skip [" << level2Directory << "]" << std::endl;
542              continue;
543           }
544           catch (BrukerInitException &e)
545           {
546              std::cout << "And Init Exception was thrown in DealWithNiveau3 (" << e.what() << "); " 
547                        << " We skip [" << level2Directory << "]" << std::endl;
548              continue;
549           }
550       }
551    }
552 }
553
554 //
555 // =====================================================================
556 //
557
558 void Bruker2Dicom::DealWithNiveau3(std::string &level3Directory, std::string &currentOutputDirName){
559
560 //
561 // e.g. at level 3, in
562
563    // just to be able to go on checking // JP
564    if ( GDCM_NAME_SPACE::Util::GetName(level3Directory) != "1")
565       return;
566
567    bool res = CreateDirectory(currentOutputDirName);
568
569    if (!res)
570    {
571       std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
572       throw ( BrukerHopelessException ("Hopeless! Level3 output directory creation failure"));
573       //exit (0);
574    }
575
576    GDCM_NAME_SPACE::DirList dirList(level3Directory, false, true); // DON'T get recursively the list of files
577    GDCM_NAME_SPACE::DirListType::iterator it;
578    GDCM_NAME_SPACE::DirListType fileNames;
579    fileNames = dirList.GetFilenames();
580
581    char original2dseqName       [(unsigned int) PATH_MAX+2];
582    char original2dseqName_XXX   [(unsigned int) PATH_MAX+2];   
583    char currentOutputMhdDirName [(unsigned int) PATH_MAX+2];
584
585    char outputMhdFileName       [(unsigned int) PATH_MAX+2];
586    char output2dseqSliceFileName[(unsigned int) PATH_MAX+6]; // think about extra '.dcm'
587    char output2dseqName         [(unsigned int) PATH_MAX+6];
588    char output2dseqCartoName    [(unsigned int) PATH_MAX+6];
589
590    char copyFile[PATH_MAX + PATH_MAX + 5]; // Should be enough!
591    bool canOpen;
592
593    //-------------- try d3proc;
594    char char_d3proc[(unsigned int) PATH_MAX+2];
595
596    sprintf(char_d3proc,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"d3proc" );     
597
598    if (verbose)
599       std::cout << "d3proc: --- => [" << char_d3proc << "]" << std::endl;
600    std::string str_d3proc(char_d3proc);     
601    canOpen = br_d3proc.LoadFile(str_d3proc);
602
603    if (!canOpen)
604    {
605       std::cout << "Hopeless! no 'd3proc' found" << std::endl;
606       throw ( BrukerHopelessException ("Hopeless! no 'd3proc' found"));
607       //exit(0);  /// \TODO throw an exception ! 
608    }
609
610    canOpen = br_d3proc.FillMap();
611    if (!canOpen)
612    {
613       std::cout << "Hopeless! FillMap failed on 'd3proc'" << std::endl;
614       throw ( BrukerHopelessException ("Hopeless! FillMap failed on 'd3proc'"));      
615       //exit(0);  /// \TODO throw an exception !
616    }
617
618    //-------------- end try d3proc;
619
620
621  // -------------------try reco
622
623    char char_reco[(unsigned int) PATH_MAX+2];
624
625    sprintf(char_reco,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );     
626     //str_d3proc = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()))+
627     //             GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
628     //             "d3proc";
629    if (verbose)
630       std::cout << "reco: --- => [" << char_reco << "]" << std::endl;
631
632    std::string str_reco(char_reco);
633    canOpen = br_reco.LoadFile(str_reco);
634
635    if (!canOpen) // we try in directory ../1
636    {
637       if (verbose)
638          std::cout << "[" << str_reco << "] not found " << std::endl;
639       std::string lastDirName = GDCM_NAME_SPACE::Util::GetPath(level3Directory);
640       //lastDirName = GDCM_NAME_SPACE::Util::GetPath(lastDirName);
641       sprintf(char_reco,"%s%c1%c%s", lastDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"reco" );
642       //str_reco=char_reco;
643       canOpen = br_reco.LoadFile(str_reco);
644       if (!canOpen)
645       {
646          std::cout << "Hopeless! cannot find 'reco' in [" << str_reco << "]"  << std::endl;      
647          throw ( BrukerHopelessException ("Hopeless! cannot find 'reco'"));  
648          //exit(0);  /// \TODO throw an exception !    
649       }
650    } else {
651       if (verbose)
652          std::cout << "[" << str_reco << "] successfully Loaded " << std::endl;
653    }
654
655    canOpen = br_reco.FillMap();
656    if (!canOpen)
657    {
658       std::cout << "Hopeless! FillMap failed on [" << str_reco << "]" << std::endl;
659       throw ( BrukerHopelessException ("Hopeless! FillMap failed on 'reco'"));  
660       //exit(0);  /// \TODO throw an exception !
661    } else {
662       if (verbose)
663          std::cout << "[" << str_reco << "] successfully Mapped" << std::endl;
664    }
665
666    //std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
667    // br_reco.PrintSelf();
668    // std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
669    // -------------------end try reco
670
671
672    BrukerFieldData bX = br_d3proc.GetFieldData("IM_SIX");
673    int NX = bX.GetIntValue()[0];
674
675    if (verbose)
676       std::cout << "IM_SIX " << NX << std::endl;
677    BrukerFieldData bY=br_d3proc.GetFieldData("IM_SIY"); 
678    int NY = bY.GetIntValue()[0];
679
680    if (verbose)
681          std::cout << "IM_SIY " << NY << std::endl;
682    /// \todo : check if there are actually 3 dimensions or only 2
683
684    BrukerFieldData bZ= br_d3proc.GetFieldData("IM_SIZ");
685    int nbFrames = bZ.GetIntValue()[0]; 
686    if (verbose)
687          std::cout << "IM_SIZ " << nbFrames << std::endl;
688
689         // WARNING DATTYPE is, either in {ip_short, ip_int, ip_char, ...}, or in {1, 2, 3, ...}
690
691    BrukerFieldData bDPT = br_d3proc.GetFieldData("DATTYPE");
692
693    std::string mhdDataPixelType;
694    int pixelSize;
695    getImhDataType(bDPT, mhdDataPixelType, pixelSize);
696
697
698  /*
699
700  // See mail Denis : 
701  // En regle generale il vaut mieux que l'on passe par RECO_* 
702  // pour extraire les parametres de l'image
703  //
704
705    BrukerFieldData fov = br_method.GetFieldData("PVM_Fov");
706    double fovX = fov.GetDoubleValue()[0];
707    double fovY = fov.GetDoubleValue()[1];
708    if (verbose)
709       std::cout << "FOV (ds method) " << fovX << " " << fovY << std::endl;
710
711    BrukerFieldData spatResol = br_method.GetFieldData("PVM_SpatResol");
712    double spatResolX = spatResol.GetDoubleValue()[0];
713    double spatResolY = spatResol.GetDoubleValue()[1];
714    if (verbose)
715       std::cout << "SpatResol (ds method) " << spatResolX << " " << spatResolY << std::endl;
716      
717 */
718
719 /* ------  */
720 // Better we use 'get' accessors from BrukerImage class, as Denis wrote them
721
722    BrukerFieldData fov = br_reco.GetFieldData("RECO_fov");
723    double fovX = fov.GetDoubleValue()[0];
724    double fovY = fov.GetDoubleValue()[1];
725    if (verbose)
726       std::cout << "FOV (ds reco) " << fovX << " " << fovY << std::endl;
727
728    BrukerFieldData size = br_reco.GetFieldData("RECO_size");
729    double sizeX = size.GetDoubleValue()[0];
730    double sizeY = size.GetDoubleValue()[1];
731
732    if (verbose)
733       std::cout << "SIZE (ds reco) " << sizeX << " " << sizeY << std::endl;
734
735    double spatResolX = fovX / sizeX;
736    double spatResolY = fovY / sizeY;
737
738    if (verbose)
739       std::cout << "spatResol (ds reco : fov/size) " << spatResolX << " " << spatResolY << std::endl;
740
741 /* ------  */
742
743    /// \TODO probabely a more sophisticated accessor will be necessary :
744    ///  (cf : non contiguous slices, overlapping, slice thickness, space between slices, etc)
745
746    BrukerFieldData bsliceDistance = br_method.GetFieldData("PVM_SPackArrSliceDistance");
747    double sliceDistance = bsliceDistance.GetDoubleValue()[0];
748
749    if (verbose)
750       std::cout << "SPackArrSliceDistance (ds method) " << sliceDistance << std::endl;   
751
752 // ----------------------------------------------------------------------------------------
753
754    if (mhd)
755    {
756       sprintf(currentOutputMhdDirName, "%s%c%s", currentOutputDirName.c_str(),
757                                GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "MhdFiles");
758
759       std::string strCurrentOutputMhdDirName(currentOutputMhdDirName);
760       res = CreateDirectory( strCurrentOutputMhdDirName );
761       if (!res) {
762          std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
763          throw ( BrukerHopelessException ("Hopeless!FillMap failed on 'reco'"));  
764          //exit (0);
765       } 
766
767       if (verbose)
768          std::cout << "Directory creation [" <<  currentOutputDirName << "]" << std::endl;
769    }  // end if mhd
770
771    if (verbose)
772          std::cout << "nbFrames " << nbFrames << std::endl;
773    if (verbose)
774          std::cout << "nbSlices " << nbSlices << std::endl;
775    int k;
776    int nbInstants = nbFrames/nbSlices;
777    if (verbose)
778          std::cout << "nbInstants (deduced)" << nbInstants << std::endl;    
779    int instantNb;
780    int sliceNb; 
781    FILE *fp;  // for MHD files
782
783    sprintf( original2dseqName, "%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, "2dseq");
784
785 /**/   
786   // \TODO : tenir compte du bazar precedent 
787
788     // load 2dseq in memory
789
790    fp = fopen(original2dseqName, "rb");
791    if (!fp) 
792    {
793       // try 2dseq_Angio2D ?!?
794
795       sprintf( original2dseqName_XXX, "%s%s", original2dseqName, "_Angio2D");
796       fp = fopen(original2dseqName_XXX, "rb");
797       if (!fp)
798       {
799          std::cout << "Cannot open [" << original2dseqName << "] nor [" <<  original2dseqName_XXX << "] for reading" << std::endl;
800          fclose(fp);     
801          throw ( BrukerHopelessException ("Hopeless! Cannot open '2dseq'"));
802          //exit (0);
803       }
804    }
805
806    unsigned char *buffer_2dseq = new unsigned char[NX*NY*pixelSize*nbSlices*nbInstants];   
807    ///\ TODO : find a safer way to be sure to read everything!
808    size_t lgr = fread(buffer_2dseq, 1, NX*NY*pixelSize*nbSlices*nbInstants, fp);
809
810    // This one will be important!
811    // ---------------------------
812    try {
813       imageSet = CreateImageSet ( );
814    }
815    catch (BrukerInitException& e)
816    {
817       if (verbose)
818          std::cout <<  "an Init Exception was thrown in CreateImageSet ( ); " << e.what() 
819                    <<  "catched in DealWithNiveau3" << std::endl;
820       //return;
821       throw (e);
822    }
823
824    serieNumber++;
825    strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
826    if (nbInstants==1) // creer un seul fichier .mhd  pour toutes les Slices! (images natives)
827    {
828        if (verbose)
829           std::cout << "Single instant : do not split" << std::endl;
830        if (mhd)
831        {
832              sprintf(outputMhdFileName, "%s%cMhdData_All_the_Slices.mhd", currentOutputMhdDirName,
833                                          GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
834              fp=fopen(outputMhdFileName, "w");
835              if (!fp)
836              {
837                 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
838                 throw ( BrukerHopelessException ("Hopeless! Cannot open  mhd file for writting"));
839                 //exit(0);
840              }
841              else
842              {
843                fprintf(fp, "ObjectType = Image\n");
844                fprintf(fp, "NDims = 3\n" );
845                fprintf(fp, "BinaryData = True \n" );
846                fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
847                fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices );
848                fprintf(fp, "HeaderSize = %d\n", 0);
849                //fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
850                fprintf(fp, "ElementSpacing = %lf %lf %lf\n", spatResolX, spatResolY, sliceDistance );
851                fprintf(fp, "Position = 0 0 %d\n", 0 );
852                fprintf(fp, "Offset = 0 0 0\n" );
853                fprintf(fp, "CenterOfRotation = 0 0 0\n" );
854                fprintf(fp, "ElementNumberOfChannels = 1\n" );
855                fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );  
856                fprintf(fp, "ElementDataFile = %s\n", "../2dseq_All_the_Slices" );
857                fclose(fp);     
858              }
859              sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices", 
860                                        currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
861              fp=fopen(output2dseqSliceFileName, "wb");
862              if (!fp)
863              {
864                 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
865                 throw ( BrukerHopelessException ("Hopeless! Cannot open 2dseq file for writting"));             
866              }
867              else
868              {
869                 fwrite( buffer_2dseq, NX*NY*pixelSize, nbSlices, fp);     
870              }
871              fclose(fp);
872              serieNumber ++;
873              strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
874        }  // end if mhd
875        if (dicom)
876        {
877              sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices.dcm", 
878                                        currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
879
880             /* ----------- Write Dicom Image  ---------------*/
881              MakeDicomImage(buffer_2dseq,
882                NX,
883                NY,
884                nbFrames,
885                pixelSize,
886                //fovX/NY, fovY/NY, sliceDistance,
887                spatResolX, spatResolY, sliceDistance,
888                output2dseqSliceFileName,
889                subject_name,
890                day,
891                strStudyUID,
892                strSerieUID,
893                strStudyDescr,
894                strSerieDescr,
895                strStudyTimeDate,
896                0,// index frame number
897                GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
898              );
899        }  // end if dicom
900    }  // end if nbInstants = 1
901
902    else  // more than ONE instant
903    {
904           // Interleaved !
905           // it's (slice1,slide2, ...)t1 ; (slice1,slide2, ...)t2 ; ...
906          unsigned char *pixelsForCurrentSlice = new unsigned char[NX*NY*pixelSize*nbInstants];
907
908          k = 0;
909          for (sliceNb=0; sliceNb<nbSlices; sliceNb++)
910          {
911             if (mhd)
912             {
913                sprintf(outputMhdFileName, "%s%cMhdData_%03d.mhd", currentOutputMhdDirName, 
914                                         GDCM_NAME_SPACE::GDCM_FILESEPARATOR, k  );
915                if (verbose)
916                   std::cout << "--- Output MHD file [" << outputMhdFileName << "]" << std::endl;
917                fp=fopen(outputMhdFileName, "w");
918                if (!fp)
919                {
920                    std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
921                    throw ( BrukerHopelessException ("Hopeless! Cannot open  mhd file for writting"));
922                    //exit(0);
923                }
924                else
925                {
926             /* ----------- Write MHD Image  ---------------*/
927                 //if (verbose)
928                 //   std::cout << "Open sucessfully[" << outputMhdFileName << "] for writting" << std::endl; 
929                    fprintf(fp, "ObjectType = Image\n");
930                    fprintf(fp, "NDims = 3\n" );  
931                    fprintf(fp, "BinaryData = True \n" );  
932                    fprintf(fp, "BinaryDataByteOrderMSB = False\n" );    
933                    fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbInstants);  
934                    fprintf(fp, "HeaderSize = %d\n", 0); 
935                    //fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, 1.0 ); // 
936                    fprintf(fp, "ElementSpacing = %lf %lf %lf\n",spatResolX, spatResolY, 1.0 ); //slice distance : no meaning for temporal serie
937                    fprintf(fp, "Position = 0 0 %d\n", sliceNb );  
938                    fprintf(fp, "Offset = 0 0 0\n" );  
939                    fprintf(fp, "CenterOfRotation = 0 0 0\n" );
940                    fprintf(fp, "ElementNumberOfChannels = 1\n" );  
941                    fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );  
942                    fprintf(fp, "ElementDataFile = ..%c2dseq_Slice_%d\n", GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb ); 
943                    fclose(fp);
944                } // end write MHD
945
946                sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d", 
947                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,sliceNb);
948                fp=fopen(output2dseqSliceFileName, "wb");
949                if (!fp)
950                {     
951                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
952                    throw ( BrukerHopelessException ("Hopeless! Cannot open 2dseqSliceFile file for writting"));            
953                    //exit (0);
954                }
955                int frameSize = NX*NY*pixelSize;
956                for (instantNb=0; instantNb<nbInstants; instantNb++)
957                {
958 // std::cout << "------------SN " << sliceNb << " IN " << instantNb <<  " T " << nbSlices*instantNb + sliceNb << std::endl;
959                     fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
960                             frameSize,
961                             1, fp);
962                }
963                fclose(fp);
964
965 // std::cout << "end writting[" << output2dseqSliceFileName << "]" << std::endl;
966             }  // end if mhd
967    
968             if (dicom)
969             {
970                // desperate try !
971              /* 
972                sprintf(output2dseqSliceFileName, "%sdummy_buffer", 
973                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
974                fp=fopen(output2dseqSliceFileName, "wb");
975                if (!fp)
976                {     
977                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
978                    exit (0);
979                }
980                int frameSize = NX*NY*pixelSize;
981                for (instantNb=0; instantNb<nbInstants; instantNb++)
982                {
983 // std::cout << "------------SN " << sliceNb << " IN " << instantNb <<  " T " << nbSlices*instantNb + sliceNb << std::endl;
984                     fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
985                             frameSize,
986                             1, fp);
987                }
988                fclose(fp);
989
990                fp=fopen(output2dseqSliceFileName, "rb");
991                if (!fp)
992                {     
993                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for reading" << std::endl;
994                    exit (0);
995                }       
996                fread( pixelsForCurrentSlice,
997                             frameSize*nbInstants,
998                             1, fp);
999                fclose(fp);
1000               // end of desperate try !
1001               */
1002
1003                /* ----------- Write Dicom Image  ---------------*/
1004
1005                int frameSize = NX*NY*pixelSize;
1006                for (instantNb=0; instantNb<nbInstants; instantNb++)
1007                {
1008                   memcpy(pixelsForCurrentSlice + frameSize*instantNb, buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize, frameSize);
1009                }
1010
1011                int indOfFirsImageWithinImageSet =  nbSlices*instantNb;
1012                sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d.dcm", 
1013                                                  currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR, sliceNb);
1014
1015                MakeDicomImage(
1016                   pixelsForCurrentSlice,
1017                   NX,
1018                   NY,
1019                   nbInstants,
1020                   pixelSize,
1021                   spatResolX, spatResolY, sliceDistance,
1022                   //fovX/NY, fovY/NY, sliceDistance,
1023                   output2dseqSliceFileName,
1024                   subject_name,
1025                   day,
1026                   strStudyUID,
1027                   strSerieUID,
1028                   strStudyDescr,
1029                   strSerieDescr,
1030                   strStudyTimeDate,
1031                   sliceNb*nbInstants,
1032                   GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
1033                );
1034                if (verbose)
1035                   std::cout << "--- Output DCM file [" << output2dseqSliceFileName << "]" << std::endl;      
1036
1037            } // en if dicom
1038
1039         k++;
1040         }
1041         delete [] pixelsForCurrentSlice;  
1042      }  // end nbInstants == 1
1043    delete [] buffer_2dseq;
1044 /**/
1045
1046
1047    // -----------------------------------------------------
1048    //  deal with MatLab-generated Carto file.
1049    // -----------------------------------------------------
1050
1051    dealWithCarto(fileNames,  NX,  NY,  nbSlices, /*fovX, fovY,*/ spatResolX, spatResolY, sliceDistance,
1052                    copyFile, currentOutputDirName, outputMhdFileName, output2dseqCartoName);
1053 }
1054
1055 // ===========================================================================================
1056
1057 void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX, int NY, int nbSlices, 
1058                                  /*double fovX, double fovY, */
1059                                  double spatResolX, double spatResolY, double sliceDistance,
1060                                  char *copyFile, std::string &currentOutputDirName, 
1061                                  char *outputMhdFileName, char *output2dseqCartoName)
1062 {
1063    // -----------------------------------------------------
1064    //  deal with MatLab-generated Carto file.
1065    // -----------------------------------------------------
1066
1067    const char *code[] = { "ADC", "adc", "TTP", "ttp", "PEAK", "peak", "" };  // add more carto file name identifiers if necessary; end with ""
1068    const char *separator[] =  { "_", ".", "-", "" }; //  add more, if necessary, to ckeck for 2dseq.ADC, 2dseq_ADC, 2dseq-ADC, etc; end with ""
1069    int icode;
1070    int iseparator; 
1071    GDCM_NAME_SPACE::DirListType::iterator it;
1072    char file_name_ident[500];
1073    FILE *fp;
1074
1075    // Iterate to ALL the objets(files/directories) found in the input directory    
1076    for (it = fileNames.begin();
1077         it != fileNames.end();
1078       ++it)
1079    {
1080       if ( boost::filesystem::is_regular(*it) )
1081       //if ( ! boost::filesystem::is_directory(*it) )
1082       {         
1083          if (verbose)
1084             std::cout << "--- [" << *it << "] is a file..." << std::endl;
1085
1086          icode      = 0;
1087          while (code[icode][0] != 0)
1088          { 
1089          iseparator = 0;       
1090          while (separator[iseparator][0] != 0)
1091          {
1092             sprintf(file_name_ident, "2dseq%s%s",separator[iseparator],code[icode]); // e.g  "2dseq_ADC"
1093             //if (verbose)
1094             //   std::cout << "check name ["<<(*it) << "] for string [" << file_name_ident << "]" << std::endl;
1095             std::string::size_type loc = (*it).rfind(file_name_ident); 
1096
1097             if ( loc != std::string::npos )
1098             {
1099
1100        ///\ TODO : find a safer way to be sure to read everything!
1101               unsigned char *buffer_carto = new unsigned char[NX*NY*sizeof(double)*nbSlices];
1102               fp = fopen ( (*it).c_str(), "rb");
1103               if (!fp){
1104                  std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
1105                  throw ( BrukerHopelessException ("Level 1 Unable to open 'carto' file "));
1106                }
1107                fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
1108
1109                     // ?!?  sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
1110                std::cout << "Deal with Carto file :[" <<*it << "], computed length : "
1111                          << NX*NY*sizeof(double)*nbSlices << std::endl;
1112                std::string lastFileName = GDCM_NAME_SPACE::Util::GetName((*it).c_str());
1113                if (mhd)
1114                {
1115                   // Copy the data file in the new directory
1116                   sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
1117                             currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str()); 
1118                   system(copyFile);
1119                   sprintf(outputMhdFileName, "%s%c%s%s",
1120                                          currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".mhd" );
1121                   if (verbose)
1122                     std::cout << "--- Output Carto MHD file [" << outputMhdFileName << "]" << std::endl;
1123
1124                   FILE *fp;
1125                   fp=fopen(outputMhdFileName, "w");
1126                   if (!fp)
1127                   {
1128                      std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
1129                   }
1130                   else
1131                   {
1132                      fprintf(fp, "ObjectType = Image\n");
1133                      fprintf(fp, "NDims = 3\n" );
1134                      fprintf(fp, "BinaryData = True \n" );
1135                      fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
1136                      fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices);
1137                      fprintf(fp, "HeaderSize = %d\n", 0 );
1138                      fprintf(fp, "ElementSpacing = %lf %lf %lf\n",spatResolX, spatResolY, sliceDistance );
1139                      fprintf(fp, "Position = 0 0 0\n" );
1140                      fprintf(fp, "Offset = 0 0 0\n" );
1141                      fprintf(fp, "CenterOfRotation = 0 0 0\n" );
1142                      fprintf(fp, "ElementNumberOfChannels = 1\n" );
1143                      fprintf(fp, "ElementType = %s\n", "MET_DOUBLE" );
1144                      fprintf(fp, "ElementDataFile = %s\n", lastFileName.c_str() );
1145
1146                      fclose(fp);
1147                   }
1148                   if (verbose)
1149                      std::cout << "--- end write Carto MHD file [" << outputMhdFileName << "]" << std::endl;
1150                }  // end if mhd
1151
1152             // ----------- Write Dicom Image  ---------------
1153
1154                if (dicom)
1155                {
1156                   sprintf(output2dseqCartoName, "%s%c%s%s",
1157                                        currentOutputDirName.c_str(),GDCM_NAME_SPACE::GDCM_FILESEPARATOR, lastFileName.c_str(), ".dcm" );
1158                   if (verbose)
1159                      std::cout << "--- end create name output2dseqCartoName file [" << output2dseqCartoName << "]" << std::endl;
1160
1161                   strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID(); //New SerieUID for each carto.
1162                   std::string strNewSerieDescr(strSerieDescr+ "_" +GDCM_NAME_SPACE::Util::GetName((*it).c_str()));
1163                   MakeDicomImage(buffer_carto,
1164                      NX,
1165                      NY,
1166                      nbSlices,
1167                      8, // pixelSize
1168                      //fovX/NY, fovY/NY, sliceDistance,
1169                      spatResolX, spatResolY, sliceDistance,
1170                      output2dseqCartoName,
1171                      subject_name,
1172                      day,
1173                      strStudyUID,
1174                      strSerieUID,
1175                      strStudyDescr,
1176                      strNewSerieDescr,
1177                      strStudyTimeDate,
1178                      0,
1179                      GDCM_NAME_SPACE::CREATED_IMAGE
1180                   );
1181                }  // end if dicom
1182
1183                delete [] buffer_carto;
1184                if (verbose) 
1185                   std::cout << "--- End writing Carto DICOM file [" << output2dseqCartoName << "]" << std::endl;
1186                break; // don't check for more ident on same file name!
1187
1188             }  // end deal with _ADC, -adc, etc
1189           iseparator ++;
1190           }  // end iterate speparators
1191           icode++;
1192           } // end iterate code
1193       } // end boost::filesystem::is_regular(*it)
1194    } // end iterate on all objects (files, dir, etc)
1195 } // end method
1196
1197 // ==========================================================================================================
1198
1199 int Bruker2Dicom::CheckUserDirectory(std::string &userDirName)
1200 {
1201    GDCM_NAME_SPACE::DirList dirList(userDirName, false, true); // DON'T get recursively the list of files
1202
1203    GDCM_NAME_SPACE::DirListType fileNames;
1204    fileNames = dirList.GetFilenames();
1205
1206    std::string path = GDCM_NAME_SPACE::Util::GetPath(*(fileNames.begin()));
1207
1208    std::string subject =  path +
1209                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
1210                           "subject";
1211
1212     std::string acqp = path +
1213                        GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
1214                        "acqp";
1215
1216     if ( boost::filesystem::is_regular(subject) )
1217        subjectFound = true; // user passed a 'study
1218     else
1219        subjectFound = false; // user didnt' pass a 'study 
1220
1221     if ( boost::filesystem::is_regular(acqp) )
1222        acqpFound= true; // user passes a 'serie', not a 'study' 
1223     else
1224        acqpFound = false; // user passed a 'non study' directory; Hope it's a 'set of studies' directory!
1225
1226    int type;    
1227    if  (subjectFound )  type = 1; // user passed a 'study
1228    else if  (acqpFound) type = 2; // user passed a 'serie' 
1229    else                 type = 3; // user passed a 'non study' directory; Hope it's a 'set of studies' directory!
1230
1231    return type;   
1232 }
1233
1234 // ==========================================================================================================
1235
1236 bool Bruker2Dicom::CreateDirectory(std::string &OutputDirName)
1237 {
1238    std::string systemCommand;
1239    
1240    if (verbose)
1241       std::cout << "Check for output directory :[" << OutputDirName << "]."
1242                 <<std::endl;
1243    if ( ! boost::filesystem::is_directory(OutputDirName) )    // dirout not found
1244    {
1245       systemCommand = "mkdir " + OutputDirName;        // create it!      
1246       if (verbose)
1247          std::cout << systemCommand << std::endl;
1248       system (systemCommand.c_str());
1249       if ( ! boost::filesystem::is_directory(OutputDirName) ) // be sure it worked
1250       {
1251          if (verbose) 
1252             std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
1253          //return 0;
1254          throw ( BrukerHopelessException ("Level 1 output directory creation failure "));
1255       }
1256       else
1257       {
1258          if (verbose) 
1259            std::cout << "Directory [" << OutputDirName << "] created." << std::endl;
1260       }
1261    }
1262    else
1263    {
1264        if (verbose)
1265             std::cout << "Output Directory [" << OutputDirName << "] already exists; Used as is." << std::endl;
1266    }
1267    return 1;
1268 }
1269
1270 // ===========================================================================================
1271
1272 /// \TODO move cleanString to 'crea' ?
1273
1274 void Bruker2Dicom::cleanString(std::string &s)
1275 {
1276    int l = s.size();
1277    if (s[l-1] == 0x0A || s[l-1] == 0x0D ) // CR or NL
1278    {
1279       l--;
1280       s = s.substr(0, l);
1281    }
1282    if (s[l-1] == ' ' ) // blank space
1283    {
1284       l--;
1285       s = s.substr(0, l);
1286    }   
1287
1288    if (s[0] == '<')      
1289       s= s.substr(1,l-2);
1290    std::string repChar("_");
1291    GDCM_NAME_SPACE::Util::ReplaceSpecChar(s, repChar);
1292 }
1293
1294 // ===========================================================================================
1295
1296 void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPixelType, int &pixelSize)
1297
1298    if(bDPT.GetDataType() == "string")
1299    {         
1300          std::string brukerDataPixelType = bDPT.GetStringValue()[0];
1301          if (verbose)
1302             std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
1303          //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1304          
1305          if (brukerDataPixelType ==  "ip_short") {
1306             mhdDataPixelType = "MET_USHORT";
1307             pixelSize = 2;
1308          }
1309          if (brukerDataPixelType ==  "ip_int") {
1310             mhdDataPixelType = "MET_UINT";
1311             pixelSize = 4;
1312          }
1313          if (brukerDataPixelType ==  "ip_char") {
1314              mhdDataPixelType = "MET_UCHAR";
1315              pixelSize = 1;
1316          }
1317                   /// \TODO : finish the list
1318     /*
1319     case 0 : fp << "ElementType = MET_CHAR" << std::endl;
1320       break;
1321     case 1 : fp << "ElementType = MET_UCHAR" << std::endl;
1322       break;
1323     case 2 : fp << "ElementType = MET_SHORT" << std::endl;
1324       break;
1325     case 3 : fp << "ElementType = MET_USHORT" << std::endl;
1326       break;
1327     case 4 : fp << "ElementType = MET_INT" << std::endl;
1328       break;
1329     case 5 : fp << "ElementType = MET_UINT" << std::endl;
1330       break;
1331     case 6 : fp << "ElementType = MET_FLOAT" << std::endl;
1332       break;
1333     case 7 : fp << "ElementType = MET_DOUBLE" << std::endl;  
1334     */
1335     }
1336     else
1337     {
1338          int brukerDataPixelType = bDPT.GetIntValue()[0];
1339          if (verbose)
1340             std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
1341          //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
1342  
1343 // Cross your fingers !!!
1344
1345 // pb : found values : 2, 3, 5
1346
1347          if (brukerDataPixelType ==  2) {
1348             mhdDataPixelType = "MET_USHORT";
1349             pixelSize = 2;
1350          }
1351          if (brukerDataPixelType ==  3) {
1352             mhdDataPixelType = "MET_USHORT";
1353             pixelSize = 2;
1354          }    
1355          if (brukerDataPixelType ==  1) {
1356             mhdDataPixelType = "MET_UCHAR";
1357             pixelSize = 1;
1358          }     
1359     }
1360 }
1361
1362 // ===========================================================================================
1363
1364 std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
1365 {
1366          std::vector<BrukerImage> imageSet;      
1367          br_acqp.SetLoopStructure();
1368          std::vector<int> tempVect                      = br_acqp.GetLoopStructure() ;
1369          std::map<std::string, BrukerFieldData> map     = br_acqp.GetBrukerHeaderMap();
1370
1371          bool result                                    = br_acqp.ObjectVaryingProperties.init(map,tempVect);
1372
1373          if (result == false)
1374          {
1375             throw ( BrukerInitException ("ObjectVaryingProperties.init() failure in Bruker2Dicom::CreateImageSet()") );
1376          }
1377
1378          br_acqp.SetImageLoopStructure();
1379          br_acqp.SetBrukerImageList();
1380          std::vector<std::vector<int> > brukerImageList = br_acqp.GetBrukerImageList();
1381
1382          BrukerImage image(br_acqp,br_reco);
1383          image.Init(br_acqp,br_reco,1); 
1384
1385          for(int i=0;i<brukerImageList.size();i++)
1386          {
1387             image.Init(br_acqp,br_reco,i);    
1388             imageSet.push_back(image);
1389          }
1390
1391  // Just for checking
1392  /*
1393
1394          std::vector<std::vector <double> > imageOrientation;
1395          std::vector <double> imagePosition; 
1396          for(int i=0;i<brukerImageList.size();i++)
1397          {
1398            // fread(buffer_2dseq, NX*NY*pixelSize*nbSlices*nbInstants, 1, fp);   
1399
1400            imagePosition = imageSet[i].getTranslationVectorRPS2XYZ();
1401            std::cout << "Position " << imagePosition[0] << " " 
1402                      << imagePosition[1] << " "  << imagePosition[2] ;
1403            imageOrientation =  imageSet[i].getRotationMatrixRPS2XYZ();
1404            std::cout << "\t  Orientation " ;
1405            for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
1406               std::cout << imageOrientation[i1][i2] << " ";CreateImageSet
1407
1408            //std::cout << "\t  Abs Time " << imageSet[i].getAbsoluteTimePosition();
1409            std::cout << "\t  Relat Time " << imageSet[i].getRelativeTimePosition();
1410
1411            std::cout << "\t [";
1412            for (int i3=0; i3<imageSet[i].getLoopStamp().size();i3++)
1413               std::cout << " " << imageSet[i].getLoopStamp()[i3];
1414            std::cout << "]" << std::endl;       
1415          } 
1416 */
1417    return imageSet;
1418 }
1419
1420 // ===========================================================================================
1421
1422 void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels, 
1423               int X, 
1424               int Y,
1425               int nbFrames,
1426               int pixelSize,
1427               double spacingX, double spacingY, double sliceDistance, 
1428               std::string dcmImageName,
1429               const std::string &patientName,
1430               const char *day,
1431               std::string &studyUID,
1432               std::string &serieUID,
1433               std::string &studyDescr,
1434               std::string &serieDescr,
1435               std::string &strStudyTimeDate,
1436               int imgNum,
1437               GDCM_NAME_SPACE::ImageContentType contentType
1438       )
1439 {  
1440    std::ostringstream str;
1441
1442    GDCM_NAME_SPACE::File *file;
1443    file = GDCM_NAME_SPACE::File::New();
1444
1445   // Set the image size
1446    str.str(""); 
1447    str << X;
1448    file->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
1449    str.str("");
1450    str << Y;
1451    file->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
1452
1453    if (nbFrames != 1)
1454    {
1455       str.str("");
1456       str << nbFrames;
1457       file->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames  
1458    }
1459
1460   // Set the pixel type
1461   //      //8, 16, 32, 64 (for double ?)
1462    str.str("");
1463    str << pixelSize*8;
1464
1465   // Bits Allocated
1466    file->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
1467
1468    file->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
1469
1470    str.str("");
1471    str << pixelSize*8-1;     
1472    file->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
1473
1474   // Set the pixel representation // 0/1 , 0=unsigned
1475    file->InsertEntryString("1",0x0028,0x0103, "US"); // Pixel Representation
1476
1477   // Set the samples per pixel // 1:Grey level, 3:RGB
1478    file->InsertEntryString("1",0x0028,0x0002, "US"); // Samples per Pixel
1479
1480 //  0028 0030 DS 2 Pixel Spacing
1481    str.str("");
1482    str << spacingX << "\\" << spacingY;
1483    file->InsertEntryString(str.str(),0x0028,0x0030, "DS"); // Pixel Spacing     
1484
1485  //   0018 0050 DS 1 Slice Thickness 
1486    str.str("");    
1487    str << sliceDistance;
1488    file->InsertEntryString(str.str(),0x0018,0x0050, "DS"); 
1489
1490 //    0020 0011 IS 1 Series Number
1491    str.str("");    
1492    str << serieNumber;
1493    file->InsertEntryString(str.str(),0x0020,0x0011, "IS");
1494
1495 //    0020|0013 [IS]  [Instance Number] 
1496    instanceNumber++;
1497    str.str("");    
1498    str << instanceNumber;
1499    file->InsertEntryString(str.str(),0x0020,0x0013, "IS");
1500
1501   // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
1502   //  file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
1503   // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI");  // [SOP Class UID]
1504
1505 // OK : MR is NOT multiframe, but I want just a quick an dirty solution
1506
1507 // 1.2.840.10008.5.1.4.1.1.4         MR Image Storage
1508    file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
1509    file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI");  // [SOP Class UID]     
1510
1511   // if (strlen(patientName) != 0)
1512    file->InsertEntryString(patientName.c_str(),0x0010,0x0010, "PN"); // Patient's Name
1513    file->InsertEntryString(patientName.c_str(),0x0010,0x0020, "LO"); // Patient's ID
1514
1515    file->InsertEntryString(studyUID, 0x0020, 0x000d, "UI");
1516    file->InsertEntryString(serieUID, 0x0020, 0x000e, "UI");
1517
1518 //  0008 0020 DA 1 Study Date
1519 //  0008 0030 TM 1 Study Time
1520
1521 /// \TODO split into 2 strings!
1522    file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
1523    file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),  0x0008,0x0030, "TM");
1524
1525    file->InsertEntryString(studyDescr, 0x0008,0x1030, "LO");  // Study Description  
1526    file->InsertEntryString(serieDescr, 0x0008,0x103e, "LO");  // Series Description 
1527
1528 //0008|0060 [CS] [Modality] 
1529    file->InsertEntryString("MR",0x0008,0x0060, "CS");
1530
1531 // 0020 0037 DS 6 Image Orientation (Patient)
1532    char charImageOrientation[256];
1533
1534 /*
1535 std::cout << "charImageOrientation  " << 
1536                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0] << " " <<
1537                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1] << " " <<
1538                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2] << " " <<
1539                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0] << " " <<
1540                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1] << " " <<
1541                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] << std::endl ;
1542 */      
1543    sprintf(charImageOrientation,"%f\\%f\\%f \\ %f\\%f\\%f",
1544                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0],
1545                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1],
1546                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2],
1547                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0],
1548                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1],
1549                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] ) ;
1550
1551    file->InsertEntryString(charImageOrientation,0x0020,0x0037, "DS");
1552
1553 // 0020 0032 DS 3 Image Position (Patient) 
1554
1555    char charImagePosition[256];   
1556    sprintf(charImagePosition,"%f\\%f\\%f", 
1557                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[0], 
1558                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[1],
1559                              imageSet[imgNum].getTranslationVectorRPS2XYZ()[2]);
1560
1561    file->InsertEntryString(charImagePosition,0x0020,0x0032, "DS");  //0020 0032 DS 3 Image Position (Patient) 
1562
1563    // Private creator
1564    /*
1565
1566 0029|0010 [LO]   [Private Creator] [CREATIS HEADER ]
1567 0029|0011 [LO]   [Private Creator] [CREATIS for BRUKER to DICOM]
1568 0029|1031 [LO]   [] [4.0.7571167 ]
1569 0029|1032 [UL]   [] [1440000] =0x(15f900)
1570
1571 > $$ Thu Jul 30 17:29:46 2009 CEST (UT+2h)  mwiart
1572 > $$ /opt/PV4.0/data/mwiart/nmr/dha80.Uw1/4/method
1573 > ##$Method=DtiEpi
1574 > ##$PVM_DwNDiffDir=3             % 3 directions
1575 > ##$PVM_DwNDiffExpEach=2         % 2 valeurs de b par direction
1576 > ##$PVM_DwAoImages=1             % 1 image pour b=0
1577 > ##$PVM_DwBvalEach=( 2 )         % Valeurs de b
1578 > 1500.000000 3000.000000
1579 >
1580 > $$ Wed Dec  2 09:56:01 2009 UTC (UT+0h)  mwiart
1581 > $$ /opt/Pv5.0/data/mwiart/nmr/ECI7.Wx1/4/method
1582 > ##$Method=DtiEpi
1583 > ##$PVM_DwNDiffDir=3             % 3 directions
1584 > ##$PVM_DwNDiffExpEach=2         % 2 valeurs de b par direction
1585 > ##$PVM_DwAoImages=1             % 1 image pour b=0
1586 > ##$PVM_DwBvalEach=( 2 )         % Valeurs de b
1587 > 1500 3000
1588 >
1589 > $$ Wed Dec  2 10:14:27 2009 UTC (UT+0h)  mwiart
1590 > $$ /opt/Pv5.0/data/mwiart/nmr/ECI7.Wx1/5/method
1591 > ##$Method=DtiStandard
1592 > ##$PVM_DwNDiffDir=1             % 1 direction
1593 > ##$PVM_DwNDiffExpEach=2         % 2 valeurs de b
1594 > ##$PVM_DwAoImages=0             % 0 image pour b=0
1595 > ##$PVM_DwBvalEach=( 2 )         % Valeurs de b
1596 > 138 1600
1597 >
1598    */
1599
1600    file->InsertEntryString("CREATIS HEADER", 0x0029,0x0010, "LO");
1601    file->InsertEntryString("CREATIS FOR BRUKER-TO-DICOM", 0x0029,0x0011, "LO");
1602
1603    BrukerFieldData brf_method            = br_method.GetFieldData("Method");
1604    const std::vector<std::string> method = brf_method.GetStringValue();
1605
1606   // std::string method = br_method.GetFieldData("Method").GetStringValue();    
1607    file->InsertEntryString(method[0], 0x0029,0x0100, "LO");
1608
1609    std::cout << " method[" << method[0]  << "]" << std::endl;
1610    if (method[0] == "DtiEpi" || method[0] == "DtiStandard")
1611    {
1612      // const std::vector<int> NDiffDir       = br_method.GetFieldData("PVM_DwNDiffDir").GetIntValue();
1613       BrukerFieldData brf_NDiffDir    = br_method.GetFieldData("PVM_DwNDiffDir");
1614       const std::vector<int> NDiffDir = brf_NDiffDir.GetIntValue();
1615
1616       //const std::vector<int> NDiffExpEach   = br_method.GetFieldData("PVM_DwNDiffExpEach").GetIntValue();
1617       BrukerFieldData brf_NDiffExpEach      = br_method.GetFieldData("PVM_DwNDiffExpEach");
1618       const std::vector<int> NDiffExpEach   =brf_NDiffExpEach.GetIntValue();
1619
1620 //      const std::vector<int> AoImages     = br_method.GetFieldData("PVM_DwAoImages").GetIntValue();
1621       BrukerFieldData brf_AoImages        = br_method.GetFieldData("PVM_DwAoImages");
1622       const std::vector<int> AoImages     = brf_AoImages.GetIntValue();
1623
1624       BrukerFieldData brf_DwBvalEach       = br_method.GetFieldData("PVM_DwBvalEach");
1625       const std::vector<double> DwBvalEach = brf_DwBvalEach.GetDoubleValue();
1626
1627  std::cout << "nb directions : " <<  NDiffDir[0] << " nb valeurs de b par direction : " << NDiffExpEach[0] 
1628            << " nb images for b=0 : " << AoImages[0] << std::endl;
1629
1630        str.str(""); 
1631        str << NDiffDir[0];
1632        file->InsertEntryString(str.str(),0x0029,0x0101,"US"); // nb de directions
1633        str.str(""); 
1634        str << NDiffExpEach[0];
1635        file->InsertEntryString(str.str(),0x0029,0x0102,"US"); // nb valeurs de b par direction       
1636        str.str(""); 
1637        str << AoImages[0];
1638        file->InsertEntryString(str.str(),0x0029,0x0103,"US"); // nb images pour b=0
1639
1640        str.str("");
1641        for (unsigned int i=0; i<NDiffExpEach[0]; i++) {
1642           str << DwBvalEach[i];
1643           if (i!=AoImages[0])
1644              str << "\\";
1645       }
1646       file->InsertEntryString(str.str(),0x0029,0x0104,"DS"); // Valeurs de b
1647    }   
1648
1649 // 0020 0x1041 DS 1 Slice Location 
1650 //        sprintf(charImagePosition,"%f",float(imgNum));
1651 //        file->InsertEntryString(charImagePosition,0x0020,0x1041, "DS");   
1652 /*
1653   // Set Rescale Intercept
1654         str.str("");
1655         str << div;  
1656         file->InsertEntryString(str.str(),0x0028,0x1052,"DS");
1657
1658   // Set Rescale Slope
1659         str.str("");
1660         str << mini;  
1661         file->InsertEntryString(str.str(),0x0028,0x1053,"DS");
1662 */
1663
1664    GDCM_NAME_SPACE::FileHelper *fileH;
1665    fileH = GDCM_NAME_SPACE::FileHelper::New(file);
1666    fileH->SetContentType(contentType);
1667
1668    // cast is just to avoid warnings (*no* conversion is performed)
1669    //fileH->SetImageData((uint8_t *)img,int(maxX*maxY)*sizeof(uint16_t)); // troubles when maxX, mayY are *actually* float!
1670
1671 //std::cout << "--------------------------------  X*Y*nbFrames*pixelSize " << X << " " << Y << " " << nbFrames << " " << pixelSize << std::endl; 
1672
1673    fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
1674    fileH->SetWriteModeToRaw(); 
1675    fileH->SetWriteTypeToDcmExplVR();
1676    if( !fileH->Write(dcmImageName)) {
1677       std::cout << "Failed for [" << dcmImageName << "]\n"
1678                 << "           File is unwrittable" << std::endl;               
1679       file->Delete();
1680       fileH->Delete();          
1681       throw ( BrukerHopelessException ("Level 1 Unable to write Dicom file "));
1682    }
1683    //if (verbose)
1684    //   file->Print();
1685
1686    file->Delete();
1687    fileH->Delete();  
1688 }