]> Creatis software - creaBruker.git/commitdiff
run creaBruker with gdcm2
authorFrederic Cervenansky <Frederic.Cervenansky@creatis.insa-lyon.fr>
Fri, 17 Sep 2010 12:05:04 +0000 (12:05 +0000)
committerFrederic Cervenansky <Frederic.Cervenansky@creatis.insa-lyon.fr>
Fri, 17 Sep 2010 12:05:04 +0000 (12:05 +0000)
CMakeLists.txt
lib/src1/CMakeLists.txt
lib/src1/bruker2dicom2.cxx [new file with mode: 0644]
lib/src1/bruker2dicom2.h [new file with mode: 0644]

index f54d1822f1f655ff327d7f16e05b3a9cf79a8721..25ce48e8ffa6cf348e8553c7cce5a042b77cb10d 100644 (file)
@@ -56,9 +56,9 @@ CREA_PREVENT_IN_SOURCE_BUILD()
 #  if you need to LINK against crea
 #  (and not only use its macros)
 SET(USE_CREA      ON)
-SET(USE_GDCM      ON)
+OPTION(USE_GDCM      ON)
 SET(USE_GDCM_VTK  ON)
-SET(USE_GDCM2     OFF)
+OPTION(USE_GDCM2     OFF)
 SET(USE_WXWIDGETS OFF)
 SET(USE_KWWIDGETS OFF)
 SET(USE_VTK       OFF)
index c5149f69e3efa8caf568d705717f7e7662b3f2fe..6cc702baf977541394889fb21f478000c29127d3 100644 (file)
@@ -39,7 +39,17 @@ IF ( BUILD_${LIBRARY_NAME} )
   #
   #    )
   #----------------------------------------------------------------------------
-
+  #TO SWITCH BETWEEN GDCM AND GDCM2
+  message ("avant... ${creaBruker_SOURCES}")
+if(USE_GDCM2)
+       LIST(REMOVE_ITEM ${LIBRARY_NAME}_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/bruker2dicom.cxx")
+       LIST(REMOVE_ITEM ${LIBRARY_NAME}_HEADERS "${CMAKE_CURRENT_SOURCE_DIR}/ bruker2dicom.h")
+endif()
+if(USE_GDCM)
+       LIST(REMOVE_ITEM ${LIBRARY_NAME}_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/bruker2dicom2.cxx")
+       LIST(REMOVE_ITEM ${LIBRARY_NAME}_HEADERS "${CMAKE_CURRENT_SOURCE_DIR}/ bruker2dicom2.h")
+endif()
+  message ("apres... ${creaBruker_SOURCES}")
   #----------------------------------------------------------------------------
   # LIBRARY DEPENDENCIES (LIBRARIES TO LINK WITH)
   SET ( ${LIBRARY_NAME}_LINK_LIBRARIES
diff --git a/lib/src1/bruker2dicom2.cxx b/lib/src1/bruker2dicom2.cxx
new file mode 100644 (file)
index 0000000..a05d413
--- /dev/null
@@ -0,0 +1,1894 @@
+#include "bruker2dicom2.h"
+#include "brukerexception.h"
+
+#include <gdcmAttribute.h>
+#include <boost/filesystem.hpp>
+#include <boost/algorithm/string.hpp>
+
+
+#ifndef PATH_MAX // If not defined yet : do it 
+   #define PATH_MAX 2048
+#endif 
+
+        bool Bruker2Dicom::Execute()
+        {
+            
+            //--- first, Test the system----//
+             bool bigEndian = gdcm::ByteSwap<uint16_t>::SystemIsBigEndian();
+            gdcm::SwapCode sc = gdcm::SwapCode::Unknown;
+            if ( gdcm::ByteSwap<uint16_t>::SystemIsBigEndian() )
+            {
+                sc = gdcm::SwapCode::BigEndian;
+             }
+            else if ( gdcm::ByteSwap<uint16_t>::SystemIsLittleEndian() )
+            {
+                sc = gdcm::SwapCode::LittleEndian;
+            }
+            else // sc == gdcm::SwapCode::Unknown
+            {
+                return 1;
+            }
+
+            // ----- Check input directory name -----
+            if ( ! boost::filesystem::is_directory(InputDirName) )
+            {
+                    std::cout << "KO : [" << InputDirName << "] is not a Directory." << std::endl;
+                    return 0;
+            }
+            else
+            {
+                if (verbose)
+                    std::cout << "OK : [" << InputDirName << "] is a Directory." << std::endl;
+            }
+
+             // ----- Check output directory name -----
+            if ( ! boost::filesystem::is_directory(OutputDirName) )
+            {
+                bool res=CreateDirectory(OutputDirName);
+                if (!res) 
+                {
+                     std::cout << "[" << OutputDirName << "] Directory creation failure " << std::endl;
+                     throw ( BrukerHopelessException ("Output directory creation failure "));
+                }
+            }
+            else
+            {
+                if(verbose)
+                        std::cout << "[" << OutputDirName << "] already exist " << std::endl;
+            }
+
+            // Deal with level 0
+            // Level 0  is the original directory
+            // who could contain  "1  2  3  4  5  6"  directories  and "AdjStatePerStudy  subject" files  
+            std::string strDirNamein(InputDirName);
+            boost::filesystem::directory_iterator it(InputDirName), it_end;
+            subjectFound = false;
+            acqpFound = false;
+            for(; it != it_end; ++it)
+            {
+                   if(! boost::filesystem::is_directory( (*it) ) )
+                   {
+                       if( (*it).filename() == "subject")
+                       {
+                           subjectFound = true;
+                       }
+                       if( (*it).filename() == "acqp")
+                       {
+                           acqpFound = true;
+                       }
+                   }
+            }
+
+            // 1 : if subjectFound                       : user passed a Single Study Directory
+            // 2 : if NOT subjectFound and acqpFound     : user passed a Serie Directory
+            // 3 : if NOT subjectFound and NOT acqpFound : user passed a 'non Study Directory' (Hope it's a set of Single Study Directories)
+            int type;
+            if  (subjectFound )  type = 1; // user passed a 'study
+            else if  (acqpFound) type = 2; // user passed a 'serie' 
+            else                 type = 3; // user passed a 'non study' directory; Hope it's a 'set of studies' directory!
+            switch (type)
+            {
+                case 1:  {
+                    std::string subject = InputDirName +   VALID_FILE_SEPARATOR;
+                    subject += "subject";
+                    boost::algorithm::replace_all( subject,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+                    bool canOpen = br_subject.LoadFile(subject);
+                    if (!canOpen)
+                    {
+                        std::cout << "Hopeless! 'subject' found / cannot be open" << std::endl;
+                        throw ( BrukerHopelessException ("Hopeless! 'subject' found in root input directory / cannot be open"));
+                    }
+                    else
+                    {
+                        br_subject.FillMap();
+                        // get info for 'Study Description'  
+                        BrukerFieldData b_name=br_subject.GetFieldData("SUBJECT_name_string");
+                        subject_name = b_name.GetStringValue()[0];
+                        strPatientName = subject_name;
+                        cleanString(subject_name);
+                        DealWithSingleStudyDirectory (InputDirName, OutputDirName);
+                       }
+                    break;
+                }
+
+                case 2: 
+                    {
+                     subject_name = "defaultPatName";
+                        strPatientName = subject_name;
+                     DealWithSingleStudyDirectory (InputDirName,OutputDirName);
+                        break;
+                    }
+      
+
+      case 3: {
+         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;
+//      DealWithMultiStudyDirectory (fileNames);
+        break;
+      }
+   }
+}
+
+// ----------------------------------------------------------------------------------------------------------
+
+void Bruker2Dicom::DealWithMultiStudyDirectory (gdcm::Directory::FilenamesType &dirNames,const  std::string &currentOutputDirName)
+{
+    gdcm::Directory::FilenamesType::iterator it;
+
+   for (it = dirNames.begin();
+         it != dirNames.end();
+       ++it)
+   {
+      if ( boost::filesystem::is_directory(*it) )
+      {
+         subjectFound = false;
+         if (verbose)
+            std::cout << "in 'DealWithMultiStudyDirectory' [" << *it << "] is a directory" << std::endl;
+         
+         gdcm::Directory dirList;
+         dirList.Load(*it);
+         gdcm::Directory::FilenamesType fileNames;
+         fileNames = dirList.GetFilenames();
+
+         gdcm::Filename file(fileNames.begin()->c_str());
+         std::string path = file.GetPath();
+         std::string subject =  path +
+                                VALID_FILE_SEPARATOR +
+                                "subject";
+        boost::algorithm::replace_all( subject,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+         if (! boost::filesystem::is_regular(subject) )
+         {
+           std::cout << "no [" << subject << "] file found" << std::endl;
+           continue;
+         }
+
+         bool canOpen = br_subject.LoadFile(subject);
+         if (!canOpen)
+         {
+            std::cout << "Hopeless! 'subject' found / cannot be open" << std::endl;
+            throw ( BrukerHopelessException ("Hopeless! 'subject' found in root input directory / cannot be open"));
+         }
+         else
+         {
+            br_subject.FillMap();
+           subjectFound = true; // Hope so! (full checking needed!)
+
+            BrukerFieldData b_name=br_subject.GetFieldData("SUBJECT_name_string");
+            subject_name = b_name.GetStringValue()[0];
+            strPatientName = subject_name;
+            cleanString(subject_name);  
+        
+            DealWithSingleStudyDirectory(dirList.GetDirectories().begin()->c_str(), currentOutputDirName);
+        }  
+      }
+      else
+      {
+         if (verbose)
+            std::cout << "[" << *it << "] is NOT a directory; skipped!" << std::endl; 
+      }   
+   } 
+}
+
+// ----------------------------------------------------------------------------------------------------------
+
+void Bruker2Dicom::DealWithSingleStudyDirectory  (const std::string &dirname, const std::string &i_outputDir) //(gdcm::Directory::FilenamesType &fileNames)
+{
+     bool res;  
+      // creation directory : 'nom du patient'
+     std::string output =  createDirectory(subject_name.c_str(), i_outputDir);
+
+    if (subjectFound)
+    {
+       BrukerFieldData b_entry=br_subject.GetFieldData("SUBJECT_entry");
+       subject_entry = b_entry.GetStringValue()[0];
+       //cleanString(subject_entry);
+       subject_entry = subject_entry.substr(11, subject_entry.size()-11);
+  
+       BrukerFieldData b_position=br_subject.GetFieldData("SUBJECT_position");
+       subject_position = b_position.GetStringValue()[0];
+       //cleanString(subject_position);
+       subject_position = subject_position.substr(9, subject_position.size()-9);
+       BrukerFieldData b_date=br_subject.GetFieldData("SUBJECT_date");
+       subject_date = b_date.GetStringValue()[0];
+       strStudyTimeDate = subject_date;
+       cleanString(subject_date);
+       BrukerFieldData b_study_name=br_subject.GetFieldData("SUBJECT_study_name");
+       subject_study_name = b_study_name.GetStringValue()[0];
+       subject_study_name = subject_study_name.substr(1, subject_study_name.size()-2);
+       cleanString(subject_study_name);
+   }
+   else  // Desperate trick when file 'subject' is missing
+   {
+      subject_entry      = "HeadFirst";            // Why not?
+      subject_position   = "Supine";               // Why not?
+      strStudyTimeDate   = "06_06_06_6_June_1666"; // Why not?
+      subject_date       = "6_June_1666";          // Why not?
+      subject_study_name = "defStudyName";         // Why not? 
+   }
+    // subject_name is already in 'Patient Name' 
+    strStudyDescr = /*subject_name + "." + */ subject_study_name /*+ "." + subject_entry + "." + subject_position + "." + subject_date*/;
+
+    // creation directory : 'nom de la Study'
+    output = createDirectory(strStudyDescr, output);
+
+    gdcm::UIDGenerator uid;
+   strStudyUID     = uid.Generate();
+   serieNumber    = 0;
+   instanceNumber = 0;
+
+   // -----------------------------------------------------
+   // Iterate to ALL the objets(files/directories) found in the input directory
+   // (this is level ZERO)
+   // each Directory (name : 1, 2, 3, ...) will be a Dicom Serie
+   // -----------------------------------------------------
+      boost::filesystem::directory_iterator it(dirname), end_iter;
+         for(; it != end_iter; ++it)
+        {
+         if(boost::filesystem::is_directory(*it))
+            {
+             std::string fname = (*it).filename() ;
+              //if (fname == "AdjResult")                  continue; what's the point?
+             boost::filesystem::directory_iterator it_level((*it));
+            bool bAcqp = false;
+            std::string nextLevel;
+            std::string strAcqp;
+            std::string nameAcqp;
+            for(; it_level != end_iter; ++it_level)
+            {
+                if( (*it_level).filename() == "acqp")
+                {
+                    strAcqp =  (*it_level).string();
+                    nameAcqp = (*it_level).filename();
+                    boost::algorithm::replace_all( strAcqp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+                    bAcqp = true;
+               }
+               else if (boost::filesystem::is_directory( (*it_level) ) && nextLevel == "")
+               {
+                   nextLevel = (*it_level).string(); // Hope we found only one directory
+               }
+               else
+               {
+                   // nothing
+               }
+           }
+
+           if ( bAcqp)
+           {
+               std::string acqp_scan_name;
+               std::string acqp_method;
+               std::string acqp_protocol_location; 
+               br_acqp.LoadFile(strAcqp);
+               br_acqp.FillMap();
+               BrukerFieldData b_protocol_location=br_acqp.GetFieldData("ACQ_protocol_location");
+               acqp_protocol_location = b_protocol_location.GetStringValue()[0];
+               cleanString(acqp_protocol_location);
+              
+               BrukerFieldData b_scan_name=br_acqp.GetFieldData("ACQ_scan_name");
+               acqp_scan_name = b_scan_name.GetStringValue()[0];
+              cleanString(acqp_scan_name);
+
+              BrukerFieldData b_method=br_acqp.GetFieldData("ACQ_method");
+                 b_method.PrintSelf(); // why?
+              acqp_method = b_method.GetStringValue()[0];
+              cleanString(acqp_method);
+        
+              BrukerFieldData b_list_size = br_acqp.GetFieldData("ACQ_O1_list_size");
+              nbSlices =  b_list_size.GetIntValue()[0];
+             strSerieDescr = fname
+                         + "." + acqp_scan_name
+                         + "." + acqp_method.c_str();
+
+
+         /*sprintf(outputDirName, "%s%c%s", i_outputDir.c_str(), VALID_FILE_SEPARATOR, strSerieDescr.c_str() );
+         std::string temp(outputDirName);
+         boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);*/
+           output = createDirectory(strSerieDescr, output);
+        if (verbose)
+           printf ("outputDirName [%s]\n", output);
+        try {
+
+            DealWithNiveau1( (*it).string(), output);
+             }
+               catch (BrukerHopelessException &e)
+               {
+                std::cout << "And Exception was thrown in DealWithNiveau1 (" << e.what() << ") " << std::endl;
+                continue;
+               }
+           }
+      }
+   } // end of : for (GDCM_NAME_SPACE::DirListType::iterator it
+}
+
+// =====================================================================
+
+void Bruker2Dicom::DealWithNiveau1(std::string &level1Directory, std::string &currentOutputDirName) {
+//
+// e.g. : at level 1, in B67d1.Bp1/6
+//
+// acqp  fid  imnd  pdata  pulseprogram  spnam0  spnam1
+
+  
+   //gdcm::Directory dirList;
+   //dirList.Load(level1Directory);  // DON'T get recursively the list of files
+   //gdcm::Directory::FilenamesType fileNames;
+   //fileNames = dirList.GetFilenames();
+   // -----------------------------------------------------
+   // Iterate to ALL the objets(files/directories) found in the input directory
+   // -----------------------------------------------------
+   bool bmethod = false;
+   //gdcm::Directory::FilenamesType::iterator it =  fileNames.begin();
+     boost::filesystem::directory_iterator it(level1Directory), it_end;
+   for(; it != it_end; it++)
+   {
+       if((*it).leaf() == "method")
+       {
+          bmethod = br_method.LoadFile((*it).string());
+          break;
+       }
+   }
+
+   // if method wasn't found or unable to load, try with imnd file
+   if(!bmethod)
+   {
+          for(; it != it_end; it++)
+          {
+                if((*it).leaf() == "imnd")
+                 {
+                     bmethod = br_method.LoadFile((*it).string());
+                     break;
+                }
+            }
+   }
+   if(!bmethod)
+   {
+          std::cout << "Hopeless! neither 'method' nor 'imnd' found in ["
+                         << level1Directory  << "]; we skip it!" << std::endl;
+   }
+  //  if (verbose)
+     //        std::cout << "open => [" << strMethod << "] successfully" << std::endl; 
+      /* a recuperer :
+             ##$PVM_Fov (dimension)  // ou plutot RECO_fov !
+          */
+  /*
+          dans method (pour perfusion  seulement?) :
+          ##$PVM_ObjOrderList=( 8 )
+          0 2 4 6 1 3 5 7
+          ##$PVM_NSPacks=2
+          ##$PVM_SPackArrNSlices=( 2 )
+          7 1  
+  */  
+    br_method.FillMap();
+   
+    try
+    {
+       boost::filesystem::directory_iterator itDir(level1Directory), it_end;
+       for(; itDir != it_end; ++itDir)
+       {
+           if ( boost::filesystem::is_directory(*itDir) && (*itDir).leaf() == "pdata")
+           {
+               std::string output = createDirectory( (*itDir).leaf() , currentOutputDirName);
+                 // will be always "pdata" ...
+               boost::filesystem::directory_iterator itDirInside(*itDir), it_inside_end;
+                for(; itDirInside != it_end; ++it)
+                {
+                    // we take the first and hope that we have only one!
+                    if ( boost::filesystem::is_directory(*itDirInside))
+                    {
+                                 output = createDirectory( (*itDirInside).leaf() , output);
+                                DealWithNiveau2( (*itDirInside).string(), output);
+                    }
+                }
+            }
+         }
+    }
+       catch(BrukerHopelessException &e)
+        {
+           std::cout << "And Exception was thrown in DealWithNiveau2 (" << e.what() << ") " << std::endl;
+        }
+  
+}
+
+// =====================================================================
+
+void Bruker2Dicom::DealWithNiveau2(std::string &level2Directory, std::string &currentOutputDirName) {
+
+// e.g. : at level 2 in B67d1.Bp1/6/pdata
+//
+// acqp  fid  imnd  pdata  pulseprogram  spnam0  spnam1
+//
+    std::string output = currentOutputDirName;
+
+    bool bisa = false;
+    boost::filesystem::directory_iterator it(level2Directory), it_end;
+    for(; it != it_end; ++it)
+    {
+        if((*it).leaf() == "isa")
+        {
+            bisa =  br_isa.LoadFile((*it).string());
+          if (bisa)
+          {
+             br_isa.FillMap();
+             BrukerFieldData b_isa_func_name = br_isa.GetFieldData("ISA_func_name");
+    
+             std::string  str_isa_func_name = b_isa_func_name.GetStringValue()[0];
+             cleanString(str_isa_func_name);
+             output = createDirectory(str_isa_func_name, currentOutputDirName);
+            
+          }
+          break;
+        }
+    }
+         try {
+             DealWithNiveau3(level2Directory, output);
+         }
+         catch (BrukerHopelessException &e)
+         {
+            std::cout << "And Exception was thrown in DealWithNiveau3 (" << e.what() << "); " 
+                      << " We skip [" << level2Directory << "]" << std::endl;
+        
+         }
+         catch (BrukerInitException &e)
+         {
+            std::cout << "And Init Exception was thrown in DealWithNiveau3 (" << e.what() << "); " 
+                      << " We skip [" << level2Directory << "]" << std::endl;
+        
+         }          
+   
+}
+
+//
+// =====================================================================
+//
+
+void Bruker2Dicom::DealWithNiveau3(std::string &level3Directory, std::string &currentOutputDirName){
+
+//
+// e.g. at level 3, in
+
+   // just to be able to go on checking // JP
+    gdcm::Filename file;
+
+   bool res;
+
+
+   gdcm::Directory dirList;
+   dirList.Load(level3Directory); // DON'T get recursively the list of files
+   gdcm::Directory::FilenamesType::iterator it;
+   gdcm::Directory::FilenamesType fileNames = dirList.GetFilenames();
+
+   char original2dseqName       [(unsigned int) PATH_MAX+2];
+   char original2dseqName_XXX   [(unsigned int) PATH_MAX+2];   
+   char currentOutputMhdDirName [(unsigned int) PATH_MAX+2];
+
+   char outputMhdFileName       [(unsigned int) PATH_MAX+2];
+   char output2dseqSliceFileName[(unsigned int) PATH_MAX+6]; // think about extra '.dcm'
+   char output2dseqName         [(unsigned int) PATH_MAX+6];
+   char output2dseqCartoName    [(unsigned int) PATH_MAX+6];
+
+   char copyFile[PATH_MAX + PATH_MAX + 5]; // Should be enough!
+   std::string temp;
+   bool canOpen;
+
+   //-------------- try d3proc;
+     
+   canOpen = br_d3proc.LoadFile(findFile( level3Directory,"d3proc"));
+
+   if (!canOpen)
+   {
+      std::cout << "Hopeless! no 'd3proc' found" << std::endl;
+      throw ( BrukerHopelessException ("Hopeless! no 'd3proc' found"));
+      //exit(0);  /// \TODO throw an exception ! 
+   }
+   else
+   {
+        canOpen = br_d3proc.FillMap();
+        if (!canOpen)
+        {
+            std::cout << "Hopeless! FillMap failed on 'd3proc'" << std::endl;
+            throw ( BrukerHopelessException ("Hopeless! FillMap failed on 'd3proc'"));      
+        }
+   }
+
+   //-------------- end try d3proc;
+
+
+ // -------------------try reco
+
+   
+   std::string str_reco = level3Directory + VALID_FILE_SEPARATOR + "reco";
+   canOpen = br_reco.LoadFile(findFile( level3Directory, "reco"));
+   if (!canOpen)
+      {
+         std::cout << "Hopeless! cannot find 'reco' in [" << str_reco << "]"  << std::endl;     
+         throw ( BrukerHopelessException ("Hopeless! cannot find 'reco'"));  
+         //exit(0);  /// \TODO throw an exception !    
+      }
+ else {
+      if (verbose)
+         std::cout << "[" << str_reco << "] successfully Loaded " << std::endl;
+       canOpen = br_reco.FillMap();
+        if (!canOpen)
+        {
+            std::cout << "Hopeless! FillMap failed on [" << str_reco << "]" << std::endl;
+            throw ( BrukerHopelessException ("Hopeless! FillMap failed on 'reco'"));  
+      
+        } 
+        else {
+            if (verbose)
+                std::cout << "[" << str_reco << "] successfully Mapped" << std::endl;
+        }
+ }
+
+   //std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
+   // br_reco.PrintSelf();
+   // std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
+   // -------------------end try reco
+
+
+   BrukerFieldData bX = br_d3proc.GetFieldData("IM_SIX");
+   int NX = bX.GetIntValue()[0];
+
+   if (verbose)
+      std::cout << "IM_SIX " << NX << std::endl;
+   BrukerFieldData bY=br_d3proc.GetFieldData("IM_SIY"); 
+   int NY = bY.GetIntValue()[0];
+
+   if (verbose)
+         std::cout << "IM_SIY " << NY << std::endl;
+   /// \todo : check if there are actually 3 dimensions or only 2
+
+   BrukerFieldData bZ= br_d3proc.GetFieldData("IM_SIZ");
+   int nbFrames = bZ.GetIntValue()[0]; 
+   if (verbose)
+         std::cout << "IM_SIZ " << nbFrames << std::endl;
+
+        // WARNING DATTYPE is, either in {ip_short, ip_int, ip_char, ...}, or in {1, 2, 3, ...}
+
+   BrukerFieldData bDPT = br_d3proc.GetFieldData("DATTYPE");
+
+   std::string mhdDataPixelType;
+   int pixelSize;
+   getImhDataType(bDPT, mhdDataPixelType, pixelSize);
+
+
+ /*
+
+ // See mail Denis : 
+ // En regle generale il vaut mieux que l'on passe par RECO_* 
+ // pour extraire les parametres de l'image
+ //
+
+   BrukerFieldData fov = br_method.GetFieldData("PVM_Fov");
+   double fovX = fov.GetDoubleValue()[0];
+   double fovY = fov.GetDoubleValue()[1];
+   if (verbose)
+      std::cout << "FOV (ds method) " << fovX << " " << fovY << std::endl;
+
+   BrukerFieldData spatResol = br_method.GetFieldData("PVM_SpatResol");
+   double spatResolX = spatResol.GetDoubleValue()[0];
+   double spatResolY = spatResol.GetDoubleValue()[1];
+   if (verbose)
+      std::cout << "SpatResol (ds method) " << spatResolX << " " << spatResolY << std::endl;
+     
+*/
+
+/* ------  */
+// Better we use 'get' accessors from BrukerImage class, as Denis wrote them
+
+   BrukerFieldData fov = br_reco.GetFieldData("RECO_fov");
+   double fovX = fov.GetDoubleValue()[0];
+   double fovY = fov.GetDoubleValue()[1];
+   if (verbose)
+      std::cout << "FOV (ds reco) " << fovX << " " << fovY << std::endl;
+
+   BrukerFieldData size = br_reco.GetFieldData("RECO_size");
+   double sizeX = size.GetDoubleValue()[0];
+   double sizeY = size.GetDoubleValue()[1];
+
+   if (verbose)
+      std::cout << "SIZE (ds reco) " << sizeX << " " << sizeY << std::endl;
+
+   double spatResolX = fovX / sizeX;
+   double spatResolY = fovY / sizeY;
+
+   if (verbose)
+      std::cout << "spatResol (ds reco : fov/size) " << spatResolX << " " << spatResolY << std::endl;
+
+/* ------  */
+
+   /// \TODO probabely a more sophisticated accessor will be necessary :
+   ///  (cf : non contiguous slices, overlapping, slice thickness, space between slices, etc)
+
+   BrukerFieldData bsliceDistance = br_method.GetFieldData("PVM_SPackArrSliceDistance");
+   double sliceDistance = bsliceDistance.GetDoubleValue()[0];
+
+   if (verbose)
+      std::cout << "SPackArrSliceDistance (ds method) " << sliceDistance << std::endl;   
+
+// ----------------------------------------------------------------------------------------
+
+   if (mhd)
+   {
+      sprintf(currentOutputMhdDirName, "%s%c%s", currentOutputDirName.c_str(),
+                              VALID_FILE_SEPARATOR, "MhdFiles");
+      std::string temp(currentOutputMhdDirName);
+       boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+       sprintf(currentOutputMhdDirName, "%s", temp);
+      std::string strCurrentOutputMhdDirName(currentOutputMhdDirName);
+      res = CreateDirectory( strCurrentOutputMhdDirName );
+      if (!res) {
+         std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
+        throw ( BrukerHopelessException ("Hopeless!FillMap failed on 'reco'"));  
+         //exit (0);
+      } 
+
+      if (verbose)
+         std::cout << "Directory creation [" <<  currentOutputDirName << "]" << std::endl;
+   }  // end if mhd
+
+   if (verbose)
+         std::cout << "nbFrames " << nbFrames << std::endl;
+   if (verbose)
+         std::cout << "nbSlices " << nbSlices << std::endl;
+   int k;
+   int nbInstants = nbFrames/nbSlices;
+   if (verbose)
+         std::cout << "nbInstants (deduced)" << nbInstants << std::endl;    
+   int instantNb;
+   int sliceNb; 
+   FILE *fp;  // for MHD files
+
+   sprintf( original2dseqName, "%s%c%s", level3Directory.c_str(),VALID_FILE_SEPARATOR, "2dseq");
+   temp = level3Directory + VALID_FILE_SEPARATOR + "2dseq" ;
+   boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+   sprintf(original2dseqName, "%s", temp);
+
+/**/   
+  // \TODO : tenir compte du bazar precedent 
+
+    // load 2dseq in memory
+   
+   fp = fopen(temp.c_str(), "rb");
+   if (!fp) 
+   {
+      // try 2dseq_Angio2D ?!?
+       temp = original2dseqName_XXX;
+      sprintf( original2dseqName_XXX, "%s%s", original2dseqName, "_Angio2D");
+      sprintf(original2dseqName_XXX, "%s", temp);
+      fp = fopen(original2dseqName_XXX, "rb");
+      if (!fp)
+      {
+         std::cout << "Cannot open [" << original2dseqName << "] nor [" <<  original2dseqName_XXX << "] for reading" << std::endl;
+         fclose(fp);    
+         throw ( BrukerHopelessException ("Hopeless! Cannot open '2dseq'"));
+         //exit (0);
+      }
+   }
+
+   unsigned char *buffer_2dseq = new unsigned char[NX*NY*pixelSize*nbSlices*nbInstants];   
+   ///\ TODO : find a safer way to be sure to read everything!
+   size_t lgr = fread(buffer_2dseq, 1, NX*NY*pixelSize*nbSlices*nbInstants, fp);
+
+   // This one will be important!
+   // ---------------------------
+   try {
+      imageSet = CreateImageSet ( );
+   }
+   catch (BrukerInitException& e)
+   {
+      if (verbose)
+         std::cout <<  "an Init Exception was thrown in CreateImageSet ( ); " << e.what() 
+                   <<  "catched in DealWithNiveau3" << std::endl;
+      //return;
+      throw (e);
+   }
+
+   serieNumber++;
+   gdcm::UIDGenerator uid;
+   strSerieUID     = uid.Generate();
+  
+   if (nbInstants==1) // creer un seul fichier .mhd  pour toutes les Slices! (images natives)
+   {
+       if (verbose)
+          std::cout << "Single instant : do not split" << std::endl;
+       if (mhd)
+       {
+             sprintf(outputMhdFileName, "%s%cMhdData_All_the_Slices.mhd", currentOutputMhdDirName,
+                                        VALID_FILE_SEPARATOR);
+             temp = currentOutputDirName +                              VALID_FILE_SEPARATOR + "MhdFiles" + VALID_FILE_SEPARATOR +"MhdData_All_the_Slices.mhd";
+             boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+             sprintf(outputMhdFileName,"%s", temp);
+             fp=fopen(temp.c_str(), "w");
+             if (!fp)
+             {
+                std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
+               throw ( BrukerHopelessException ("Hopeless! Cannot open  mhd file for writting"));
+                //exit(0);
+             }
+             else
+             {
+               fprintf(fp, "ObjectType = Image\n");
+               fprintf(fp, "NDims = 3\n" );
+               fprintf(fp, "BinaryData = True \n" );
+               fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
+               fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices );
+               fprintf(fp, "HeaderSize = %d\n", 0);
+               //fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, sliceDistance );
+               fprintf(fp, "ElementSpacing = %lf %lf %lf\n", spatResolX, spatResolY, sliceDistance );
+               fprintf(fp, "Position = 0 0 %d\n", 0 );
+               fprintf(fp, "Offset = 0 0 0\n" );
+               fprintf(fp, "CenterOfRotation = 0 0 0\n" );
+               fprintf(fp, "ElementNumberOfChannels = 1\n" );
+               fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );  
+               fprintf(fp, "ElementDataFile = %s\n", "../2dseq_All_the_Slices" );
+               fclose(fp);     
+             }
+             sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices", 
+                                       currentOutputDirName.c_str(), VALID_FILE_SEPARATOR);
+             temp =  currentOutputDirName +  VALID_FILE_SEPARATOR + "2dseq_All_the_Slices";
+             boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+             sprintf(output2dseqSliceFileName,"%s",temp);
+             fp=fopen(temp.c_str(), "wb");
+             if (!fp)
+             {
+                std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
+               throw ( BrukerHopelessException ("Hopeless! Cannot open 2dseq file for writting"));             
+             }
+             else
+             {
+                fwrite( buffer_2dseq, NX*NY*pixelSize, nbSlices, fp);     
+             }
+             fclose(fp);
+             serieNumber ++;
+             gdcm::UIDGenerator uid;
+            strSerieUID     = uid.Generate();
+             
+       }  // end if mhd
+       if (dicom)
+       {
+             sprintf(output2dseqSliceFileName, "%s%c2dseq_All_the_Slices.dcm", 
+                                      VALID_FILE_SEPARATOR);
+             temp = currentOutputDirName + VALID_FILE_SEPARATOR + "2dseq_All_the_Slices.dcm";
+             boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+             sprintf(output2dseqSliceFileName, "%s", temp);
+
+            /* ----------- Write Dicom Image  ---------------*/
+             MakeDicomImage(buffer_2dseq,
+               NX,
+               NY,
+               nbFrames,
+               pixelSize,
+               //fovX/NY, fovY/NY, sliceDistance,
+              spatResolX, spatResolY, sliceDistance,
+               temp.c_str(),
+               subject_name,
+               day,
+               strStudyUID,
+               strSerieUID,
+               strStudyDescr,
+               strSerieDescr,
+               strStudyTimeDate,
+               0,// index frame number
+               4 //GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
+             );
+       }  // end if dicom
+   }  // end if nbInstants = 1
+
+   else  // more than ONE instant
+   {
+          // Interleaved !
+          // it's (slice1,slide2, ...)t1 ; (slice1,slide2, ...)t2 ; ...
+         unsigned char *pixelsForCurrentSlice = new unsigned char[NX*NY*pixelSize*nbInstants];
+
+         k = 0;
+         for (sliceNb=0; sliceNb<nbSlices; sliceNb++)
+         {
+            if (mhd)
+            {
+               sprintf(outputMhdFileName, "%s%cMhdData_%03d.mhd", currentOutputMhdDirName, 
+                                        VALID_FILE_SEPARATOR, k  );
+               temp = outputMhdFileName;
+               boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+               sprintf(outputMhdFileName, "%s", temp);
+               if (verbose)
+                  std::cout << "--- Output MHD file [" << outputMhdFileName << "]" << std::endl;
+               fp=fopen(outputMhdFileName, "w");
+               if (!fp)
+               {
+                   std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
+                  throw ( BrukerHopelessException ("Hopeless! Cannot open  mhd file for writting"));
+                   //exit(0);
+               }
+               else
+               {
+            /* ----------- Write MHD Image  ---------------*/
+                //if (verbose)
+                //   std::cout << "Open sucessfully[" << outputMhdFileName << "] for writting" << std::endl; 
+                   fprintf(fp, "ObjectType = Image\n");
+                   fprintf(fp, "NDims = 3\n" );  
+                   fprintf(fp, "BinaryData = True \n" );  
+                   fprintf(fp, "BinaryDataByteOrderMSB = False\n" );    
+                   fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbInstants);  
+                   fprintf(fp, "HeaderSize = %d\n", 0); 
+                   //fprintf(fp, "ElementSpacing = %lf %lf %lf\n",fovX/NY, fovY/NY, 1.0 ); // 
+                   fprintf(fp, "ElementSpacing = %lf %lf %lf\n",spatResolX, spatResolY, 1.0 ); //slice distance : no meaning for temporal serie
+                  fprintf(fp, "Position = 0 0 %d\n", sliceNb );  
+                   fprintf(fp, "Offset = 0 0 0\n" );  
+                   fprintf(fp, "CenterOfRotation = 0 0 0\n" );
+                   fprintf(fp, "ElementNumberOfChannels = 1\n" );  
+                   fprintf(fp, "ElementType = %s\n", mhdDataPixelType.c_str() );  
+                   fprintf(fp, "ElementDataFile = ..%c2dseq_Slice_%d\n", VALID_FILE_SEPARATOR, sliceNb ); 
+                   fclose(fp);
+               } // end write MHD
+
+               sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d", 
+                                                 currentOutputDirName.c_str(), VALID_FILE_SEPARATOR,sliceNb);
+               temp = output2dseqSliceFileName;
+               boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+               sprintf(output2dseqSliceFileName, "%s", temp);
+               fp=fopen(output2dseqSliceFileName, "wb");
+               if (!fp)
+               {     
+                   std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
+                  throw ( BrukerHopelessException ("Hopeless! Cannot open 2dseqSliceFile file for writting"));            
+                   //exit (0);
+               }
+               int frameSize = NX*NY*pixelSize;
+               for (instantNb=0; instantNb<nbInstants; instantNb++)
+               {
+// std::cout << "------------SN " << sliceNb << " IN " << instantNb <<  " T " << nbSlices*instantNb + sliceNb << std::endl;
+                    fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
+                            frameSize,
+                            1, fp);
+               }
+               fclose(fp);
+
+// std::cout << "end writting[" << output2dseqSliceFileName << "]" << std::endl;
+            }  // end if mhd
+   
+            if (dicom)
+            {
+               // desperate try !
+             /* 
+               sprintf(output2dseqSliceFileName, "%sdummy_buffer", 
+                                                 currentOutputDirName.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR);
+               fp=fopen(output2dseqSliceFileName, "wb");
+               if (!fp)
+               {     
+                   std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
+                   exit (0);
+               }
+               int frameSize = NX*NY*pixelSize;
+               for (instantNb=0; instantNb<nbInstants; instantNb++)
+               {
+// std::cout << "------------SN " << sliceNb << " IN " << instantNb <<  " T " << nbSlices*instantNb + sliceNb << std::endl;
+                    fwrite( buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize,
+                            frameSize,
+                            1, fp);
+               }
+               fclose(fp);
+
+               fp=fopen(output2dseqSliceFileName, "rb");
+               if (!fp)
+               {     
+                   std::cout << "Cannot open [" << output2dseqSliceFileName << "] for reading" << std::endl;
+                   exit (0);
+               }       
+               fread( pixelsForCurrentSlice,
+                            frameSize*nbInstants,
+                            1, fp);
+               fclose(fp);
+              // end of desperate try !
+              */
+
+               /* ----------- Write Dicom Image  ---------------*/
+
+               int frameSize = NX*NY*pixelSize;
+               for (instantNb=0; instantNb<nbInstants; instantNb++)
+               {
+                  memcpy(pixelsForCurrentSlice + frameSize*instantNb, buffer_2dseq +(nbSlices*instantNb + sliceNb)*frameSize, frameSize);
+               }
+
+               int indOfFirsImageWithinImageSet =  nbSlices*instantNb;
+               sprintf(output2dseqSliceFileName, "%s%c2dseq_Slice_%d.dcm", 
+                                                 currentOutputDirName.c_str(),  VALID_FILE_SEPARATOR, sliceNb);
+               temp= output2dseqSliceFileName;
+               boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+               sprintf(output2dseqSliceFileName, "%s", temp);
+
+               MakeDicomImage(
+                  pixelsForCurrentSlice,
+                  NX,
+                  NY,
+                  nbInstants,
+                  pixelSize,
+                 spatResolX, spatResolY, sliceDistance,
+                  //fovX/NY, fovY/NY, sliceDistance,
+                  output2dseqSliceFileName,
+                  subject_name,
+                  day,
+                  strStudyUID,
+                  strSerieUID,
+                  strStudyDescr,
+                  strSerieDescr,
+                  strStudyTimeDate,
+                  sliceNb*nbInstants,
+                  4 //GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE
+               );
+               if (verbose)
+                  std::cout << "--- Output DCM file [" << output2dseqSliceFileName << "]" << std::endl;      
+
+           } // en if dicom
+
+        k++;
+        }
+        delete [] pixelsForCurrentSlice;  
+     }  // end nbInstants == 1
+   delete [] buffer_2dseq;
+/**/
+
+
+   // -----------------------------------------------------
+   //  deal with MatLab-generated Carto file.
+   // -----------------------------------------------------
+
+   dealWithCarto(fileNames,  NX,  NY,  nbSlices, /*fovX, fovY,*/ spatResolX, spatResolY, sliceDistance,
+                   copyFile, currentOutputDirName, outputMhdFileName, output2dseqCartoName);
+}
+
+// ===========================================================================================
+
+void Bruker2Dicom::dealWithCarto(gdcm::Directory::FilenamesType &fileNames, int NX, int NY, int nbSlices, 
+                                 /*double fovX, double fovY, */
+                                double spatResolX, double spatResolY, double sliceDistance,
+                                 char *copyFile, std::string &currentOutputDirName, 
+                                 char *outputMhdFileName, char *output2dseqCartoName)
+{
+   // -----------------------------------------------------
+   //  deal with MatLab-generated Carto file.
+   // -----------------------------------------------------
+
+   const char *code[] = { "ADC", "adc", "TTP", "ttp", "PEAK", "peak", "" };  // add more carto file name identifiers if necessary; end with ""
+   const char *separator[] =  { "_", ".", "-", "" }; //  add more, if necessary, to ckeck for 2dseq.ADC, 2dseq_ADC, 2dseq-ADC, etc; end with ""
+   int icode;
+   int iseparator; 
+  gdcm::Directory::FilenamesType::iterator it;
+   char file_name_ident[500];
+   FILE *fp;
+
+   // Iterate to ALL the objets(files/directories) found in the input directory    
+   for (it = fileNames.begin();
+        it != fileNames.end();
+      ++it)
+   {
+      if ( boost::filesystem::is_regular(*it) )
+      //if ( ! boost::filesystem::is_directory(*it) )
+      {         
+         if (verbose)
+            std::cout << "--- [" << *it << "] is a file..." << std::endl;
+
+         icode      = 0;
+         while (code[icode][0] != 0)
+         { 
+        iseparator = 0;       
+        while (separator[iseparator][0] != 0)
+         {
+            sprintf(file_name_ident, "2dseq%s%s",separator[iseparator],code[icode]); // e.g  "2dseq_ADC"
+           //if (verbose)
+           //   std::cout << "check name ["<<(*it) << "] for string [" << file_name_ident << "]" << std::endl;
+            std::string::size_type loc = (*it).rfind(file_name_ident); 
+
+            if ( loc != std::string::npos )
+            {
+
+       ///\ TODO : find a safer way to be sure to read everything!
+              unsigned char *buffer_carto = new unsigned char[NX*NY*sizeof(double)*nbSlices];
+              fp = fopen ( (*it).c_str(), "rb");
+              if (!fp){
+                 std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
+                 throw ( BrukerHopelessException ("Level 1 Unable to open 'carto' file "));
+               }
+               fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
+
+                    // ?!?  sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
+               std::cout << "Deal with Carto file :[" <<*it << "], computed length : "
+                         << NX*NY*sizeof(double)*nbSlices << std::endl;
+               gdcm::Filename file ( (*it).c_str());
+               std::string lastFileName = file.GetName();
+               if (mhd)
+               {
+                  // Copy the data file in the new directory
+                  sprintf(copyFile, "cp %s %s%c%s", (*it).c_str() ,
+                            currentOutputDirName.c_str(),  VALID_FILE_SEPARATOR, lastFileName.c_str()); 
+                  std::string temp(copyFile);
+                       boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+                    sprintf(copyFile, "%s", temp);
+      
+                  system(copyFile);
+                  sprintf(outputMhdFileName, "%s%c%s%s",
+                                         currentOutputDirName.c_str(),VALID_FILE_SEPARATOR, lastFileName.c_str(), ".mhd" );
+                  temp = outputMhdFileName;
+                   boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+                  sprintf(outputMhdFileName, "%s", temp);
+      
+                  if (verbose)
+                    std::cout << "--- Output Carto MHD file [" << outputMhdFileName << "]" << std::endl;
+
+                  FILE *fp;
+                  fp=fopen(outputMhdFileName, "w");
+                  if (!fp)
+                  {
+                     std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
+                  }
+                  else
+                  {
+                     fprintf(fp, "ObjectType = Image\n");
+                     fprintf(fp, "NDims = 3\n" );
+                     fprintf(fp, "BinaryData = True \n" );
+                     fprintf(fp, "BinaryDataByteOrderMSB = False\n" );
+                     fprintf(fp, "DimSize = %d %d %d\n", NX, NY, nbSlices);
+                     fprintf(fp, "HeaderSize = %d\n", 0 );
+                     fprintf(fp, "ElementSpacing = %lf %lf %lf\n",spatResolX, spatResolY, sliceDistance );
+                     fprintf(fp, "Position = 0 0 0\n" );
+                     fprintf(fp, "Offset = 0 0 0\n" );
+                     fprintf(fp, "CenterOfRotation = 0 0 0\n" );
+                     fprintf(fp, "ElementNumberOfChannels = 1\n" );
+                     fprintf(fp, "ElementType = %s\n", "MET_DOUBLE" );
+                     fprintf(fp, "ElementDataFile = %s\n", lastFileName.c_str() );
+
+                     fclose(fp);
+                  }
+                  if (verbose)
+                     std::cout << "--- end write Carto MHD file [" << outputMhdFileName << "]" << std::endl;
+               }  // end if mhd
+
+            // ----------- Write Dicom Image  ---------------
+
+               if (dicom)
+               {
+                  sprintf(output2dseqCartoName, "%s%c%s%s",
+                                       currentOutputDirName.c_str(), VALID_FILE_SEPARATOR, lastFileName.c_str(), ".dcm" );
+                  
+                  std::string temp(output2dseqCartoName);
+                  boost::algorithm::replace_all( temp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+                  sprintf(output2dseqCartoName,"%s", temp);
+           
+                  if (verbose)
+                     std::cout << "--- end create name output2dseqCartoName file [" << output2dseqCartoName << "]" << std::endl;
+                     gdcm::UIDGenerator uid;
+                    strSerieUID     = uid.Generate();
+                  
+                    gdcm::Filename file( (*it).c_str() );
+                    std::string strNewSerieDescr(strSerieDescr+ "_" + file.GetName()); 
+                  MakeDicomImage(buffer_carto,
+                     NX,
+                     NY,
+                     nbSlices,
+                     8, // pixelSize
+                     //fovX/NY, fovY/NY, sliceDistance,
+                     spatResolX, spatResolY, sliceDistance,
+                     output2dseqCartoName,
+                     subject_name,
+                     day,
+                     strStudyUID,
+                     strSerieUID,
+                     strStudyDescr,
+                     strNewSerieDescr,
+                     strStudyTimeDate,
+                     0,
+                  3//   GDCM_NAME_SPACE::CREATED_IMAGE
+                  );
+               }  // end if dicom
+
+               delete [] buffer_carto;
+               if (verbose) 
+                  std::cout << "--- End writing Carto DICOM file [" << output2dseqCartoName << "]" << std::endl;
+               break; // don't check for more ident on same file name!
+
+            }  // end deal with _ADC, -adc, etc
+          iseparator ++;
+          }  // end iterate speparators
+          icode++;
+          } // end iterate code
+      } // end boost::filesystem::is_regular(*it)
+   } // end iterate on all objects (files, dir, etc)
+} // end method
+
+// ==========================================================================================================
+
+int Bruker2Dicom::CheckUserDirectory(std::string &userDirName)
+{
+    gdcm::Directory dirList;
+    dirList.Load(userDirName); // DON'T get recursively the list of files
+     
+   gdcm::Directory::FilenamesType fileNames;
+   fileNames = dirList.GetFilenames();
+
+   gdcm::Filename file( fileNames.begin()->c_str());
+   std::string path = file.GetPath();
+
+   std::string subject =  path +
+                         VALID_FILE_SEPARATOR +
+                          "subject";
+   boost::algorithm::replace_all( subject,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+    std::string acqp = path +
+                       VALID_FILE_SEPARATOR +
+                       "acqp";
+    boost::algorithm::replace_all( acqp,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+    if ( boost::filesystem::is_regular(subject) )
+       subjectFound = true; // user passed a 'study
+    else
+       subjectFound = false; // user didnt' pass a 'study 
+
+    if ( boost::filesystem::is_regular(acqp) )
+       acqpFound= true; // user passes a 'serie', not a 'study' 
+    else
+       acqpFound = false; // user passed a 'non study' directory; Hope it's a 'set of studies' directory!
+   
+   int type;    
+   if  (subjectFound )  type = 1; // user passed a 'study
+   else if  (acqpFound) type = 2; // user passed a 'serie' 
+   else                 type = 3; // user passed a 'non study' directory; Hope it's a 'set of studies' directory!
+
+   return type;   
+}
+
+// ==========================================================================================================
+
+bool Bruker2Dicom::CreateDirectory(const std::string &OutputDirName)
+{
+   std::string systemCommand;
+   
+   if (verbose)
+      std::cout << "Check for output directory :[" << OutputDirName << "]."
+                <<std::endl;
+   boost::filesystem::directory_entry ent(OutputDirName);
+   if ( ! boost::filesystem::is_directory(ent) )    // dirout not found
+   {
+      systemCommand = "mkdir " + OutputDirName;        // create it!      
+      if (verbose)
+         std::cout << systemCommand << std::endl;
+      system (systemCommand.c_str());
+  //    if ( ! boost::filesystem::is_directory(OutputDirName) ) // be sure it worked
+  //    {
+  //       if (verbose) 
+  //          std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
+  //       //return 0;
+        //throw ( BrukerHopelessException ("Level 1 output directory creation failure "));
+  //    }
+  //    else
+  //    {
+  //       if (verbose) 
+  //         std::cout << "Directory [" << OutputDirName << "] created." << std::endl;
+  //    }
+   }
+   else
+   {
+       if (verbose)
+            std::cout << "Output Directory [" << OutputDirName << "] already exists; Used as is." << std::endl;
+   }
+   return 1;
+}
+
+// ===========================================================================================
+
+/// \TODO move cleanString to 'crea' ?
+
+void Bruker2Dicom::cleanString(std::string &s)
+{
+   int l = s.size();
+   if (s[l-1] == 0x0A || s[l-1] == 0x0D ) // CR or NL
+   {
+      l--;
+      s = s.substr(0, l);
+   }
+   if (s[l-1] == ' ' ) // blank space
+   {
+      l--;
+      s = s.substr(0, l);
+   }   
+   
+   if (s[0] == '<')      
+      s= s.substr(1,l-2);
+   std::string repChar("_");   
+   ////boost::algorithm::replace_all(
+   //GDCM_NAME_SPACE::Util::ReplaceSpecChar(s, repChar);
+}
+
+// ===========================================================================================
+
+void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPixelType, int &pixelSize)
+{ 
+   if(bDPT.GetDataType() == "string")
+   {         
+         std::string brukerDataPixelType = bDPT.GetStringValue()[0];
+        if (verbose)
+            std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
+         //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
+         
+         if (brukerDataPixelType ==  "ip_short") {
+            mhdDataPixelType = "MET_USHORT";
+            pixelSize = 2;
+         }
+         if (brukerDataPixelType ==  "ip_int") {
+            mhdDataPixelType = "MET_UINT";
+            pixelSize = 4;
+         }
+         if (brukerDataPixelType ==  "ip_char") {
+             mhdDataPixelType = "MET_UCHAR";
+             pixelSize = 1;
+         }
+                  /// \TODO : finish the list
+    /*
+    case 0 : fp << "ElementType = MET_CHAR" << std::endl;
+      break;
+    case 1 : fp << "ElementType = MET_UCHAR" << std::endl;
+      break;
+    case 2 : fp << "ElementType = MET_SHORT" << std::endl;
+      break;
+    case 3 : fp << "ElementType = MET_USHORT" << std::endl;
+      break;
+    case 4 : fp << "ElementType = MET_INT" << std::endl;
+      break;
+    case 5 : fp << "ElementType = MET_UINT" << std::endl;
+      break;
+    case 6 : fp << "ElementType = MET_FLOAT" << std::endl;
+      break;
+    case 7 : fp << "ElementType = MET_DOUBLE" << std::endl;  
+    */
+    }
+    else
+    {
+         int brukerDataPixelType = bDPT.GetIntValue()[0];
+         if (verbose)
+           std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
+         //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
+// Cross your fingers !!!
+
+// pb : found values : 2, 3, 5
+
+         if (brukerDataPixelType ==  2) {
+            mhdDataPixelType = "MET_USHORT";
+            pixelSize = 2;
+         }
+         if (brukerDataPixelType ==  3) {
+            mhdDataPixelType = "MET_USHORT";
+            pixelSize = 2;
+         }    
+         if (brukerDataPixelType ==  1) {
+            mhdDataPixelType = "MET_UCHAR";
+            pixelSize = 1;
+         }     
+    }
+}
+
+// ===========================================================================================
+
+std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
+{
+         std::vector<BrukerImage> imageSet;      
+         br_acqp.SetLoopStructure();
+         std::vector<int> tempVect                      = br_acqp.GetLoopStructure() ;
+         std::map<std::string, BrukerFieldData> map     = br_acqp.GetBrukerHeaderMap();
+        
+         bool result                                    = br_acqp.ObjectVaryingProperties.init(map,tempVect);
+
+         if (result == false)
+        {
+           throw ( BrukerInitException  ("ObjectVaryingProperties.init() failure in Bruker2Dicom::CreateImageSet()") );
+        }
+
+         br_acqp.SetImageLoopStructure();
+         br_acqp.SetBrukerImageList();
+         std::vector<std::vector<int> > brukerImageList = br_acqp.GetBrukerImageList();
+
+         BrukerImage image(br_acqp,br_reco);
+         image.Init(br_acqp,br_reco,1); 
+
+         for(int i=0;i<brukerImageList.size();i++)
+         {
+            image.Init(br_acqp,br_reco,i);    
+            imageSet.push_back(image);
+         }
+
+ // Just for checking
+ /*
+
+         std::vector<std::vector <double> > imageOrientation;
+         std::vector <double> imagePosition; 
+         for(int i=0;i<brukerImageList.size();i++)
+         {
+           // fread(buffer_2dseq, NX*NY*pixelSize*nbSlices*nbInstants, 1, fp);   
+
+           imagePosition = imageSet[i].getTranslationVectorRPS2XYZ();
+           std::cout << "Position " << imagePosition[0] << " " 
+                     << imagePosition[1] << " "  << imagePosition[2] ;
+           imageOrientation =  imageSet[i].getRotationMatrixRPS2XYZ();
+           std::cout << "\t  Orientation " ;
+           for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
+              std::cout << imageOrientation[i1][i2] << " ";CreateImageSet
+
+           //std::cout << "\t  Abs Time " << imageSet[i].getAbsoluteTimePosition();
+           std::cout << "\t  Relat Time " << imageSet[i].getRelativeTimePosition();
+
+           std::cout << "\t [";
+           for (int i3=0; i3<imageSet[i].getLoopStamp().size();i3++)
+              std::cout << " " << imageSet[i].getLoopStamp()[i3];
+           std::cout << "]" << std::endl;       
+         } 
+*/
+   return imageSet;
+}
+
+// ===========================================================================================
+
+void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels, 
+              int X, 
+              int Y,
+              int nbFrames,
+              int pixelSize,
+              double spacingX, double spacingY, double sliceDistance, 
+              std::string dcmImageName,
+              const std::string &patientName,
+              const char *day,
+              std::string &studyUID,
+              std::string &serieUID,
+              std::string &studyDescr,
+              std::string &serieDescr,
+              std::string &strStudyTimeDate,
+              int imgNum,
+             int contentType
+      )
+{  
+   std::ostringstream str;
+
+   gdcm::File file;
+   gdcm::DataSet ds;
+    ds.Clear();
+
+
+    // Set the image size
+    // columns
+    {
+        gdcm::Attribute<0x0028,0x0011, gdcm::VR::US> at;
+        at.SetValue(X);
+        ds.Replace(at.GetAsDataElement());
+    }
+    // rows
+    {
+        gdcm::Attribute<0x0028,0x0010, gdcm::VR::US> at;
+        at.SetValue(Y);
+        ds.Replace(at.GetAsDataElement());
+    }
+
+   //file.SetDataSet( createDataSet(str.str(),0x0028,0x0011,"US"));
+  // Set the image size
+   str.str(""); 
+   str << X;
+   
+ //  file->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
+   str.str("");
+   str << Y;
+ //  file->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
+
+   if (nbFrames != 1)
+   {
+        gdcm::Attribute<0x0028,0x0008, gdcm::VR::IS> at;
+        at.SetValue(nbFrames);
+        ds.Replace(at.GetAsDataElement());
+     // file->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames  
+   }
+
+  // Set the pixel type
+   // Bits allocated
+       {
+            gdcm::Attribute<0x0028,0x0100, gdcm::VR::US> at;
+            at.SetValue(pixelSize*8);
+            ds.Replace(at.GetAsDataElement());
+        }
+       // Bits stored
+       {
+            gdcm::Attribute<0x0028,0x0101, gdcm::VR::US> at;
+            at.SetValue(pixelSize*8);
+            ds.Replace(at.GetAsDataElement());
+        }
+       // High Bit
+        {
+            gdcm::Attribute<0x0028,0x0102, gdcm::VR::US> at;
+            at.SetValue(pixelSize*8 -1);
+            ds.Replace(at.GetAsDataElement());
+        }
+
+        // pixel representation
+        {
+            gdcm::Attribute<0x0028,0x0103, gdcm::VR::US> at;
+            at.SetValue(1);
+            ds.Replace(at.GetAsDataElement());
+        }
+        // sample per pixel
+        {
+            gdcm::Attribute<0x0028,0x0002, gdcm::VR::US> at;
+            at.SetValue(1);
+            ds.Replace(at.GetAsDataElement());
+        }
+
+           // pixel spacing
+        {
+           char temp[256];
+           sprintf(temp,"%d%s%d",spacingX, "\\", spacingY);
+           std::string st;
+           st = temp;
+             gdcm::Attribute<0x0028,0x0030, gdcm::VR::DS> at;
+       //     at.SetValue(st);
+            ds.Replace(at.GetAsDataElement());
+        }
+        //Slice Thickness 
+        {
+            gdcm::Attribute<0x0018,0x00500, gdcm::VR::DS> at;
+            
+            at.SetValue(sliceDistance);
+            ds.Replace(at.GetAsDataElement());
+        }
+        // Series Number
+        {
+            gdcm::Attribute<0x0020,0x0011, gdcm::VR::IS> at;
+            at.SetValue(serieNumber);
+            ds.Replace(at.GetAsDataElement());
+        }
+         //Instance Number
+        {
+            gdcm::Attribute<0x0020,0x00131,gdcm::VR::IS> at;
+            at.SetValue(++instanceNumber);
+            ds.Replace(at.GetAsDataElement());
+            
+        }
+          // [Media Storage SOP Class UID]
+          {
+        /*    
+               str.str("");
+               str <<  "1.2.840.10008.5.1.4.1.1.4";
+                 gdcm::Tag tag(0x0002, 0x0002);
+              tag.Write(str);
+                        at.SetValue(str);
+            ds.Replace(at.GetAsDataElement());*/
+        }
+            // [SOP Class UID]   
+         {
+         /*   gdcm::Attribute<0x0008, 0x0162gdcm::VR::UI> at;
+            at.SetValue("1.2.840.10008.5.1.4.1.1.4");
+            ds.Replace(at.GetAsDataElement());*/
+        }
+         // Patient Name
+         {
+            gdcm::Attribute<0x0010,0x0010, gdcm::VR::PN> at;
+            at.SetValue(patientName);
+            ds.Replace(at.GetAsDataElement());
+        }
+          // Patient's ID
+         {
+            gdcm::Attribute<0x0010,0x0020, gdcm::VR::LO> at;
+            at.SetValue(patientName);
+            ds.Replace(at.GetAsDataElement());
+        }
+          // study UID
+         {
+            gdcm::Attribute< 0x0020, 0x000d, gdcm::VR::UI> at;
+            at.SetValue(studyUID);
+            ds.Replace(at.GetAsDataElement());
+        }
+          // serieUID
+         {
+            gdcm::Attribute<  0x0020, 0x000e, gdcm::VR::UI> at;
+            at.SetValue(serieUID);
+            ds.Replace(at.GetAsDataElement());
+        }
+          {
+              gdcm::Attribute<  0x0008,0x0020, gdcm::VR::DA> at;
+            at.SetValue(strStudyTimeDate.substr(10,11).c_str());
+            ds.Replace(at.GetAsDataElement());
+        }
+           {
+            gdcm::Attribute<  0x0008,0x0030, gdcm::VR::TM> at;
+            at.SetValue(strStudyTimeDate.substr(1,8).c_str());
+            ds.Replace(at.GetAsDataElement());
+        }
+           // Study Description  
+        {
+            gdcm::Attribute<  0x0008,0x1030, gdcm::VR::LO> at;
+            at.SetValue(studyDescr);
+            ds.Replace(at.GetAsDataElement());
+        }
+            // Series Description  
+        {
+            gdcm::Attribute<  0x0008,0x103e, gdcm::VR::LO> at;
+            at.SetValue(serieDescr);
+            ds.Replace(at.GetAsDataElement());
+        }
+         // Modalirty
+        {
+            gdcm::Attribute<  0x0008,0x0060, gdcm::VR::CS> at;
+            at.SetValue("MR");
+            ds.Replace(at.GetAsDataElement());
+        }
+
+
+  //      //8, 16, 32, 64 (for double ?)
+   str.str("");
+   str << pixelSize*8;     
+ //  file->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
+
+ //  file->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
+
+   str.str("");
+   str << pixelSize*8-1;     
+  // file->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
+
+  // Set the pixel representation // 0/1 , 0=unsigned
+ //  file->InsertEntryString("1",0x0028,0x0103, "US"); // Pixel Representation
+   
+  // Set the samples per pixel // 1:Grey level, 3:RGB
+  // file->InsertEntryString("1",0x0028,0x0002, "US"); // Samples per Pixel
+
+//  0028 0030 DS 2 Pixel Spacing
+   str.str("");
+   str << spacingX << "\\" << spacingY;
+ //  file->InsertEntryString(str.str(),0x0028,0x0030, "DS"); // Pixel Spacing     
+   
+ //   0018 0050 DS 1 Slice Thickness 
+   str.str("");    
+   str << sliceDistance;
+ //  file->InsertEntryString(str.str(),0x0018,0x0050, "DS"); 
+   
+//    0020 0011 IS 1 Series Number
+   str.str("");    
+   str << serieNumber;
+//   file->InsertEntryString(str.str(),0x0020,0x0011, "IS");
+      
+//    0020|0013 [IS]  [Instance Number] 
+   instanceNumber++;
+   str.str("");    
+   str << instanceNumber;
+ //  file->InsertEntryString(str.str(),0x0020,0x0013, "IS");
+     
+  // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
+ //  file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
+  // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI");  // [SOP Class UID]
+
+// OK : MR is NOT multiframe, but I want just a quick an dirty solution
+//
+//// 1.2.840.10008.5.1.4.1.1.4         MR Image Storage
+//   file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
+//   file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI");  // [SOP Class UID]     
+//
+//  // if (strlen(patientName) != 0)
+//   file->InsertEntryString(patientName.c_str(),0x0010,0x0010, "PN"); // Patient's Name
+//   file->InsertEntryString(patientName.c_str(),0x0010,0x0020, "LO"); // Patient's ID
+//
+//   file->InsertEntryString(studyUID, 0x0020, 0x000d, "UI");
+//   file->InsertEntryString(serieUID, 0x0020, 0x000e, "UI");
+//   
+////  0008 0020 DA 1 Study Date
+////  0008 0030 TM 1 Study Time
+//
+///// \TODO split into 2 strings!
+//   file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
+//   file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),  0x0008,0x0030, "TM");
+//
+//   file->InsertEntryString(studyDescr, 0x0008,0x1030, "LO");  // Study Description  
+//   file->InsertEntryString(serieDescr, 0x0008,0x103e, "LO");  // Series Description 
+//
+////0008|0060 [CS] [Modality] 
+//   file->InsertEntryString("MR",0x0008,0x0060, "CS");
+//
+// 0020 0037 DS 6 Image Orientation (Patient)
+   char charImageOrientation[256];
+
+/*
+std::cout << "charImageOrientation  " << 
+                              imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0] << " " <<
+                              imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1] << " " <<
+                              imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2] << " " <<
+                              imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0] << " " <<
+                              imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1] << " " <<
+                              imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2] << std::endl ;
+*/      
+
+   {
+             gdcm::Attribute<  0x0020,0x0037, gdcm::VR::DS> at;
+              at.SetValue(  imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0], 0);
+              at.SetValue(  imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1], 1);
+              at.SetValue(  imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2], 2);
+              at.SetValue(   imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][0], 3);
+              at.SetValue(  imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][1], 4);
+              at.SetValue(  imageSet[imgNum].getRotationMatrixRPS2XYZ()[1][2], 4);
+            ds.Replace(at.GetAsDataElement());
+   }
+//   file->InsertEntryString(charImageOrientation,0x0020,0x0037, "DS");
+
+   char charImagePosition[256];   
+   sprintf(charImagePosition,"%f\\%f\\%f", 
+                             imageSet[imgNum].getTranslationVectorRPS2XYZ()[0], 
+                             imageSet[imgNum].getTranslationVectorRPS2XYZ()[1],
+                             imageSet[imgNum].getTranslationVectorRPS2XYZ()[2]);
+  
+   //file->InsertEntryString(charImagePosition,0x0020,0x0032, "DS");  //0020 0032 DS 3 Image Position (Patient) 
+   
+// 0020 0032 DS 3 Image Position (Patient) 
+  {
+             gdcm::Attribute<  0x0020,0x0032,gdcm::VR::DS> at;
+              at.SetValue(  imageSet[imgNum].getTranslationVectorRPS2XYZ()[0], 0);
+              at.SetValue(  imageSet[imgNum].getTranslationVectorRPS2XYZ()[1], 1);
+              at.SetValue(imageSet[imgNum].getTranslationVectorRPS2XYZ()[2], 2);
+              ds.Replace(at.GetAsDataElement());
+  }
+   
+   
+   // Private creator
+   /*
+   
+0029|0010 [LO]   [Private Creator] [CREATIS HEADER ]
+0029|0011 [LO]   [Private Creator] [CREATIS for BRUKER to DICOM]
+0029|1031 [LO]   [] [4.0.7571167 ]
+0029|1032 [UL]   [] [1440000] =0x(15f900)
+
+> $$ Thu Jul 30 17:29:46 2009 CEST (UT+2h)  mwiart
+> $$ /opt/PV4.0/data/mwiart/nmr/dha80.Uw1/4/method
+> ##$Method=DtiEpi
+> ##$PVM_DwNDiffDir=3             % 3 directions
+> ##$PVM_DwNDiffExpEach=2         % 2 valeurs de b par direction
+> ##$PVM_DwAoImages=1             % 1 image pour b=0
+> ##$PVM_DwBvalEach=( 2 )         % Valeurs de b
+> 1500.000000 3000.000000
+>
+> $$ Wed Dec  2 09:56:01 2009 UTC (UT+0h)  mwiart
+> $$ /opt/Pv5.0/data/mwiart/nmr/ECI7.Wx1/4/method
+> ##$Method=DtiEpi
+> ##$PVM_DwNDiffDir=3             % 3 directions
+> ##$PVM_DwNDiffExpEach=2         % 2 valeurs de b par direction
+> ##$PVM_DwAoImages=1             % 1 image pour b=0
+> ##$PVM_DwBvalEach=( 2 )         % Valeurs de b
+> 1500 3000
+>
+> $$ Wed Dec  2 10:14:27 2009 UTC (UT+0h)  mwiart
+> $$ /opt/Pv5.0/data/mwiart/nmr/ECI7.Wx1/5/method
+> ##$Method=DtiStandard
+> ##$PVM_DwNDiffDir=1             % 1 direction
+> ##$PVM_DwNDiffExpEach=2         % 2 valeurs de b
+> ##$PVM_DwAoImages=0             % 0 image pour b=0
+> ##$PVM_DwBvalEach=( 2 )         % Valeurs de b
+> 138 1600
+>
+   */
+    {
+             gdcm::Attribute<  0x0029,0x0010, gdcm::VR::LO> at;
+              at.SetValue(  "CREATIS HEADER");
+              ds.Replace(at.GetAsDataElement());
+    }
+    {
+                gdcm::Attribute<  0x0029,0x0011, gdcm::VR::LO> at;
+              at.SetValue( "CREATIS FOR BRUKER-TO-DICOM");
+              ds.Replace(at.GetAsDataElement());
+    }
+
+  // file->InsertEntryString("CREATIS HEADER", 0x0029,0x0010, "LO");
+   //file->InsertEntryString("CREATIS FOR BRUKER-TO-DICOM", 0x0029,0x0011, "LO");
+   
+   BrukerFieldData brf_method            = br_method.GetFieldData("Method");
+   const std::vector<std::string> method = brf_method.GetStringValue();
+
+  // std::string method = br_method.GetFieldData("Method").GetStringValue();    
+   //{
+   //            gdcm::Attribute<  0x0029,0x0100, gdcm::VR::LO> at;
+   //           at.SetValue(method[0]);
+   //           ds.Replace(at.GetAsDataElement());
+   //}
+   //file->InsertEntryString(method[0], 0x0029,0x0100, "LO");
+   
+   std::cout << " method[" << method[0]  << "]" << std::endl;
+   if (method[0] == "DtiEpi" || method[0] == "DtiStandard")
+   {
+     // const std::vector<int> NDiffDir       = br_method.GetFieldData("PVM_DwNDiffDir").GetIntValue();
+      BrukerFieldData brf_NDiffDir    = br_method.GetFieldData("PVM_DwNDiffDir");
+      const std::vector<int> NDiffDir = brf_NDiffDir.GetIntValue();
+      
+      //const std::vector<int> NDiffExpEach   = br_method.GetFieldData("PVM_DwNDiffExpEach").GetIntValue();
+      BrukerFieldData brf_NDiffExpEach      = br_method.GetFieldData("PVM_DwNDiffExpEach");
+      const std::vector<int> NDiffExpEach   =brf_NDiffExpEach.GetIntValue();
+      
+//      const std::vector<int> AoImages     = br_method.GetFieldData("PVM_DwAoImages").GetIntValue();
+      BrukerFieldData brf_AoImages        = br_method.GetFieldData("PVM_DwAoImages");
+      const std::vector<int> AoImages     = brf_AoImages.GetIntValue();
+      
+      BrukerFieldData brf_DwBvalEach       = br_method.GetFieldData("PVM_DwBvalEach");
+      const std::vector<double> DwBvalEach = brf_DwBvalEach.GetDoubleValue();
+      
+ std::cout << "nb directions : " <<  NDiffDir[0] << " nb valeurs de b par direction : " << NDiffExpEach[0] 
+           << " nb images for b=0 : " << AoImages[0] << std::endl;
+          
+       str.str(""); 
+       str << NDiffDir[0];
+         {
+               gdcm::Attribute<  0x0029,0x0101, gdcm::VR::US> at;
+              at.SetValue( NDiffDir[0]);
+              ds.Replace(at.GetAsDataElement());
+   }
+    //   file->InsertEntryString(str.str(),0x0029,0x0101,"US"); // directions
+       str.str(""); 
+       str << NDiffExpEach[0];
+        {
+               gdcm::Attribute<  0x0029,0x0102, gdcm::VR::US> at;
+              at.SetValue( NDiffExpEach[0]);
+              ds.Replace(at.GetAsDataElement());
+   }
+   //    file->InsertEntryString(str.str(),0x0029,0x0102,"US"); // valeurs de b par direction       
+       str.str(""); 
+       str << AoImages[0];
+               {
+               gdcm::Attribute<  0x0029,0x0103, gdcm::VR::US> at;
+              at.SetValue( AoImages[0]);
+              ds.Replace(at.GetAsDataElement());
+   }
+   //    file->InsertEntryString(str.str(),0x0029,0x0103,"US"); // image pour b=0
+
+          {
+             gdcm::Attribute<  0x0029,0x0104,gdcm::VR::DS> at;
+                        for (unsigned int i=0; i<NDiffExpEach[0]; i++)
+                     at.SetValue( DwBvalEach[i], i);
+              ds.Replace(at.GetAsDataElement());
+               }
+    //  file->InsertEntryString(str.str(),0x0029,0x0104,"DS"); // Valeurs de b          
+   }   
+      file.SetDataSet(ds);
+
+// 0020 0x1041 DS 1 Slice Location 
+//        sprintf(charImagePosition,"%f",float(imgNum));
+//        file->InsertEntryString(charImagePosition,0x0020,0x1041, "DS");   
+/*
+  // Set Rescale Intercept
+        str.str("");
+        str << div;  
+        file->InsertEntryString(str.str(),0x0028,0x1052,"DS");
+
+  // Set Rescale Slope
+        str.str("");
+        str << mini;  
+        file->InsertEntryString(str.str(),0x0028,0x1053,"DS");
+*/
+     // dcmImageName = "c:\\toto.dcm";
+     boost::algorithm::replace_all( dcmImageName,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+   FILE *fil=fopen("c:\\toto", "a");
+    fclose(fil);
+
+   gdcm::ImageWriter writer;
+   writer.SetFileName(dcmImageName.c_str());
+   writer.SetFile(file);
+  gdcm::DataElement pixeldata( gdcm::Tag(0x7fe0,0x0010) );
+  pixeldata.SetByteValue( (char*)tabPixels ,X*Y*nbFrames*pixelSize );
+  gdcm::Image im;
+  im.SetDataElement(pixeldata);
+  writer.SetImage(im);
+
+//   GDCM_NAME_SPACE::FileHelper *fileH;
+//   fileH = GDCM_NAME_SPACE::FileHelper::New(file);
+//   fileH->SetContentType(contentType);   
+//   
+//   // cast is just to avoid warnings (*no* conversion is performed)
+//   //fileH->SetImageData((uint8_t *)img,int(maxX*maxY)*sizeof(uint16_t)); // troubles when maxX, mayY are *actually* float!
+//
+////std::cout << "--------------------------------  X*Y*nbFrames*pixelSize " << X << " " << Y << " " << nbFrames << " " << pixelSize << std::endl; 
+//
+//   fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
+//   fileH->SetWriteModeToRaw(); 
+//   fileH->SetWriteTypeToDcmExplVR();
+//   if( !fileH->Write(dcmImageName)) {
+//      std::cout << "Failed for [" << dcmImageName << "]\n"
+//                << "           File is unwrittable" << std::endl;            
+//      file->Delete();
+//      fileH->Delete();               
+//      throw ( BrukerHopelessException ("Level 1 Unable to write Dicom file "));
+//   }
+//   //if (verbose)
+//   //   file->Print();
+//
+//   file->Delete();
+//   fileH->Delete();  
+}
+
+//////////////////////////////////////////////////////////////////////
+// Generic repertory creation                                                            //
+//////////////////////////////////////////////////////////////////////
+const std::string  Bruker2Dicom::createDirectory(const std::string &i_name, const std::string &i_dir)
+{
+
+ // creation directory : 'nom du patient'
+    std::string tempString(i_dir);
+    tempString = tempString + VALID_FILE_SEPARATOR + i_name;
+    boost::algorithm::replace_all( tempString,       INVALID_FILE_SEPARATOR ,    VALID_FILE_SEPARATOR);
+    if (!CreateDirectory(tempString))
+    {
+       std::cout << "[" << tempString << "] Directory creation failure " << std::endl;
+       throw ( BrukerHopelessException ("Patient directory creation failure "));
+    }
+    return tempString.c_str();
+}
+
+ std::string Bruker2Dicom::findFile(const std::string &i_dir, const  std::string i_name)
+{
+    bool bres = false;
+    std::string file;
+     boost::filesystem::directory_iterator it(i_dir), it_end;
+     for(; it != it_end; ++it)
+     {
+         if((*it).leaf() == i_name)
+         {
+             file = (*it).string();
+             bres = true;
+             break;
+         }
+     }
+
+     if(!bres)
+     {
+         boost::filesystem::path pth (i_dir);
+         boost::filesystem::directory_iterator itless(pth.branch_path()), it_end;
+         for(; itless != it_end; ++itless)
+        {
+            if((*itless).leaf() == i_name)
+           {
+                file = (*itless).string();
+                bres = true;
+                break;
+            }
+        }
+     }
+     return file.c_str();
+}
+
+
+//const gdcm::DataSet Bruker2Dicom::createDataSet(const std::string &i_val,
+//                                                                                            const  uint16_t &i_gr, const uint16_t &i_el,
+//                                                                                            const gdcm::VR &i_vr)
+//
+//{
+//    gdcm::Attribute<i_gr, i_el> at;
+//    at.SetValue(i_val.c_str());
+//
+//
+//    gdcm::DataElement de;
+//    de.Clear();
+//    de.SetVR(i_vr);
+//    de.SetTag( gdcm::Tag(i_gr, i_el) );
+//    
+//    gdcm::DataSet ds;
+//    ds.Clear();
+//    ds.Replace(at.GetAsDataElement());
+//   return ds;
+//}
diff --git a/lib/src1/bruker2dicom2.h b/lib/src1/bruker2dicom2.h
new file mode 100644 (file)
index 0000000..d047865
--- /dev/null
@@ -0,0 +1,161 @@
+#ifndef BRUKER2DICOM2_H
+#define BRUKER2DICOM2_H
+
+#include <gdcmReader.h>
+#include "gdcmDirectory.h"
+#include <vtkGDCMImageReader.h>
+#include <gdcmScanner.h>
+
+#include "gdcmByteSwap.h"
+#include "gdcmSwapCode.h"
+#include "gdcmFilename.h"
+#include "gdcmDataSet.h"
+
+#include "gdcmImageWriter.h"
+#include "gdcmImage.h"
+#include "gdcmWriter.h"
+#include "gdcmReader.h"
+#include "gdcmUIDGenerator.h"
+//
+//#include "gdcmFile.h"
+//#include "gdcmFileHelper.h"
+//#include "gdcmCommon.h"
+//#include "gdcmDebug.h"
+//#include "gdcmUtil.h"
+//#include "gdcmDirList.h"
+//
+//#include "gdcmArgMgr.h"
+#include "brukerSystem.h"
+#include "brukerdataset.h"
+#include "brukerkspaceobject.h"
+#include "brukerimage.h"
+#include <string>
+#include <iostream>
+#include <sstream>
+
+  // file separator
+#if defined(_WIN32)
+#define VALID_FILE_SEPARATOR "\\"
+#define INVALID_FILE_SEPARATOR "/"
+#else
+#define INVALID_FILE_SEPARATOR "\\"
+#define VALID_FILE_SEPARATOR "/"
+#endif
+
+class __declspec( dllexport ) Bruker2Dicom {
+
+public:
+ /*! \brief Constructor
+*/
+  Bruker2Dicom () /* : verbose(0), mhd(0), dicom(0), day(O)*/ {};
+/*! \brief Destructor
+*/
+  ~Bruker2Dicom (){};
+
+  void SetInputDirectory (const std::string &i) { InputDirName   = i;}
+  void SetOutputDirectory(const std::string &o) { OutputDirName  = o;}
+  void SetConvertModeToDicom()                  { dicom = 1; mhd = 0;}
+  void SetConvertModeToMhd()                    { dicom = 0; mhd = 1;}  
+  bool Execute();
+  
+  /* 
+  // For debugging pupose only.
+  //Don't need accessors : Attributes are 'public' 
+  
+  void SetVerbose(int v) { verbose = v;}
+  void SetMhd(int m)     { mhd = m;    }
+  void SetDicom(int d)   { dicom = d;  }
+  */     
+
+private :
+
+void MakeDicomImage(unsigned char *tabPixels, 
+              int X, 
+              int Y,
+              int nbFrames,
+              int pixelSize,
+              double spacingX, double spacingY, double sliceDistance, 
+              std::string dcmImageName,
+              const std::string &patientName,
+              const char *day,
+              std::string &studyUID,
+              std::string &serieUID,
+              std::string &studyDescr,
+              std::string &serieDescr,
+             std::string &strStudyTimeDate,
+              int imgNum, int  imagecontenttype//gdcm2 dont have such things, I think, as ImageContentTYpe 
+      );
+      
+std::vector<BrukerImage> CreateImageSet ( );
+
+void getImhDataType(BrukerFieldData &bDPT, 
+                    std::string &mhdDataPixelType, 
+                   int &pixelSize);
+                   
+void cleanString(std::string &s);
+
+bool CreateDirectory(const std::string &dirNameout);
+
+int CheckUserDirectory(std::string &userDirName);
+void DealWithMultiStudyDirectory(gdcm::Directory::FilenamesType &fileNames,const  std::string &currentOutputDirName);
+void DealWithSingleStudyDirectory (const std::string &dirname,const  std::string &currentOutputDirName) ;
+
+void DealWithNiveau1(std::string &level1Directory, std::string &currentOutputDirName);
+void DealWithNiveau2(std::string &level2Directory, std::string &currentOutputDirName);
+void DealWithNiveau3(std::string &level3Directory, std::string &currentOutputDirName);
+                   
+void dealWithCarto(gdcm::Directory::FilenamesType &fileNames, int NX, int NY, int nbSlices, 
+                   double fovX, double fovY, double sliceDistance,
+                   char *copyFile, std::string &currentOutputDirName, 
+                  char *outputMhdFileName, char *output2dseqCartoName);
+
+const std::string createDirectory(const std::string &i_name,const std::string &i_dir);
+ std::string findFile(const std::string &i_dir,  const std::string i_name);
+public:
+
+// these ones are for debugging only
+// don't bbfy the accessors.
+
+   int verbose;
+   const char *day;
+       
+private :
+   std::string InputDirName;
+   std::string OutputDirName;
+
+   bool subjectFound;
+   bool acqpFound;
+   
+   std::string subject_entry;
+   std::string subject_position;
+   std::string subject_date;
+   std::string subject_study_name;
+   int mhd;
+   int dicom;
+     
+   int nbSlices;
+   BrukerDataSet br_subject;
+   BrukerDataSet br_acqp;
+   BrukerDataSet br_method;
+   BrukerDataSet br_d3proc;
+   BrukerDataSet br_isa;
+   BrukerDataSet br_reco;
+
+   std::vector<BrukerImage> imageSet;
+
+// For DICOM images.
+
+   std::string strStudyUID; 
+   std::string strSerieUID; 
+   std::string strStudyDescr; 
+   std::string strSerieDescr;
+   std::string strStudyTimeDate;
+   std::string strPatientName;
+   std::string subject_name; // cleaned strPatientName
+   int serieNumber;
+   int instanceNumber;      
+};
+
+#endif