Salome HOME
Lease constraints on getHeapMem.
[tools/medcoupling.git] / src / MEDLoader / MEDLoader.cxx
index 60e8773ec517cbc912193479c5e0abef9a2416c5..5af7ca0c0c6661763181909a35f6ac1cb381edcb 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright (C) 2007-2012  CEA/DEN, EDF R&D
+// Copyright (C) 2007-2013  CEA/DEN, EDF R&D
 //
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
@@ -261,11 +261,11 @@ void MEDLoader::MEDConnOfOneElemType::releaseArray()
   delete [] _global;
 }
 
-MEDLoader::MEDFieldDoublePerCellType::MEDFieldDoublePerCellType(INTERP_KERNEL::NormalizedCellType type, double *values, int ncomp, int ntuple,
-                                                                const int *cellIdPerType, const char *locName):_ntuple(ntuple),_ncomp(ncomp),_values(values),_type(type)
+MEDLoader::MEDFieldDoublePerCellType::MEDFieldDoublePerCellType(INTERP_KERNEL::NormalizedCellType type, double *values, int ncomp, int nGeoElt, int nbi,
+                                                                const int *cellIdPerType, const char *locName):_ngeo_elt(nGeoElt),_nbi(nbi),_ncomp(ncomp),_values(values),_type(type)
 {
   if(cellIdPerType)
-    _cell_id_per_type.insert(_cell_id_per_type.end(),cellIdPerType,cellIdPerType+ntuple);
+    _cell_id_per_type.insert(_cell_id_per_type.end(),cellIdPerType,cellIdPerType+nGeoElt);
   if(locName)
     _loc_name=locName;
 }
@@ -304,10 +304,11 @@ std::vector<std::string> MEDLoaderNS::getMeshNamesFid(med_idt fid)
 
 void MEDLoaderNS::fillGaussDataOnField(const char *fileName, const std::list<MEDLoader::MEDFieldDoublePerCellType>& data, MEDCouplingFieldDouble *f)
 {
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   char locName[MED_NAME_SIZE+1];
   int nloc=MEDnLocalization(fid);
   med_geometry_type typeGeo;
+  int offset=0;
   for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=data.begin();iter!=data.end();iter++)
     {
       const std::string& loc=(*iter).getLocName();
@@ -329,9 +330,17 @@ void MEDLoaderNS::fillGaussDataOnField(const char *fileName, const std::list<MED
       int nbPtPerCell=(int)INTERP_KERNEL::CellModel::GetCellModel((*iter).getType()).getNumberOfNodes();
       std::vector<double> refcoo(nbPtPerCell*dim),gscoo(nbOfGaussPt*dim),w(nbOfGaussPt);
       MEDlocalizationRd(fid,(*iter).getLocName().c_str(),MED_FULL_INTERLACE,&refcoo[0],&gscoo[0],&w[0]);
-      f->setGaussLocalizationOnType((*iter).getType(),refcoo,gscoo,w);
+      if((*iter).getCellIdPerType().empty())
+        f->setGaussLocalizationOnType((*iter).getType(),refcoo,gscoo,w);
+      else
+        {
+          MEDCouplingAutoRefCountObjectPtr<DataArrayInt> pfl=DataArrayInt::New();
+          pfl->alloc((*iter).getCellIdPerType().size(),1);
+          pfl->iota(offset);
+          f->setGaussLocalizationOnCells(pfl->begin(),pfl->end(),refcoo,gscoo,w);
+        }
+      offset+=(*iter).getNbOfGeoElt();
     }
-  MEDfileClose(fid);
 }
 
 /// @endcond
@@ -344,9 +353,8 @@ void MEDLoader::CheckFileForRead(const char *fileName) throw(INTERP_KERNEL::Exce
 std::vector<std::string> MEDLoader::GetMeshNames(const char *fileName) throw(INTERP_KERNEL::Exception)
 {
   CheckFileForRead(fileName);
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   std::vector<std::string> ret=MEDLoaderNS::getMeshNamesFid(fid);
-  MEDfileClose(fid);
   return ret;
 }
 
@@ -457,7 +465,7 @@ std::vector<std::string> MEDLoader::GetMeshNamesOnField(const char *fileName, co
   CheckFileForRead(fileName);
   std::vector<std::string> ret;
   //
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nbFields=MEDnField(fid);
   //
   med_field_type typcha;
@@ -478,14 +486,13 @@ std::vector<std::string> MEDLoader::GetMeshNamesOnField(const char *fileName, co
       if(curFieldName==fieldName)
         ret.push_back(meshName);
     }
-  MEDfileClose(fid);
   return ret;
 }
 
 std::vector<std::string> MEDLoader::GetMeshFamiliesNames(const char *fileName, const char *meshName) throw(INTERP_KERNEL::Exception)
 {
   CheckFileForRead(fileName);
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nfam=MEDnFamily(fid,meshName);
   std::vector<std::string> ret(nfam);
   char nomfam[MED_NAME_SIZE+1];
@@ -502,7 +509,6 @@ std::vector<std::string> MEDLoader::GetMeshFamiliesNames(const char *fileName, c
       std::string cur=MEDLoaderBase::buildStringFromFortran(nomfam,sizeof(nomfam));
       ret[i]=cur;
     }
-  MEDfileClose(fid);
   return ret;
 }
 
@@ -510,7 +516,7 @@ std::vector<std::string> MEDLoader::GetMeshFamiliesNames(const char *fileName, c
 std::vector<std::string> MEDLoader::GetMeshFamiliesNamesOnGroup(const char *fileName, const char *meshName, const char *grpName) throw(INTERP_KERNEL::Exception)
 {
   CheckFileForRead(fileName);
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nfam=MEDnFamily(fid,meshName);
   std::vector<std::string> ret;
   char nomfam[MED_NAME_SIZE+1];
@@ -532,14 +538,13 @@ std::vector<std::string> MEDLoader::GetMeshFamiliesNamesOnGroup(const char *file
             ret.push_back(cur);
         }
     }
-  MEDfileClose(fid);
   return ret;
 }
 
 std::vector<std::string> MEDLoader::GetMeshGroupsNamesOnFamily(const char *fileName, const char *meshName, const char *famName) throw(INTERP_KERNEL::Exception)
 {
   CheckFileForRead(fileName);
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nfam=MEDnFamily(fid,meshName);
   std::vector<std::string> ret;
   char nomfam[MED_NAME_SIZE+1];
@@ -563,7 +568,6 @@ std::vector<std::string> MEDLoader::GetMeshGroupsNamesOnFamily(const char *fileN
             ret.push_back(cur2);
           }
     }
-  MEDfileClose(fid);
   if(!found)
     {
       std::ostringstream oss;
@@ -577,7 +581,7 @@ std::vector<std::string> MEDLoader::GetMeshGroupsNamesOnFamily(const char *fileN
 std::vector<std::string> MEDLoader::GetMeshGroupsNames(const char *fileName, const char *meshName) throw(INTERP_KERNEL::Exception)
 {
   CheckFileForRead(fileName);
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nfam=MEDnFamily(fid,meshName);
   std::vector<std::string> ret;
   char nomfam[MED_NAME_SIZE+1];
@@ -598,14 +602,13 @@ std::vector<std::string> MEDLoader::GetMeshGroupsNames(const char *fileName, con
             ret.push_back(cur);
         }
     }
-  MEDfileClose(fid);
   return ret;
 }
 std::vector<ParaMEDMEM::TypeOfField> MEDLoader::GetTypesOfField(const char *fileName, const char *meshName, const char *fieldName) throw(INTERP_KERNEL::Exception)
 {
   CheckFileForRead(fileName);
   std::vector<ParaMEDMEM::TypeOfField> ret;
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nbFields=MEDnField(fid);
   //
   med_field_type typcha;
@@ -668,7 +671,6 @@ std::vector<ParaMEDMEM::TypeOfField> MEDLoader::GetTypesOfField(const char *file
     }
   delete [] maa_ass;
   delete [] nomcha;
-  MEDfileClose(fid);
   return ret;
 }
 
@@ -676,7 +678,7 @@ std::vector<std::string> MEDLoader::GetAllFieldNames(const char *fileName) throw
 {
   CheckFileForRead(fileName);
   std::vector<std::string> ret;
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nbFields=MEDnField(fid);
   med_field_type typcha;
   for(int i=0;i<nbFields;i++)
@@ -692,7 +694,6 @@ std::vector<std::string> MEDLoader::GetAllFieldNames(const char *fileName) throw
       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
       ret.push_back(std::string(nomcha));
     }
-  MEDfileClose(fid);
   return ret;
 }
 
@@ -700,7 +701,7 @@ std::vector<std::string> MEDLoader::GetAllFieldNamesOnMesh(const char *fileName,
 {
   CheckFileForRead(fileName);
   std::vector<std::string> ret;
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nbFields=MEDnField(fid);
   //
   med_field_type typcha;
@@ -724,7 +725,6 @@ std::vector<std::string> MEDLoader::GetAllFieldNamesOnMesh(const char *fileName,
     }
   delete [] maa_ass;
   delete [] nomcha;
-  MEDfileClose(fid);
   return ret;
 }
 
@@ -746,7 +746,7 @@ std::vector<std::string> MEDLoader::GetCellFieldNamesOnMesh(const char *fileName
 {
   CheckFileForRead(fileName);
   std::vector<std::string> ret;
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nbFields=MEDnField(fid);
   //
   med_field_type typcha;
@@ -789,7 +789,6 @@ std::vector<std::string> MEDLoader::GetCellFieldNamesOnMesh(const char *fileName
             }
         }
     }
-  MEDfileClose(fid);
   return ret;
 }
 
@@ -797,7 +796,7 @@ std::vector<std::string> MEDLoader::GetNodeFieldNamesOnMesh(const char *fileName
 {
   CheckFileForRead(fileName);
   std::vector<std::string> ret;
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nbFields=MEDnField(fid);
   char pflname[MED_NAME_SIZE+1]="";
   char locname[MED_NAME_SIZE+1]="";
@@ -831,16 +830,14 @@ std::vector<std::string> MEDLoader::GetNodeFieldNamesOnMesh(const char *fileName
             }
         }
     }
-  MEDfileClose(fid);
   return ret;
 }
 
-std::vector< std::pair< std::pair<int,int>, double> > MEDLoader::GetAllFieldIterations(const char *fileName, const char *meshName, const char *fieldName) throw(INTERP_KERNEL::Exception)
+std::vector< std::pair< std::pair<int,int>, double> > MEDLoader::GetAllFieldIterations(const char *fileName, const char *fieldName) throw(INTERP_KERNEL::Exception)
 {
   CheckFileForRead(fileName);
-  std::string meshNameCpp(meshName);
   std::vector< std::pair< std::pair<int,int>, double > > ret;
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nbFields=MEDnField(fid);
   //
   med_field_type typcha;
@@ -851,6 +848,7 @@ std::vector< std::pair< std::pair<int,int>, double> > MEDLoader::GetAllFieldIter
   INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
   med_bool localmesh;
   //
+  std::ostringstream oss; oss << "MEDLoader::GetAllFieldIterations : No field with name \"" << fieldName<< "\" in file \"" << fileName << "\" ! Possible fields are : ";
   for(int i=0;i<nbFields;i++)
     {
       med_int ncomp=MEDfieldnComponent(fid,i+1);
@@ -866,16 +864,22 @@ std::vector< std::pair< std::pair<int,int>, double> > MEDLoader::GetAllFieldIter
               MEDfieldComputingStepInfo(fid,nomcha,k+1,&numdt,&numo,&dt);
               ret.push_back(std::make_pair(std::make_pair(numdt,numo),dt));
             }
+          return ret;
+        }
+      else
+        {
+          oss << "\"" << curFieldName << "\"";
+          if(i!=nbFields-1) oss << ", ";
         }
     }
-  MEDfileClose(fid);
-  return ret;
+  oss << " !";
+  throw INTERP_KERNEL::Exception(oss.str().c_str());
 }
 
 double MEDLoader::GetTimeAttachedOnFieldIteration(const char *fileName, const char *fieldName, int iteration, int order) throw(INTERP_KERNEL::Exception)
 {
   CheckFileForRead(fileName);
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nbFields=MEDnField(fid);
   //
   med_field_type typcha;
@@ -911,7 +915,6 @@ double MEDLoader::GetTimeAttachedOnFieldIteration(const char *fileName, const ch
             }
         }
     }
-  MEDfileClose(fid);
   if(!found || !found2)
     {
       std::ostringstream oss;
@@ -940,7 +943,7 @@ std::vector< std::pair<int,int> > MEDLoader::GetCellFieldIterations(const char *
   CheckFileForRead(fileName);
   std::string meshNameCpp(meshName);
   std::vector< std::pair<int,int> > ret;
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nbFields=MEDnField(fid);
   //
   med_field_type typcha;
@@ -953,6 +956,8 @@ std::vector< std::pair<int,int> > MEDLoader::GetCellFieldIterations(const char *
   INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
   med_bool localmesh;
   //
+  std::ostringstream oss; oss << "MEDLoader::GetCellFieldIterations : No cell Field field with name \"" << fieldName<< "\" in file \"" << fileName << "\" ! Possible fields are : ";
+  std::set<std::string> s2;
   for(int i=0;i<nbFields;i++)
     {
       med_int ncomp=MEDfieldnComponent(fid,i+1);
@@ -973,16 +978,35 @@ std::vector< std::pair<int,int> > MEDLoader::GetCellFieldIterations(const char *
                   med_int nbOfVal=MEDfieldnValueWithProfile(fid,nomcha,numdt,numo,MED_CELL,typmai[j],1,MED_COMPACT_PFLMODE,
                                                             pflname,&profilesize,locname,&nbi);
                   std::string maa_ass_cpp(maa_ass);
-                  if(meshNameCpp==maa_ass_cpp && nbOfVal>0)
+                  if(nbOfVal>0)
                     {
-                      found=true;
-                      ret.push_back(std::make_pair(numdt,numo));
+                      if(meshNameCpp==maa_ass_cpp)
+                        {
+                          found=true;
+                          ret.push_back(std::make_pair(numdt,numo));
+                        }
+                      else
+                        s2.insert(maa_ass_cpp);
                     }
                 }
             }
         }
+      else
+        {
+          oss << "\"" << curFieldName << "\"";
+          if(i!=nbFields-1) oss << ", ";
+        }
+    }
+  if(ret.empty())
+    {
+      if(!s2.empty())
+        {
+          oss << ". Cell Field \"" << fieldName << "\" exists but lies on meshes with names : \"";
+          std::copy(s2.begin(),s2.end(),std::ostream_iterator<std::string>(oss,"\", \""));
+        }
+      oss << " !";
+      throw INTERP_KERNEL::Exception(oss.str().c_str());
     }
-  MEDfileClose(fid);
   return ret;
 }
 
@@ -991,7 +1015,7 @@ std::vector< std::pair<int,int> > MEDLoader::GetNodeFieldIterations(const char *
   CheckFileForRead(fileName);
   std::string meshNameCpp(meshName);
   std::vector< std::pair<int,int> > ret;
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nbFields=MEDnField(fid);
   //
   med_field_type typcha;
@@ -1004,6 +1028,8 @@ std::vector< std::pair<int,int> > MEDLoader::GetNodeFieldIterations(const char *
   INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
   med_bool localmesh;
   //
+  std::ostringstream oss; oss << "MEDLoader::GetNodeFieldIterations : No node Field field with name \"" << fieldName<< "\" in file \"" << fileName << "\" ! Possible fields are : ";
+  std::set<std::string> s2;
   for(int i=0;i<nbFields;i++)
     {
       med_int ncomp=MEDfieldnComponent(fid,i+1);
@@ -1021,14 +1047,31 @@ std::vector< std::pair<int,int> > MEDLoader::GetNodeFieldIterations(const char *
               med_int nbOfVal=MEDfieldnValueWithProfile(fid,nomcha,numdt,numo,MED_NODE,MED_NONE,1,MED_COMPACT_PFLMODE,
                                                         pflname,&profilesize,locname,&nbi);
                std::string maa_ass_cpp(maa_ass);
-               if(meshNameCpp==maa_ass_cpp && nbOfVal>0)
+               if(nbOfVal>0)
                  {
-                   ret.push_back(std::make_pair(numdt,numo));
+                   if(meshNameCpp==maa_ass_cpp)
+                     { ret.push_back(std::make_pair(numdt,numo)); }
+                   else
+                     s2.insert(maa_ass_cpp);
                  }
             }
         }
+      else
+        {
+          oss << "\"" << curFieldName << "\"";
+          if(i!=nbFields-1) oss << ", ";
+        }
+    }
+  if(ret.empty())
+    {
+      if(!s2.empty())
+        {
+          oss << ". Node Field \"" << fieldName << "\" exists but lies on meshes with names : \"";
+          std::copy(s2.begin(),s2.end(),std::ostream_iterator<std::string>(oss,"\", \""));
+        }
+      oss << " !";
+      throw INTERP_KERNEL::Exception(oss.str().c_str());
     }
-  MEDfileClose(fid);
   return ret;
 }
 
@@ -1106,27 +1149,33 @@ void MEDLoaderNS::readFieldDoubleDataInMedFile(const char *fileName, const char
             {
               if(nbPdt>0)
                 {
-                  int profilesize,nbi;
-                  int nval=MEDfieldnValueWithProfile(fid,fieldName,numdt,numo,tabEnt[typeOfOutField],tabType[typeOfOutField][j],1,MED_COMPACT_PFLMODE,pflname,&profilesize,locname,&nbi);
-                  if(nval>0)
+                  INTERP_KERNEL::AutoPtr<char> pflDummy=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
+                  INTERP_KERNEL::AutoPtr<char> locDummy=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
+                  int nbProfiles=MEDfieldnProfile(fid,fieldName,numdt,numo,tabEnt[typeOfOutField],tabType[typeOfOutField][j],pflDummy,locDummy);
+                  for(int kk=0;kk<nbProfiles;kk++)
                     {
-                      double *valr=new double[ncomp*nval*nbi];
-                      MEDfieldValueWithProfileRd(fid,fieldName,iteration,order,tabEnt[typeOfOutField],tabType[typeOfOutField][j],MED_COMPACT_PFLMODE,
-                                                 pflname,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,(unsigned char*)valr);
-                      std::string tmp(locname);
-                      if((locname[0]!='\0' && (typeOfOutField!=ON_GAUSS_PT))
-                         || (locname[0]=='\0' && typeOfOutField==ON_GAUSS_PT))
+                      int profilesize,nbi;
+                      int nval=MEDfieldnValueWithProfile(fid,fieldName,numdt,numo,tabEnt[typeOfOutField],tabType[typeOfOutField][j],kk+1,MED_COMPACT_PFLMODE,pflname,&profilesize,locname,&nbi);
+                      if(nval>0)
                         {
-                          delete [] valr;
-                          continue;
+                          double *valr=new double[ncomp*nval*nbi];
+                          MEDfieldValueWithProfileRd(fid,fieldName,iteration,order,tabEnt[typeOfOutField],tabType[typeOfOutField][j],MED_COMPACT_PFLMODE,
+                                                     pflname,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,(unsigned char*)valr);
+                          std::string tmp(locname);
+                          if((locname[0]!='\0' && (typeOfOutField!=ON_GAUSS_PT))
+                             || (locname[0]=='\0' && typeOfOutField==ON_GAUSS_PT))
+                            {
+                              delete [] valr;
+                              continue;
+                            }
+                          INTERP_KERNEL::AutoPtr<int> pfl=0;
+                          if(pflname[0]!='\0')
+                            {
+                              pfl=new int[nval];
+                              MEDprofileRd(fid,pflname,pfl);
+                            }
+                          field.push_back(MEDLoader::MEDFieldDoublePerCellType(typmai2[j],valr,ncomp,nval,nbi,pfl,locname));
                         }
-                      INTERP_KERNEL::AutoPtr<int> pfl=0;
-                      if(pflname[0]!='\0')
-                        {
-                          pfl=new int[nval];
-                          MEDprofileRd(fid,pflname,pfl);
-                        }
-                      field.push_back(MEDLoader::MEDFieldDoublePerCellType(typmai2[j],valr,ncomp,nval*nbi,pfl,locname));
                     }
                 }
             }
@@ -1142,7 +1191,7 @@ void MEDLoaderNS::readFieldDoubleDataInMedFile(const char *fileName, const char
 std::vector<int> MEDLoaderNS::getIdsFromFamilies(const char *fileName, const char *meshName, const std::vector<std::string>& fams)
 {
   std::vector<int> ret;
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nfam=MEDnFamily(fid,meshName);
   char nomfam[MED_NAME_SIZE+1];
   med_int numfam;
@@ -1159,14 +1208,13 @@ std::vector<int> MEDLoaderNS::getIdsFromFamilies(const char *fileName, const cha
       if(std::find(fams.begin(),fams.end(),cur)!=fams.end())
         ret.push_back(numfam);
     }
-  MEDfileClose(fid);
   return ret;
 }
 
 std::vector<int> MEDLoaderNS::getIdsFromGroups(const char *fileName, const char *meshName, const std::vector<std::string>& grps)
 {
   std::vector<int> ret;
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   med_int nfam=MEDnFamily(fid,meshName);
   char nomfam[MED_NAME_SIZE+1];
   med_int numfam;
@@ -1190,7 +1238,6 @@ std::vector<int> MEDLoaderNS::getIdsFromGroups(const char *fileName, const char
             }
         }
     }
-  MEDfileClose(fid);
   return ret;
 }
 
@@ -1245,7 +1292,7 @@ void MEDLoaderNS::dispatchElems(int nbOfElemCell, int nbOfElemFace, int& nbOfEle
 int MEDLoaderNS::readUMeshDimFromFile(const char *fileName, const char *meshName, std::vector<int>& possibilities)
 {
   possibilities.clear();
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   int ret;
   std::set<int> poss;
   char nommaa[MED_NAME_SIZE+1];
@@ -1287,7 +1334,6 @@ int MEDLoaderNS::readUMeshDimFromFile(const char *fileName, const char *meshName
           poss.insert(curDim);
         }
     }
-  MEDfileClose(fid);
   if(!poss.empty())
     {
       ret=*poss.rbegin();
@@ -1834,7 +1880,7 @@ MEDCouplingUMesh *MEDLoaderNS::readUMeshFromFileLev1(const char *fileName, const
   if(meshDimRelToMax>0)
     throw INTERP_KERNEL::Exception("meshDimRelToMax must be <=0 !");
   //Extraction data from MED file.
-  med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
   std::string trueMeshName;
   med_int mid=getIdFromMeshName(fid,meshName,trueMeshName);
   DataArrayDouble *coords=0;
@@ -1845,7 +1891,6 @@ MEDCouplingUMesh *MEDLoaderNS::readUMeshFromFileLev1(const char *fileName, const
   meshDimExtract=meshDimExtract+meshDimRelToMax;
   MEDLoaderNS::keepSpecifiedMeshDim<MEDLoader::MEDConnOfOneElemType>(conn,meshDimExtract);
   MEDLoaderNS::keepTypes<MEDLoader::MEDConnOfOneElemType>(conn,typesToKeep);
-  MEDfileClose(fid);
   //Put data in returned data structure.
   MEDCouplingUMesh *ret=MEDCouplingUMesh::New();
   ret->setName(trueMeshName.c_str());
@@ -1884,32 +1929,26 @@ ParaMEDMEM::MEDCouplingFieldDouble *MEDLoaderNS::readFieldDoubleLev2(const char
       throw INTERP_KERNEL::Exception(oss.str().c_str());
     }
   //for profiles
-  ParaMEDMEM::MEDCouplingUMesh *newMesh=0;
+  MEDCouplingAutoRefCountObjectPtr<ParaMEDMEM::MEDCouplingUMesh> newMesh;
   std::string mName(mesh->getName());
-  for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=fieldPerCellType.begin();iter!=fieldPerCellType.end();iter++)
+  if(typeOfOutField==ON_NODES)
     {
-      const std::vector<int>& cellIds=(*iter).getCellIdPerType();
-      if(!cellIds.empty())
+      for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=fieldPerCellType.begin();iter!=fieldPerCellType.end();iter++)
         {
-          std::vector<int> ci(cellIds.size());
-          std::transform(cellIds.begin(),cellIds.end(),ci.begin(),std::bind2nd(std::plus<int>(),-1));
-          ParaMEDMEM::MEDCouplingUMesh *mesh2=0;
-          if(typeOfOutField==ON_CELLS)
+          const std::vector<int>& cellIds=(*iter).getCellIdPerType();
+          if(!cellIds.empty())
             {
-              if(newMesh)
-                mesh2=newMesh->keepSpecifiedCells((*iter).getType(),&ci[0],&ci[0]+ci.size());
-              else
-                mesh2=mesh->keepSpecifiedCells((*iter).getType(),&ci[0],&ci[0]+ci.size());
-            }
-          else if(typeOfOutField==ON_NODES)
-            {
-              DataArrayInt *da=0,*da2=0;
-              if(newMesh)
+              std::vector<int> ci(cellIds.size());
+              std::transform(cellIds.begin(),cellIds.end(),ci.begin(),std::bind2nd(std::plus<int>(),-1));
+              MEDCouplingAutoRefCountObjectPtr<ParaMEDMEM::MEDCouplingUMesh> mesh2;
+              MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da,da2;
+              if((const ParaMEDMEM::MEDCouplingUMesh *)newMesh)
                 {
                   if((int)ci.size()!=newMesh->getNumberOfNodes())
                     {
                       da=newMesh->getCellIdsFullyIncludedInNodeIds(&ci[0],&ci[ci.size()]);
-                      mesh2=dynamic_cast<MEDCouplingUMesh *>(newMesh->buildPartAndReduceNodes(da->getConstPointer(),da->getConstPointer()+da->getNbOfElems(),da2));
+                      DataArrayInt *tmpp=0;
+                      mesh2=dynamic_cast<MEDCouplingUMesh *>(newMesh->buildPartAndReduceNodes(da->begin(),da->end(),tmpp)); da2=tmpp;
                     }
                 }
               else
@@ -1917,7 +1956,8 @@ ParaMEDMEM::MEDCouplingFieldDouble *MEDLoaderNS::readFieldDoubleLev2(const char
                   if((int)ci.size()!=mesh->getNumberOfNodes())
                     {
                       da=mesh->getCellIdsFullyIncludedInNodeIds(&ci[0],&ci[ci.size()]);
-                      mesh2=dynamic_cast<MEDCouplingUMesh *>(mesh->buildPartAndReduceNodes(da->getConstPointer(),da->getConstPointer()+da->getNbOfElems(),da2));
+                      DataArrayInt *tmpp=0;
+                      mesh2=dynamic_cast<MEDCouplingUMesh *>(mesh->buildPartAndReduceNodes(da->begin(),da->end(),tmpp)); da2=tmpp;
                       //
                       int nnodes=mesh2->getNumberOfNodes();
                       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da3=DataArrayInt::New();
@@ -1942,32 +1982,47 @@ ParaMEDMEM::MEDCouplingFieldDouble *MEDLoaderNS::readFieldDoubleLev2(const char
                       mesh2->renumberNodes(da2->getConstPointer(),(int)ci.size());
                     }
                 }
-              if(da)
-                da->decrRef();
-              if(da2)
-                da2->decrRef();
+              newMesh=mesh2;
+            }
+        }
+    }
+  else
+    {
+      newMesh=const_cast<ParaMEDMEM::MEDCouplingUMesh *>(static_cast<const ParaMEDMEM::MEDCouplingUMesh *>(mesh)); mesh->incrRef();
+      std::vector<INTERP_KERNEL::NormalizedCellType> types;
+      for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=fieldPerCellType.begin();iter!=fieldPerCellType.end();iter++)
+        if(std::find(types.begin(),types.end(),(*iter).getType())==types.end())
+          types.push_back((*iter).getType());
+      for(std::vector<INTERP_KERNEL::NormalizedCellType>::const_iterator it=types.begin();it!=types.end();it++)
+        {
+          std::vector<int> cids;
+          for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=fieldPerCellType.begin();iter!=fieldPerCellType.end();iter++)
+            {
+              if((*iter).getType()==*it)
+                {
+                  const std::vector<int>& cellIds=(*iter).getCellIdPerType();
+                  if(!cellIds.empty())
+                    std::transform(cellIds.begin(),cellIds.end(),std::back_insert_iterator< std::vector<int> >(cids),std::bind2nd(std::plus<int>(),-1));
+                }
             }
-          if(newMesh)
-            newMesh->decrRef();
-          newMesh=mesh2;
+          if(!cids.empty())
+            newMesh=newMesh->keepSpecifiedCells(*it,&cids[0],&cids[0]+cids.size());
         }
     }
   //
   ParaMEDMEM::MEDCouplingFieldDouble *ret=ParaMEDMEM::MEDCouplingFieldDouble::New(typeOfOutField,ONE_TIME);
   ret->setName(fieldName);
   ret->setTime(time,iteration,order);
-  if(newMesh)
+  ParaMEDMEM::DataArrayDouble *arr=buildArrayFromRawData(fieldPerCellType,infos);
+  ret->setArray(arr);
+  arr->decrRef();
+  if((const ParaMEDMEM::MEDCouplingUMesh *)newMesh)
     {
       newMesh->setName(mName.c_str());//retrieving mesh name to avoid renaming due to mesh restriction in case of profile.
       ret->setMesh(newMesh);
-      newMesh->decrRef();
     }
   else
     ret->setMesh(mesh);
-  ParaMEDMEM::DataArrayDouble *arr=buildArrayFromRawData(fieldPerCellType,infos);
-  ret->setArray(arr);
-  arr->decrRef();
-  //
   if(typeOfOutField==ON_GAUSS_PT)
     fillGaussDataOnField(fileName,fieldPerCellType,ret);
   if(cellRenum)
@@ -2195,13 +2250,10 @@ ParaMEDMEM::MEDCouplingFieldDouble *MEDLoader::ReadFieldGaussNE(const char *file
  */
 void MEDLoaderNS::writeUMeshesDirectly(const char *fileName, const std::vector<const ParaMEDMEM::MEDCouplingUMesh *>& mesh, const std::vector<const DataArrayInt *>& families, bool forceFromScratch, bool &isRenumbering)
 {
-  med_idt fid=MEDfileOpen(fileName,forceFromScratch?MED_ACC_CREAT:MED_ACC_RDWR);
+  MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,forceFromScratch?MED_ACC_CREAT:MED_ACC_RDWR);
   std::string meshName(mesh[0]->getName());
   if(meshName=="")
-    {
-      MEDfileClose(fid);
-      throw INTERP_KERNEL::Exception("MEDCouplingMesh must have a not null name !");
-    }
+    throw INTERP_KERNEL::Exception("MEDCouplingMesh must have a not null name !");
   isRenumbering=false;
   bool isFamilies=true;
   std::vector<const DataArrayInt *> conn;
@@ -2274,7 +2326,6 @@ void MEDLoaderNS::writeUMeshesDirectly(const char *fileName, const std::vector<c
   MEDfamilyCr(fid,maa,familyName,0,0,0);
   
   MEDmeshNodeCoordinateWr(fid,maa,-1,-1,0.,MED_FULL_INTERLACE,mesh[0]->getNumberOfNodes(),arr->getConstPointer());
-  MEDfileClose(fid);
 }
 
 /*!
@@ -2316,7 +2367,7 @@ void MEDLoaderNS::writeUMeshesPartitionDirectly(const char *fileName, const char
             gidsOfFamilies[fid].push_back(gid);
     }
   fid=0;
-  med_idt fid2=MEDfileOpen(fileName,MED_ACC_RDWR);
+  MEDFileUtilities::AutoFid fid2=MEDfileOpen(fileName,MED_ACC_RDWR);
   for(std::set<int>::const_iterator it=familyIds.begin();it!=familyIds.end();it++,fid++)
     {
       int ngro=gidsOfFamilies[fid].size();
@@ -2328,7 +2379,6 @@ void MEDLoaderNS::writeUMeshesPartitionDirectly(const char *fileName, const char
       MEDLoaderBase::safeStrCpy(oss.str().c_str(),MED_NAME_SIZE,famName,MEDLoader::_TOO_LONG_STR);
       MEDfamilyCr(fid2,maa,famName,*it,ngro,groName);
     }
-  MEDfileClose(fid2);
 }
 
 /*!
@@ -2341,7 +2391,7 @@ void MEDLoaderNS::appendNodeProfileField(const char *fileName, const ParaMEDMEM:
   med_float dt;
   INTERP_KERNEL::AutoPtr<char> nommaa=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
   MEDLoaderBase::safeStrCpy(f->getMesh()->getName(),MED_NAME_SIZE,nommaa,MEDLoader::_TOO_LONG_STR);
-  med_idt fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
+  MEDFileUtilities::AutoFid fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
   int nbOfNodes=f->getMesh()->getNumberOfNodes();
   const double *pt=f->getArray()->getConstPointer();
   INTERP_KERNEL::AutoPtr<int> profile=new int[nbOfNodes];
@@ -2351,7 +2401,6 @@ void MEDLoaderNS::appendNodeProfileField(const char *fileName, const ParaMEDMEM:
   std::transform(thisMeshNodeIds,thisMeshNodeIds+nbOfNodes,(int *)profile,std::bind2nd(std::plus<int>(),1));
   MEDprofileWr(fid,profileName,nbOfNodes,profile);
   MEDfieldValueWithProfileWr(fid,f->getName(),numdt,numo,dt,MED_NODE,MED_NONE,MED_COMPACT_PFLMODE,profileName,MED_NO_LOCALIZATION,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,nbOfNodes,(const unsigned char*)pt);
-  MEDfileClose(fid);
 }
 
 /*!
@@ -2363,7 +2412,7 @@ void MEDLoaderNS::appendCellProfileField(const char *fileName, const ParaMEDMEM:
   med_int numdt,numo;
   med_float dt;
   int nbComp=f->getNumberOfComponents();
-  med_idt fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
+  MEDFileUtilities::AutoFid fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
   std::list<MEDLoader::MEDFieldDoublePerCellType> split;
   prepareCellFieldDoubleForWriting(f,thisMeshCellIdsPerType,split);
   const double *pt=f->getArray()->getConstPointer();
@@ -2376,15 +2425,13 @@ void MEDLoaderNS::appendCellProfileField(const char *fileName, const ParaMEDMEM:
       std::ostringstream oss; oss << "Pfl" << f->getName() << "_" << number++;
       MEDLoaderBase::safeStrCpy(oss.str().c_str(),MED_NAME_SIZE,profileName,MEDLoader::_TOO_LONG_STR);
       const std::vector<int>& ids=(*iter).getCellIdPerType();
-      int *profile=new int [ids.size()];
-      std::transform(ids.begin(),ids.end(),profile,std::bind2nd(std::plus<int>(),1));
+      INTERP_KERNEL::AutoPtr<int> profile=new int [ids.size()];
+      std::transform(ids.begin(),ids.end(),(int *)profile,std::bind2nd(std::plus<int>(),1));
       MEDprofileWr(fid,profileName,ids.size(),profile);
-      delete [] profile;
       MEDfieldValueWithProfileWr(fid,f->getName(),numdt,numo,dt,MED_CELL,typmai3[(int)(*iter).getType()],MED_COMPACT_PFLMODE,profileName,
                                  MED_NO_LOCALIZATION,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,(*iter).getNbOfTuple(),(const unsigned char*)pt);
       pt+=(*iter).getNbOfTuple()*nbComp;
     }
-  MEDfileClose(fid);
 }
 
 void MEDLoaderNS::appendNodeElementProfileField(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, const int *thisMeshCellIdsPerType)
@@ -2392,7 +2439,7 @@ void MEDLoaderNS::appendNodeElementProfileField(const char *fileName, const Para
   med_int numdt,numo;
   med_float dt;
   int nbComp=f->getNumberOfComponents();
-  med_idt fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
+  MEDFileUtilities::AutoFid fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
   std::list<MEDLoader::MEDFieldDoublePerCellType> split;
   prepareCellFieldDoubleForWriting(f,thisMeshCellIdsPerType,split);
   const double *pt=f->getArray()->getConstPointer();
@@ -2405,10 +2452,9 @@ void MEDLoaderNS::appendNodeElementProfileField(const char *fileName, const Para
       std::ostringstream oss; oss << "Pfl" << f->getName() << "_" << number++;
       MEDLoaderBase::safeStrCpy(oss.str().c_str(),MED_NAME_SIZE,profileName,MEDLoader::_TOO_LONG_STR);
       const std::vector<int>& ids=(*iter).getCellIdPerType();
-      int *profile=new int [ids.size()];
-      std::transform(ids.begin(),ids.end(),profile,std::bind2nd(std::plus<int>(),1));
+      INTERP_KERNEL::AutoPtr<int> profile=new int [ids.size()];
+      std::transform(ids.begin(),ids.end(),(int *)profile,std::bind2nd(std::plus<int>(),1));
       MEDprofileWr(fid,profileName,ids.size(),profile);
-      delete [] profile;
       int nbPtPerCell=(int)INTERP_KERNEL::CellModel::GetCellModel((*iter).getType()).getNumberOfNodes();
       int nbOfEntity=f->getMesh()->getNumberOfCellsWithType((*iter).getType());
       int nbOfValues=nbPtPerCell*nbOfEntity;
@@ -2418,7 +2464,6 @@ void MEDLoaderNS::appendNodeElementProfileField(const char *fileName, const Para
                                  nbOfEntity,(const unsigned char*)pt);
       pt+=nbOfValues*nbComp;
     }
-  MEDfileClose(fid);
 }
 
 /*!
@@ -2483,7 +2528,7 @@ void MEDLoaderNS::appendFieldDirectly(const char *fileName, const ParaMEDMEM::ME
     }
   //end renumbering
   int nbComp=f->getNumberOfComponents();
-  med_idt fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
+  MEDFileUtilities::AutoFid fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
   const double *pt=f->getArray()->getConstPointer();
   INTERP_KERNEL::AutoPtr<char> nommaa=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
   MEDLoaderBase::safeStrCpy(f->getMesh()->getName(),MED_NAME_SIZE,nommaa,MEDLoader::_TOO_LONG_STR);
@@ -2510,25 +2555,75 @@ void MEDLoaderNS::appendFieldDirectly(const char *fileName, const ParaMEDMEM::ME
       }
     case ParaMEDMEM::ON_GAUSS_PT:
       {
+        INTERP_KERNEL::AutoPtr<char> profileName=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
         std::list<MEDLoader::MEDFieldDoublePerCellType> split;
         prepareCellFieldDoubleForWriting(f,0,split);
-        int idGp=0;
+        int idGp=0,offset=0,offset2=0;
+        const double *pt2=0;
+        INTERP_KERNEL::NormalizedCellType prevType=INTERP_KERNEL::NORM_ERROR;
         for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=split.begin();iter!=split.end();iter++)
           {
+            if((*iter).getType()!=prevType)
+              {
+                offset=offset2;
+                prevType=(*iter).getType();
+              }
             INTERP_KERNEL::AutoPtr<char> nomGauss=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
             std::ostringstream oss; oss << "GP_" << f->getName() << idGp++;
             MEDLoaderBase::safeStrCpy(oss.str().c_str(),MED_NAME_SIZE,nomGauss,MEDLoader::_TOO_LONG_STR);
-            int id=f->getGaussLocalizationIdOfOneType((*iter).getType());
+            std::ostringstream ossPfl;
+            int id=-1,nbOfEntity=-1;
+            MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> arrTmp;
+            if((*iter).getCellIdPerType().empty())
+              {
+                id=f->getGaussLocalizationIdOfOneType((*iter).getType());
+                nbOfEntity=f->getMesh()->getNumberOfCellsWithType((*iter).getType());
+              }
+            else
+              {
+                id=f->getGaussLocalizationIdOfOneCell((*iter).getCellIdPerType()[0]+offset);
+                nbOfEntity=(int)(*iter).getCellIdPerType().size();
+                ossPfl << "Pfl" << f->getName() << "_" << id;
+                MEDLoaderBase::safeStrCpy(ossPfl.str().c_str(),MED_NAME_SIZE,profileName,MEDLoader::_TOO_LONG_STR);
+                INTERP_KERNEL::AutoPtr<int> profile=new int[(*iter).getCellIdPerType().size()];
+                std::transform((*iter).getCellIdPerType().begin(),(*iter).getCellIdPerType().end(),(int *)profile,std::bind2nd(std::plus<int>(),1));
+                MEDprofileWr(fid,profileName,(*iter).getCellIdPerType().size(),profile);
+                //
+                MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da3=DataArrayInt::New();
+                da3->useArray(const_cast<int *>(&((*iter).getCellIdPerType()[0])),false,CPP_DEALLOC,(int)(*iter).getCellIdPerType().size(),1);
+                MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da4=da3->deepCpy();
+                da4->applyLin(1,offset);
+                //
+                const MEDCouplingFieldDiscretizationGauss *disc2=static_cast<const MEDCouplingFieldDiscretizationGauss *>(f->getDiscretization());
+                MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arr=disc2->getOffsetArr(f->getMesh());
+                MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp=DataArrayInt::New();
+                int trueNval=0;
+                for(const int *pt3=da4->begin();pt3!=da4->end();pt3++)
+                  trueNval+=arr->getIJ(*pt3+1,0)-arr->getIJ(*pt3,0);
+                tmp->alloc(trueNval,1);
+                int *tmpPtr=tmp->getPointer();
+                for(const int *pt3=da4->begin();pt3!=da4->end();pt3++)
+                  for(int j=arr->getIJ(*pt3,0);j<arr->getIJ(*pt3+1,0);j++)
+                    *tmpPtr++=j;
+                arrTmp=f->getArray()->selectByTupleId(tmp->begin(),tmp->end());
+                pt2=arrTmp->getConstPointer();
+              }
             const MEDCouplingGaussLocalization& gl=f->getGaussLocalization(id);
             MEDlocalizationWr(fid,nomGauss,typmai3[(int)(*iter).getType()],mesh->getMeshDimension(),&gl.getRefCoords()[0],MED_FULL_INTERLACE,
                               gl.getNumberOfGaussPt(),&gl.getGaussCoords()[0],&gl.getWeights()[0],MED_NO_INTERPOLATION, MED_NO_MESH_SUPPORT);
-            int nbOfEntity=f->getMesh()->getNumberOfCellsWithType((*iter).getType());
             int nbOfValues=gl.getNumberOfGaussPt()*nbOfEntity;
             INTERP_KERNEL::AutoPtr<char> fieldname=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
             MEDLoaderBase::safeStrCpy(f->getName(),MED_NAME_SIZE,fieldname,MEDLoader::_TOO_LONG_STR);
-            MEDfieldValueWithProfileWr(fid,fieldname,numdt,numo,dt,MED_CELL,typmai3[(int)(*iter).getType()],MED_COMPACT_PFLMODE,
-                                       MED_ALLENTITIES_PROFILE,nomGauss,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,nbOfEntity,(const unsigned char*)pt);
+            if((*iter).getCellIdPerType().empty())
+              {
+                MEDfieldValueWithProfileWr(fid,fieldname,numdt,numo,dt,MED_CELL,typmai3[(int)(*iter).getType()],MED_COMPACT_PFLMODE,
+                                           MED_ALLENTITIES_PROFILE,nomGauss,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,nbOfEntity,(const unsigned char*)pt);
+              }
+            else
+              MEDfieldValueWithProfileWr(fid,fieldname,numdt,numo,dt,MED_CELL,typmai3[(int)(*iter).getType()],MED_COMPACT_PFLMODE,
+                                         profileName,nomGauss,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,nbOfEntity,(const unsigned char*)pt2);
             pt+=nbOfValues*nbComp;
+            offset2+=(*iter).getNbOfGeoElt();
           }
         break;
       }
@@ -2550,7 +2645,6 @@ void MEDLoaderNS::appendFieldDirectly(const char *fileName, const ParaMEDMEM::ME
     default:
       throw INTERP_KERNEL::Exception("Not managed this type of FIELD !");
     }
-  MEDfileClose(fid);
   if(renum)
     f->decrRef();
 }
@@ -2577,12 +2671,56 @@ void MEDLoaderNS::prepareCellFieldDoubleForWriting(const ParaMEDMEM::MEDCoupling
     {
       curType=(INTERP_KERNEL::NormalizedCellType)conn[*pt];
       const int *pt2=std::find_if(pt+1,connI+nbOfCells,ConnReaderML(conn,(int)curType));
-      if(!cellIdsPerType)
-        split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,pt2-pt,0,0));
+      int szOfChunk=std::distance(pt,pt2);
+      if(f->getTypeOfField()!=ON_GAUSS_PT)
+        {
+          if(!cellIdsPerType)
+            split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,szOfChunk,1,0,0));
+          else
+            {
+              split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,szOfChunk,1,wCellIdsPT,0));
+              wCellIdsPT+=szOfChunk;
+            }
+        }
       else
         {
-          split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,pt2-pt,wCellIdsPT,0));
-          wCellIdsPT+=std::distance(pt,pt2);
+          const MEDCouplingFieldDiscretizationGauss *disc=static_cast<const MEDCouplingFieldDiscretizationGauss *>(f->getDiscretization());
+          const DataArrayInt *arr=disc->getArrayOfDiscIds();
+          MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da,daTmp1;
+          if(!cellIdsPerType)
+            da=arr->selectByTupleId2(std::distance(connI,pt),std::distance(connI,pt2),1);
+          else
+            {
+              daTmp1=DataArrayInt::New();
+              daTmp1->useArray(const_cast<int *>(cellIdsPerType),false,CPP_DEALLOC,szOfChunk,1);
+              MEDCouplingAutoRefCountObjectPtr<DataArrayInt> daTmp2=daTmp1->deepCpy();
+              daTmp2->applyLin(1,std::distance(connI,pt));
+              da=arr->selectByTupleId(daTmp2->begin(),daTmp2->end());
+            }
+          std::vector<int> differentIds;
+          std::vector<DataArrayInt *> parts=da->partitionByDifferentValues(differentIds);
+          std::vector< MEDCouplingAutoRefCountObjectPtr<DataArrayInt> > partsAuto(parts.size());
+          int jj=0;
+          for(std::vector<DataArrayInt *>::const_iterator it=parts.begin();it!=parts.end();it++,jj++)
+            partsAuto[jj]=parts[jj];
+          jj=0;
+          for(std::vector<DataArrayInt *>::const_iterator it=parts.begin();it!=parts.end();it++,jj++)
+            {
+              if(!cellIdsPerType)
+                {
+                  if(parts[jj]->getNumberOfTuples()==szOfChunk && parts[jj]->isIdentity())
+                    split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,szOfChunk,1,0,0));
+                  else
+                    split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,parts[jj]->getNumberOfTuples(),1,parts[jj]->getConstPointer(),0));
+                }
+              else
+                {
+                  MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp=daTmp1->selectByTupleId(parts[jj]->begin(),parts[jj]->end());
+                  split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,tmp->getNumberOfTuples(),1,tmp->getConstPointer(),0));
+                }
+            }
+          if(!cellIdsPerType)
+            wCellIdsPT+=szOfChunk;
         }
       pt=pt2;
     }
@@ -2637,7 +2775,7 @@ void MEDLoaderNS::writeFieldTryingToFitExistingMesh(const char *fileName, const
       throw INTERP_KERNEL::Exception(oss.str().c_str());
     }
   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m=MEDLoader::ReadUMeshFromFile(fileName,f->getMesh()->getName(),f2);
-  MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m2=MEDCouplingUMesh::MergeUMeshes(m,(MEDCouplingUMesh *)f->getMesh());
+  MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m2=MEDCouplingUMesh::MergeUMeshes(m,static_cast<const MEDCouplingUMesh *>(f->getMesh()));
   bool areNodesMerged;
   int newNbOfNodes;
   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da=m2->mergeNodes(MEDLoader::_EPS_FOR_NODE_COMP,areNodesMerged,newNbOfNodes);