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