Salome HOME
Merge from V6_main 01/04/2013
[modules/med.git] / src / MEDLoader / MEDLoader.cxx
1 // Copyright (C) 2007-2013  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 // Author : Anthony Geay (CEA/DEN)
20
21 #include "MEDLoader.hxx"
22 #include "MEDLoaderBase.hxx"
23 #include "MEDFileUtilities.hxx"
24 #include "CellModel.hxx"
25 #include "MEDCouplingUMesh.hxx"
26 #include "MEDCouplingMemArray.hxx"
27 #include "MEDCouplingFieldDouble.hxx"
28 #include "MEDCouplingGaussLocalization.hxx"
29 #include "MEDCouplingAutoRefCountObjectPtr.hxx"
30
31 #include "InterpKernelAutoPtr.hxx"
32
33 #include "med.h"
34
35 #include <string>
36 #include <limits>
37 #include <cstring>
38 #include <sstream>
39 #include <fstream>
40 #include <numeric>
41 #include <iterator>
42 #include <algorithm>
43
44 med_geometry_type typmai[MED_N_CELL_FIXED_GEO] = { MED_POINT1,
45                                                    MED_SEG2,
46                                                    MED_SEG3,
47                                                    MED_SEG4,
48                                                    MED_TRIA3,
49                                                    MED_QUAD4,
50                                                    MED_TRIA6,
51                                                    MED_TRIA7,
52                                                    MED_QUAD8,
53                                                    MED_QUAD9,
54                                                    MED_TETRA4,
55                                                    MED_PYRA5,
56                                                    MED_PENTA6,
57                                                    MED_HEXA8,
58                                                    MED_OCTA12,
59                                                    MED_TETRA10,
60                                                    MED_PYRA13,
61                                                    MED_PENTA15,
62                                                    MED_HEXA20,
63                                                    MED_HEXA27,
64                                                    MED_POLYGON,
65                                                    MED_POLYHEDRON };
66
67 med_geometry_type typmainoeud[1] = { MED_NONE };
68
69 INTERP_KERNEL::NormalizedCellType typmai2[MED_N_CELL_FIXED_GEO] = { INTERP_KERNEL::NORM_POINT1,
70                                                                     INTERP_KERNEL::NORM_SEG2,
71                                                                     INTERP_KERNEL::NORM_SEG3,
72                                                                     INTERP_KERNEL::NORM_SEG4,
73                                                                     INTERP_KERNEL::NORM_TRI3,
74                                                                     INTERP_KERNEL::NORM_QUAD4,
75                                                                     INTERP_KERNEL::NORM_TRI6,
76                                                                     INTERP_KERNEL::NORM_TRI7,
77                                                                     INTERP_KERNEL::NORM_QUAD8,
78                                                                     INTERP_KERNEL::NORM_QUAD9,
79                                                                     INTERP_KERNEL::NORM_TETRA4,
80                                                                     INTERP_KERNEL::NORM_PYRA5,
81                                                                     INTERP_KERNEL::NORM_PENTA6,
82                                                                     INTERP_KERNEL::NORM_HEXA8,
83                                                                     INTERP_KERNEL::NORM_HEXGP12,
84                                                                     INTERP_KERNEL::NORM_TETRA10,
85                                                                     INTERP_KERNEL::NORM_PYRA13,
86                                                                     INTERP_KERNEL::NORM_PENTA15,
87                                                                     INTERP_KERNEL::NORM_HEXA20,
88                                                                     INTERP_KERNEL::NORM_HEXA27,
89                                                                     INTERP_KERNEL::NORM_POLYGON,
90                                                                     INTERP_KERNEL::NORM_POLYHED };
91
92 med_geometry_type typmai3[34] = { MED_POINT1,//0
93                                   MED_SEG2,//1
94                                   MED_SEG3,//2
95                                   MED_TRIA3,//3
96                                   MED_QUAD4,//4
97                                   MED_POLYGON,//5
98                                   MED_TRIA6,//6
99                                   MED_TRIA7,//7
100                                   MED_QUAD8,//8
101                                   MED_QUAD9,//9
102                                   MED_SEG4,//10
103                                   MED_NONE,//11
104                                   MED_NONE,//12
105                                   MED_NONE,//13
106                                   MED_TETRA4,//14
107                                   MED_PYRA5,//15
108                                   MED_PENTA6,//16
109                                   MED_NONE,//17
110                                   MED_HEXA8,//18
111                                   MED_NONE,//19
112                                   MED_TETRA10,//20
113                                   MED_NONE,//21
114                                   MED_OCTA12,//22
115                                   MED_PYRA13,//23
116                                   MED_NONE,//24
117                                   MED_PENTA15,//25
118                                   MED_NONE,//26
119                                   MED_HEXA27,//27
120                                   MED_NONE,//28
121                                   MED_NONE,//29
122                                   MED_HEXA20,//30
123                                   MED_POLYHEDRON,//31
124                                   MED_NONE,//32
125                                   MED_NONE//33
126 };
127
128 double MEDLoader::_EPS_FOR_NODE_COMP=1.e-12;
129
130 int MEDLoader::_COMP_FOR_CELL=0;
131
132 int MEDLoader::_TOO_LONG_STR=0;
133
134 using namespace ParaMEDMEM;
135
136 /// @cond INTERNAL
137
138 namespace MEDLoaderNS
139 {
140   class FieldPerTypeCopier
141   {
142   public:
143     FieldPerTypeCopier(double *ptr):_ptr(ptr) { }
144     void operator()(const MEDLoader::MEDFieldDoublePerCellType& elt) { _ptr=std::copy(elt.getArray(),elt.getArray()+elt.getNbOfValues(),_ptr); }
145   private:
146     double *_ptr;
147   };
148  
149   class ConnReaderML
150   {
151   public:
152     ConnReaderML(const int *c, int val):_conn(c),_val(val) { }
153     bool operator() (const int& pos) { return _conn[pos]!=_val; }
154   private:
155     const int *_conn;
156     int _val;
157   };
158   
159   std::vector<std::string> getMeshNamesFid(med_idt fid);
160   void readFieldDoubleDataInMedFile(const char *fileName, const char *meshName, const char *fieldName,
161                                     int iteration, int order, ParaMEDMEM::TypeOfField typeOfOutField,
162                                     std::list<MEDLoader::MEDFieldDoublePerCellType>& field,
163                                     double& time, std::vector<std::string>& infos);
164   std::vector<int> getIdsFromFamilies(const char *fileName, const char *meshName, const std::vector<std::string>& fams);
165   std::vector<int> getIdsFromGroups(const char *fileName, const char *meshName, const std::vector<std::string>& grps);
166   med_int getIdFromMeshName(med_idt fid, const char *meshName, std::string& trueMeshName) throw(INTERP_KERNEL::Exception);
167   void dispatchElems(int nbOfElemCell, int nbOfElemFace, int& nbOfElem, med_entity_type& whichEntity);
168   int readUMeshDimFromFile(const char *fileName, const char *meshName, std::vector<int>& possibilities);
169   void readUMeshDataInMedFile(med_idt fid, med_int meshId, DataArrayDouble *&coords, std::list<MEDLoader::MEDConnOfOneElemType>& conn, std::string& desc);
170   int buildMEDSubConnectivityOfOneType(const std::vector<const DataArrayInt *>& conn, const std::vector<const DataArrayInt *>& connIndex, const std::vector<const DataArrayInt *>& families, INTERP_KERNEL::NormalizedCellType type,
171                                        std::vector<int>& conn4MEDFile, std::vector<int>& connIndex4MEDFile, std::vector<int>& connIndexRk24MEDFile,
172                                        std::vector<int>& fam4MEDFile, std::vector<int>& renumber);
173   MEDCouplingUMesh *readUMeshFromFileLev1(const char *fileName, const char *meshName, int meshDimRelToMax, const std::vector<int>& ids,
174                                           const std::vector<INTERP_KERNEL::NormalizedCellType>& typesToKeep, unsigned& meshDimExtract, int *&cellRenum) throw(INTERP_KERNEL::Exception);
175   void tradMEDFileCoreFrmt2MEDCouplingUMesh(const std::list<MEDLoader::MEDConnOfOneElemType>& medConnFrmt,
176                                             const std::vector<int>& familiesToKeep,
177                                             DataArrayInt* &conn,
178                                             DataArrayInt* &connIndex,
179                                             int *&cellRenum);
180   ParaMEDMEM::DataArrayDouble *buildArrayFromRawData(const std::list<MEDLoader::MEDFieldDoublePerCellType>& fieldPerType,
181                                                      const std::vector<std::string>& infos);
182   int buildMEDSubConnectivityOfOneTypesPolyg(const std::vector<const DataArrayInt *>& conn, const std::vector<const DataArrayInt *>& connIndex, const std::vector<const DataArrayInt *>& families,
183                                              std::vector<int>& conn4MEDFile, std::vector<int>& connIndex4MEDFile, std::vector<int>& fam4MEDFile, std::vector<int>& renumber);
184   int buildMEDSubConnectivityOfOneTypesPolyh(const std::vector<const DataArrayInt *>&conn, const std::vector<const DataArrayInt *>& connIndex, const std::vector<const DataArrayInt *>& families,
185                                              std::vector<int>& conn4MEDFile, std::vector<int>& connIndex4MEDFile, std::vector<int>& connIndexRk24MEDFile,
186                                              std::vector<int>& fam4MEDFile, std::vector<int>& renumber);
187   int buildMEDSubConnectivityOfOneTypeStaticTypes(const std::vector<const DataArrayInt *>& conn, const std::vector<const DataArrayInt *>& connIndex, const std::vector<const DataArrayInt *>& families,
188                                                   INTERP_KERNEL::NormalizedCellType type, std::vector<int>& conn4MEDFile, std::vector<int>& fam4MEDFile, std::vector<int>& renumber);
189   ParaMEDMEM::MEDCouplingFieldDouble *readFieldDoubleLev1(const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName, int iteration, int order,
190                                                           ParaMEDMEM::TypeOfField typeOfOutField) throw(INTERP_KERNEL::Exception);
191   ParaMEDMEM::MEDCouplingFieldDouble *readFieldDoubleLev2(const char *fileName, ParaMEDMEM::TypeOfField typeOfOutField, unsigned meshDim, const int *renumCell, const ParaMEDMEM::MEDCouplingUMesh *mesh,
192                                                           const std::vector<std::string>& infos, const char *fieldName, int iteration, int order, double time,
193                                                           std::list<MEDLoader::MEDFieldDoublePerCellType>& fieldPerCellType) throw(INTERP_KERNEL::Exception);
194   med_idt appendFieldSimpleAtt(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, med_int& numdt, med_int& numo, med_float& dt);
195   void appendFieldDirectly(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f);
196   void appendNodeProfileField(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, const int *thisMeshNodeIds);
197   void appendCellProfileField(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, const int *thisMeshCellIds);
198   void appendNodeElementProfileField(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, const int *thisMeshCellIds);
199   void prepareCellFieldDoubleForWriting(const ParaMEDMEM::MEDCouplingFieldDouble *f, const int *cellIds, std::list<MEDLoader::MEDFieldDoublePerCellType>& split);
200   void fillGaussDataOnField(const char *fileName, const std::list<MEDLoader::MEDFieldDoublePerCellType>& data, MEDCouplingFieldDouble *f);
201   void writeUMeshesDirectly(const char *fileName, const std::vector<const ParaMEDMEM::MEDCouplingUMesh *>& mesh, const std::vector<const DataArrayInt *>& families, bool forceFromScratch, bool &isRenumbering);
202   void writeUMeshesPartitionDirectly(const char *fileName, const char *meshName, const std::vector<const ParaMEDMEM::MEDCouplingUMesh *>& meshes, bool forceFromScratch);
203   void writeFieldAndMeshDirectly(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, bool forceFromScratch);
204   void writeFieldTryingToFitExistingMesh(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f);
205 }
206
207 /// @endcond
208
209 /*!
210  * This method sets the epsilon value used for node comparison when trying to buid a profile for a field on node/cell on an already written mesh.
211  */
212 void MEDLoader::setEpsilonForNodeComp(double val) throw(INTERP_KERNEL::Exception)
213 {
214   _EPS_FOR_NODE_COMP=val;
215 }
216
217 /*!
218  * This method sets the policy comparison when trying to fit the already written mesh on a field. The semantic of the policy is specified in MEDCouplingUMesh::zipConnectivityTraducer.
219  */
220 void MEDLoader::setCompPolicyForCell(int val) throw(INTERP_KERNEL::Exception)
221 {
222   _COMP_FOR_CELL=val;
223 }
224
225 /*!
226  * This method set the behaviour of MEDLoader when a too long string is seen in datastructure before copy it in MED file.
227  * By default (0) an exception is thrown. If equal to 1 a warning is emitted in std_err but no exception is thrown.
228  */
229 void MEDLoader::setTooLongStrPolicy(int val) throw(INTERP_KERNEL::Exception)
230 {
231   _TOO_LONG_STR=val;
232 }
233
234 /*!
235  * @param lgth is the size of fam tab. For classical types conn is size of 'lgth'*number_of_nodes_in_type.
236  * @param index is optionnal only for polys. Set it to 0 if it is not the case.
237  * @param connLgth is the size of conn in the case of poly. Unsued if it is not the case.
238  */
239 MEDLoader::MEDConnOfOneElemType::MEDConnOfOneElemType(INTERP_KERNEL::NormalizedCellType type, int *conn, int *index, int *fam, int lgth, int connLgth):_lgth(lgth),_fam(fam),
240                                                                                                                                                        _conn(conn),_index(index),
241                                                                                                                                                        _global(0),_conn_lgth(connLgth),
242                                                                                                                                                        _type(type)
243 {
244 }
245
246 void MEDLoader::MEDConnOfOneElemType::setGlobal(int *global)
247 {
248   if(_global!=global)
249     {
250       if(_global)
251         delete [] _global;
252       _global=global;
253     }
254 }
255
256 void MEDLoader::MEDConnOfOneElemType::releaseArray()
257 {
258   delete [] _fam;
259   delete [] _conn;
260   delete [] _index;
261   delete [] _global;
262 }
263
264 MEDLoader::MEDFieldDoublePerCellType::MEDFieldDoublePerCellType(INTERP_KERNEL::NormalizedCellType type, double *values, int ncomp, int nGeoElt, int nbi,
265                                                                 const int *cellIdPerType, const char *locName):_ngeo_elt(nGeoElt),_nbi(nbi),_ncomp(ncomp),_values(values),_type(type)
266 {
267   if(cellIdPerType)
268     _cell_id_per_type.insert(_cell_id_per_type.end(),cellIdPerType,cellIdPerType+nGeoElt);
269   if(locName)
270     _loc_name=locName;
271 }
272
273 void MEDLoader::MEDFieldDoublePerCellType::releaseArray()
274 {
275   delete [] _values;
276 }
277
278 /// @cond INTERNAL
279
280 std::vector<std::string> MEDLoaderNS::getMeshNamesFid(med_idt fid)
281 {
282   med_mesh_type type_maillage;
283   char maillage_description[MED_COMMENT_SIZE+1];
284   char dtunit[MED_COMMENT_SIZE+1];
285   med_int space_dim;
286   med_int mesh_dim;
287   char nommaa[MED_NAME_SIZE+1];
288   med_axis_type axistype;
289   med_sorting_type stype;
290   med_int n=MEDnMesh(fid);
291   std::vector<std::string> ret(n);
292   for(int i=0;i<n;i++)
293     {
294       int naxis=MEDmeshnAxis(fid,i+1);
295       INTERP_KERNEL::AutoPtr<char> axisname=MEDLoaderBase::buildEmptyString(naxis*MED_SNAME_SIZE);
296       INTERP_KERNEL::AutoPtr<char> axisunit=MEDLoaderBase::buildEmptyString(naxis*MED_SNAME_SIZE);
297       int nstep;
298       MEDmeshInfo(fid,i+1,nommaa,&space_dim,&mesh_dim,&type_maillage,maillage_description,dtunit,&stype,&nstep,&axistype,axisname,axisunit);
299       std::string cur=MEDLoaderBase::buildStringFromFortran(nommaa,sizeof(nommaa));
300       ret[i]=cur;
301     }
302   return ret;
303 }
304
305 void MEDLoaderNS::fillGaussDataOnField(const char *fileName, const std::list<MEDLoader::MEDFieldDoublePerCellType>& data, MEDCouplingFieldDouble *f)
306 {
307   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
308   char locName[MED_NAME_SIZE+1];
309   int nloc=MEDnLocalization(fid);
310   med_geometry_type typeGeo;
311   int offset=0;
312   for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=data.begin();iter!=data.end();iter++)
313     {
314       const std::string& loc=(*iter).getLocName();
315       int idLoc=1;
316       int nbOfGaussPt=-1;
317       med_int spaceDim;
318       for(;idLoc<=nloc;idLoc++)
319         {
320           char geointerpname[MED_NAME_SIZE+1]="";
321           char ipointstructmeshname[MED_NAME_SIZE+1]="";
322           med_int nsectionmeshcell;
323           med_geometry_type sectiongeotype;
324           MEDlocalizationInfo(fid,idLoc,locName,&typeGeo,&spaceDim,&nbOfGaussPt, geointerpname, ipointstructmeshname, &nsectionmeshcell,
325                               &sectiongeotype);
326           if(loc==locName)
327             break;
328         }
329       int dim=(int)INTERP_KERNEL::CellModel::GetCellModel((*iter).getType()).getDimension();
330       int nbPtPerCell=(int)INTERP_KERNEL::CellModel::GetCellModel((*iter).getType()).getNumberOfNodes();
331       std::vector<double> refcoo(nbPtPerCell*dim),gscoo(nbOfGaussPt*dim),w(nbOfGaussPt);
332       MEDlocalizationRd(fid,(*iter).getLocName().c_str(),MED_FULL_INTERLACE,&refcoo[0],&gscoo[0],&w[0]);
333       if((*iter).getCellIdPerType().empty())
334         f->setGaussLocalizationOnType((*iter).getType(),refcoo,gscoo,w);
335       else
336         {
337           MEDCouplingAutoRefCountObjectPtr<DataArrayInt> pfl=DataArrayInt::New();
338           pfl->alloc((*iter).getCellIdPerType().size(),1);
339           pfl->iota(offset);
340           f->setGaussLocalizationOnCells(pfl->begin(),pfl->end(),refcoo,gscoo,w);
341         }
342       offset+=(*iter).getNbOfGeoElt();
343     }
344   MEDfileClose(fid);
345 }
346
347 /// @endcond
348
349 void MEDLoader::CheckFileForRead(const char *fileName) throw(INTERP_KERNEL::Exception)
350 {
351   MEDFileUtilities::CheckFileForRead(fileName);
352 }
353
354 std::vector<std::string> MEDLoader::GetMeshNames(const char *fileName) throw(INTERP_KERNEL::Exception)
355 {
356   CheckFileForRead(fileName);
357   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
358   std::vector<std::string> ret=MEDLoaderNS::getMeshNamesFid(fid);
359   MEDfileClose(fid);
360   return ret;
361 }
362
363 std::vector< std::pair<std::string,std::string> > MEDLoader::GetComponentsNamesOfField(const char *fileName, const char *fieldName) throw(INTERP_KERNEL::Exception)
364 {
365   CheckFileForRead(fileName);
366   MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
367   med_int nbFields=MEDnField(fid);
368   std::vector<std::string> fields(nbFields);
369   med_field_type typcha;
370   for(int i=0;i<nbFields;i++)
371     {
372       med_int ncomp=MEDfieldnComponent(fid,i+1);
373       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
374       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
375       INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE);
376       med_int nbPdt;
377       med_bool localmesh;
378       INTERP_KERNEL::AutoPtr<char> maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
379       INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
380       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
381       std::string meshName=MEDLoaderBase::buildStringFromFortran(maa_ass,MED_NAME_SIZE);
382       std::string curFieldName=MEDLoaderBase::buildStringFromFortran(nomcha,MED_NAME_SIZE+1);
383       if(curFieldName==fieldName)
384         {
385           std::vector< std::pair<std::string,std::string> > ret(ncomp);
386           for(int j=0;j<ncomp;j++)
387             ret[j]=std::pair<std::string,std::string>(MEDLoaderBase::buildStringFromFortran(((char *)comp)+j*MED_SNAME_SIZE,MED_SNAME_SIZE),
388                                                       MEDLoaderBase::buildStringFromFortran(((char *)unit)+j*MED_SNAME_SIZE,MED_SNAME_SIZE));
389           return ret;
390         }
391       fields[i]=curFieldName;
392     }
393   std::ostringstream oss; oss << "MEDLoader::GetComponentsNamesOfField : no such field \"" << fieldName << "\" in file \"" << fileName << "\" !" << std::endl;
394   oss << "Possible field names are : " << std::endl;
395   std::copy(fields.begin(),fields.end(),std::ostream_iterator<std::string>(oss," "));
396   throw INTERP_KERNEL::Exception(oss.str().c_str());
397 }
398
399 /*!
400  * Given a 'fileName' and a 'meshName' this method returns global information concerning this mesh.
401  * It returns, in this order :
402  * - number of cells sorted by dimension and by geometry type. The first entry in the vector is the maximal dimension, the 2nd in the vector is the maximal dimension-1...
403  * - the mesh dimension
404  * - the space dimension
405  * - the number of nodes
406  */
407 std::vector< std::vector< std::pair<INTERP_KERNEL::NormalizedCellType,int> > > MEDLoader::GetUMeshGlobalInfo(const char *fileName, const char *meshName, int &meshDim, int& spaceDim, int& numberOfNodes) throw(INTERP_KERNEL::Exception)
408 {
409   CheckFileForRead(fileName);
410   MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
411   std::set<int> poss;
412   char nommaa[MED_NAME_SIZE+1];
413   char maillage_description[MED_COMMENT_SIZE+1];
414   med_mesh_type type_maillage;
415   std::string trueMeshName;
416   med_int meshId=MEDLoaderNS::getIdFromMeshName(fid,meshName,trueMeshName);
417   INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE);
418   med_sorting_type sortingType;
419   med_int nstep;
420   med_axis_type axisType;
421   int naxis=MEDmeshnAxis(fid,meshId);
422   INTERP_KERNEL::AutoPtr<char> axisname=MEDLoaderBase::buildEmptyString(naxis*MED_SNAME_SIZE);
423   INTERP_KERNEL::AutoPtr<char> axisunit=MEDLoaderBase::buildEmptyString(naxis*MED_SNAME_SIZE);
424   MEDmeshInfo(fid,meshId,nommaa,&spaceDim,&meshDim,&type_maillage,maillage_description,dt_unit,&sortingType,&nstep,&axisType,axisname,axisunit); 
425   if(type_maillage!=MED_UNSTRUCTURED_MESH)
426     {
427       std::ostringstream oss; oss << "MEDLoader::GetUMeshGlobalInfo : Mesh \""<< meshName << "\" in file \"" << fileName;
428       oss << "\" exists but it is not an unstructured mesh ! This method is not relevant for mesh types that are not unstructured !";
429       throw INTERP_KERNEL::Exception(oss.str().c_str());
430     }
431   // limitation
432   if(nstep!=1)
433     throw INTERP_KERNEL::Exception("MEDLoader::GetUMeshGlobalInfo : multisteps on mesh not managed !");
434   med_int numdt,numit;
435   med_float dt;
436   MEDmeshComputationStepInfo(fid,nommaa,1,&numdt,&numit,&dt);
437   // endlimitation
438   std::vector<int> dims;
439   std::vector< std::pair<INTERP_KERNEL::NormalizedCellType,int> > geoTypes;
440   med_bool changement,transformation;
441   for(int i=0;i<MED_N_CELL_FIXED_GEO;i++)
442     {
443       med_geometry_type curMedType=typmai[i];
444       int curNbOfElemM=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,curMedType,MED_CONNECTIVITY,MED_NODAL,&changement,&transformation);
445       if(curNbOfElemM>0)
446         {
447           INTERP_KERNEL::NormalizedCellType typp=typmai2[i];
448           int mdimCell=INTERP_KERNEL::CellModel::GetCellModel(typp).getDimension();
449           dims.push_back(mdimCell);
450           geoTypes.push_back(std::pair<INTERP_KERNEL::NormalizedCellType,int>(typp,curNbOfElemM));
451         }
452     }
453   int maxLev=*std::max_element(dims.begin(),dims.end());
454   int lowLev=*std::min_element(dims.begin(),dims.end());
455   int nbOfLevels=maxLev-lowLev+1;
456   std::vector< std::vector< std::pair<INTERP_KERNEL::NormalizedCellType,int> > > ret(nbOfLevels);
457   for(std::size_t i=0;i<dims.size();i++)
458     {
459       ret[maxLev-dims[i]].push_back(geoTypes[i]);
460     }
461   numberOfNodes=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_NODE,MED_NONE,MED_COORDINATE,MED_NO_CMODE,&changement,&transformation);
462   return ret;
463 }
464
465 std::vector<std::string> MEDLoader::GetMeshNamesOnField(const char *fileName, const char *fieldName) throw(INTERP_KERNEL::Exception)
466 {
467   CheckFileForRead(fileName);
468   std::vector<std::string> ret;
469   //
470   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
471   med_int nbFields=MEDnField(fid);
472   //
473   med_field_type typcha;
474   INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE);
475   INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
476   med_bool localmesh;
477   //
478   for(int i=0;i<nbFields;i++)
479     {
480       med_int ncomp=MEDfieldnComponent(fid,i+1);
481       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
482       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
483       med_int nbPdt;
484       INTERP_KERNEL::AutoPtr<char> maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
485       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
486       std::string meshName=MEDLoaderBase::buildStringFromFortran(maa_ass,MED_NAME_SIZE);
487       std::string curFieldName=MEDLoaderBase::buildStringFromFortran(nomcha,MED_NAME_SIZE+1);
488       if(curFieldName==fieldName)
489         ret.push_back(meshName);
490     }
491   MEDfileClose(fid);
492   return ret;
493 }
494
495 std::vector<std::string> MEDLoader::GetMeshFamiliesNames(const char *fileName, const char *meshName) throw(INTERP_KERNEL::Exception)
496 {
497   CheckFileForRead(fileName);
498   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
499   med_int nfam=MEDnFamily(fid,meshName);
500   std::vector<std::string> ret(nfam);
501   char nomfam[MED_NAME_SIZE+1];
502   med_int numfam;
503   for(int i=0;i<nfam;i++)
504     {
505       int ngro=MEDnFamilyGroup(fid,meshName,i+1);
506       med_int natt=MEDnFamily23Attribute(fid,meshName,i+1);
507       INTERP_KERNEL::AutoPtr<med_int> attide=new med_int[natt];
508       INTERP_KERNEL::AutoPtr<med_int> attval=new med_int[natt];
509       INTERP_KERNEL::AutoPtr<char> attdes=new char[MED_COMMENT_SIZE*natt+1];
510       INTERP_KERNEL::AutoPtr<char> gro=new char[MED_LNAME_SIZE*ngro+1];
511       MEDfamily23Info(fid,meshName,i+1,nomfam,attide,attval,attdes,&numfam,gro);
512       std::string cur=MEDLoaderBase::buildStringFromFortran(nomfam,sizeof(nomfam));
513       ret[i]=cur;
514     }
515   MEDfileClose(fid);
516   return ret;
517 }
518
519
520 std::vector<std::string> MEDLoader::GetMeshFamiliesNamesOnGroup(const char *fileName, const char *meshName, const char *grpName) throw(INTERP_KERNEL::Exception)
521 {
522   CheckFileForRead(fileName);
523   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
524   med_int nfam=MEDnFamily(fid,meshName);
525   std::vector<std::string> ret;
526   char nomfam[MED_NAME_SIZE+1];
527   med_int numfam;
528   for(int i=0;i<nfam;i++)
529     {
530       int ngro=MEDnFamilyGroup(fid,meshName,i+1);
531       med_int natt=MEDnFamily23Attribute(fid,meshName,i+1);
532       INTERP_KERNEL::AutoPtr<med_int> attide=new med_int[natt];
533       INTERP_KERNEL::AutoPtr<med_int> attval=new med_int[natt];
534       INTERP_KERNEL::AutoPtr<char> attdes=new char[MED_COMMENT_SIZE*natt+1];
535       INTERP_KERNEL::AutoPtr<char> gro=new char[MED_LNAME_SIZE*ngro+1];
536       MEDfamily23Info(fid,meshName,i+1,nomfam,attide,attval,attdes,&numfam,gro);
537       std::string cur=MEDLoaderBase::buildStringFromFortran(nomfam,sizeof(nomfam));
538       for(int j=0;j<ngro;j++)
539         {
540           std::string cur2=MEDLoaderBase::buildStringFromFortran(gro+j*MED_LNAME_SIZE,MED_LNAME_SIZE);
541           if(cur2==grpName)
542             ret.push_back(cur);
543         }
544     }
545   MEDfileClose(fid);
546   return ret;
547 }
548
549 std::vector<std::string> MEDLoader::GetMeshGroupsNamesOnFamily(const char *fileName, const char *meshName, const char *famName) throw(INTERP_KERNEL::Exception)
550 {
551   CheckFileForRead(fileName);
552   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
553   med_int nfam=MEDnFamily(fid,meshName);
554   std::vector<std::string> ret;
555   char nomfam[MED_NAME_SIZE+1];
556   med_int numfam;
557   bool found=false;
558   for(int i=0;i<nfam && !found;i++)
559     {
560       int ngro=MEDnFamilyGroup(fid,meshName,i+1);
561       med_int natt=MEDnFamily23Attribute(fid,meshName,i+1);
562       INTERP_KERNEL::AutoPtr<med_int> attide=new med_int[natt];
563       INTERP_KERNEL::AutoPtr<med_int> attval=new med_int[natt];
564       INTERP_KERNEL::AutoPtr<char> attdes=new char[MED_COMMENT_SIZE*natt+1];
565       INTERP_KERNEL::AutoPtr<char> gro=new char[MED_LNAME_SIZE*ngro+1];
566       MEDfamily23Info(fid,meshName,i+1,nomfam,attide,attval,attdes,&numfam,gro);
567       std::string cur=MEDLoaderBase::buildStringFromFortran(nomfam,sizeof(nomfam));
568       found=(cur==famName);
569       if(found)
570         for(int j=0;j<ngro;j++)
571           {
572             std::string cur2=MEDLoaderBase::buildStringFromFortran(gro+j*MED_LNAME_SIZE,MED_LNAME_SIZE);
573             ret.push_back(cur2);
574           }
575     }
576   MEDfileClose(fid);
577   if(!found)
578     {
579       std::ostringstream oss;
580       oss << "MEDLoader::GetMeshGroupsNamesOnFamily : no such family \"" << famName << "\" in file \"" << fileName << "\" in mesh \"" << meshName << "\" !";
581       throw INTERP_KERNEL::Exception(oss.str().c_str());
582     }
583   return ret;
584 }
585
586   
587 std::vector<std::string> MEDLoader::GetMeshGroupsNames(const char *fileName, const char *meshName) throw(INTERP_KERNEL::Exception)
588 {
589   CheckFileForRead(fileName);
590   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
591   med_int nfam=MEDnFamily(fid,meshName);
592   std::vector<std::string> ret;
593   char nomfam[MED_NAME_SIZE+1];
594   med_int numfam;
595   for(int i=0;i<nfam;i++)
596     {
597       int ngro=MEDnFamilyGroup(fid,meshName,i+1);
598       med_int natt=MEDnFamily23Attribute(fid,meshName,i+1);
599       INTERP_KERNEL::AutoPtr<med_int> attide=new med_int[natt];
600       INTERP_KERNEL::AutoPtr<med_int> attval=new med_int[natt];
601       INTERP_KERNEL::AutoPtr<char> attdes=new char[MED_COMMENT_SIZE*natt+1];
602       INTERP_KERNEL::AutoPtr<char> gro=new char[MED_LNAME_SIZE*ngro+1];
603       MEDfamily23Info(fid,meshName,i+1,nomfam,attide,attval,attdes,&numfam,gro);
604       for(int j=0;j<ngro;j++)
605         {
606           std::string cur=MEDLoaderBase::buildStringFromFortran(gro+j*MED_LNAME_SIZE,MED_LNAME_SIZE);
607           if(std::find(ret.begin(),ret.end(),cur)==ret.end())
608             ret.push_back(cur);
609         }
610     }
611   MEDfileClose(fid);
612   return ret;
613 }
614 std::vector<ParaMEDMEM::TypeOfField> MEDLoader::GetTypesOfField(const char *fileName, const char *meshName, const char *fieldName) throw(INTERP_KERNEL::Exception)
615 {
616   CheckFileForRead(fileName);
617   std::vector<ParaMEDMEM::TypeOfField> ret;
618   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
619   med_int nbFields=MEDnField(fid);
620   //
621   med_field_type typcha;
622   //med_int nbpdtnor=0,pflsize,*pflval,lnsize;
623   med_int numdt=0,numo=0;
624   med_float dt=0.0;
625   char pflname[MED_NAME_SIZE+1]="";
626   char locname[MED_NAME_SIZE+1]="";
627   char *maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
628   char *nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
629   med_bool localmesh;
630   //
631   for(int i=0;i<nbFields;i++)
632     {
633       med_int ncomp=MEDfieldnComponent(fid,i+1);
634       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
635       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
636       INTERP_KERNEL::AutoPtr<char> dt_unit=new char[MED_LNAME_SIZE+1];
637       med_int nbPdt;
638       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
639       std::string curFieldName=MEDLoaderBase::buildStringFromFortran(nomcha,MED_NAME_SIZE+1);
640       std::string curMeshName=MEDLoaderBase::buildStringFromFortran(maa_ass,MED_NAME_SIZE+1);
641       if(curMeshName==meshName)
642         {
643           if(curFieldName==fieldName)
644             {
645               int profilesize,nbi;
646               if(nbPdt>0)
647                 {
648                   bool found=false;
649                   for(int ii=0;ii<nbPdt && !found;ii++)
650                     {
651                       MEDfieldComputingStepInfo(fid,nomcha,1,&numdt,&numo,&dt);
652                       med_int nbOfVal=MEDfieldnValueWithProfile(fid,nomcha,numdt,numo,MED_NODE,MED_NONE,1,MED_COMPACT_PFLMODE,
653                                                                 pflname,&profilesize,locname,&nbi);
654                       if(nbOfVal>0)
655                         {
656                           ret.push_back(ON_NODES);
657                           found=true;
658                         }
659                     }
660                 }
661               bool found=false;
662               for(int j=0;j<MED_N_CELL_FIXED_GEO && !found;j++)
663                 {
664                   if(nbPdt>0)
665                     {
666                       MEDfieldComputingStepInfo(fid,nomcha,1,&numdt,&numo,&dt);
667                       med_int nbOfVal=MEDfieldnValueWithProfile(fid,nomcha,numdt,numo,MED_CELL,typmai[j],1,MED_COMPACT_PFLMODE,
668                                                                 pflname,&profilesize,locname,&nbi);
669                       if(nbOfVal>0)
670                         {
671                           found=true;
672                           ret.push_back(ON_CELLS);
673                         }
674                     }
675                 }
676             }
677         }
678     }
679   delete [] maa_ass;
680   delete [] nomcha;
681   MEDfileClose(fid);
682   return ret;
683 }
684
685 std::vector<std::string> MEDLoader::GetAllFieldNames(const char *fileName) throw(INTERP_KERNEL::Exception)
686 {
687   CheckFileForRead(fileName);
688   std::vector<std::string> ret;
689   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
690   med_int nbFields=MEDnField(fid);
691   med_field_type typcha;
692   for(int i=0;i<nbFields;i++)
693     {
694       med_int ncomp=MEDfieldnComponent(fid,i+1);
695       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
696       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
697       INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
698       INTERP_KERNEL::AutoPtr<char> maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
699       INTERP_KERNEL::AutoPtr<char> dt_unit=new char[MED_LNAME_SIZE+1];
700       med_int nbPdt;
701       med_bool localmesh;
702       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
703       ret.push_back(std::string(nomcha));
704     }
705   MEDfileClose(fid);
706   return ret;
707 }
708
709 std::vector<std::string> MEDLoader::GetAllFieldNamesOnMesh(const char *fileName, const char *meshName) throw(INTERP_KERNEL::Exception)
710 {
711   CheckFileForRead(fileName);
712   std::vector<std::string> ret;
713   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
714   med_int nbFields=MEDnField(fid);
715   //
716   med_field_type typcha;
717   char *maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
718   char *nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
719   //
720   for(int i=0;i<nbFields;i++)
721     {
722       med_int ncomp=MEDfieldnComponent(fid,i+1);
723       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
724       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
725       INTERP_KERNEL::AutoPtr<char> dt_unit=new char[MED_LNAME_SIZE+1];
726       med_int nbPdt;
727       med_bool localmesh;
728       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
729       std::string curFieldName=MEDLoaderBase::buildStringFromFortran(nomcha,MED_NAME_SIZE+1);
730       std::string curMeshName=MEDLoaderBase::buildStringFromFortran(maa_ass,MED_NAME_SIZE+1);
731       //
732       if(curMeshName==meshName)
733         ret.push_back(curFieldName);
734     }
735   delete [] maa_ass;
736   delete [] nomcha;
737   MEDfileClose(fid);
738   return ret;
739 }
740
741 std::vector<std::string> MEDLoader::GetFieldNamesOnMesh(ParaMEDMEM::TypeOfField type, const char *fileName, const char *meshName) throw(INTERP_KERNEL::Exception)
742 {
743   CheckFileForRead(fileName);
744   switch(type)
745     {
746     case ON_CELLS:
747       return GetCellFieldNamesOnMesh(fileName,meshName);
748     case ON_NODES:
749       return GetNodeFieldNamesOnMesh(fileName,meshName);
750     default:
751       throw INTERP_KERNEL::Exception("Type of field specified not managed ! manages are ON_NODES or ON_CELLS !");
752     } 
753 }
754
755 std::vector<std::string> MEDLoader::GetCellFieldNamesOnMesh(const char *fileName, const char *meshName) throw(INTERP_KERNEL::Exception)
756 {
757   CheckFileForRead(fileName);
758   std::vector<std::string> ret;
759   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
760   med_int nbFields=MEDnField(fid);
761   //
762   med_field_type typcha;
763   //med_int nbpdtnor=0,pflsize,*pflval,lnsize;
764   med_int numdt=0,numo=0;
765   med_float dt=0.0;
766   char pflname[MED_NAME_SIZE+1]="";
767   char locname[MED_NAME_SIZE+1]="";
768   INTERP_KERNEL::AutoPtr<char> maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
769   INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE);
770   INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
771   med_bool localmesh;
772   med_int nbPdt;
773   //
774   for(int i=0;i<nbFields;i++)
775     {
776       med_int ncomp=MEDfieldnComponent(fid,i+1);
777       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
778       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
779       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
780       std::string curFieldName=MEDLoaderBase::buildStringFromFortran(nomcha,MED_NAME_SIZE+1);
781       std::string curMeshName=MEDLoaderBase::buildStringFromFortran(maa_ass,MED_NAME_SIZE+1);
782       int profilesize,nbi;
783       if(curMeshName==meshName)
784         {
785           bool found=false;
786           for(int j=0;j<MED_N_CELL_FIXED_GEO && !found;j++)
787             {
788               if(nbPdt>0)
789                 {
790                   MEDfieldComputingStepInfo(fid,nomcha,1,&numdt,&numo,&dt);
791                   med_int nbOfVal=MEDfieldnValueWithProfile(fid,nomcha,numdt,numo,MED_CELL,typmai[j],1,MED_COMPACT_PFLMODE,
792                                                             pflname,&profilesize,locname,&nbi);
793                   if(nbOfVal>0)
794                     {
795                       found=true;
796                       ret.push_back(curFieldName);
797                     }
798                 }
799             }
800         }
801     }
802   MEDfileClose(fid);
803   return ret;
804 }
805
806 std::vector<std::string> MEDLoader::GetNodeFieldNamesOnMesh(const char *fileName, const char *meshName) throw(INTERP_KERNEL::Exception)
807 {
808   CheckFileForRead(fileName);
809   std::vector<std::string> ret;
810   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
811   med_int nbFields=MEDnField(fid);
812   char pflname[MED_NAME_SIZE+1]="";
813   char locname[MED_NAME_SIZE+1]="";
814   //
815   med_field_type typcha;
816   med_int numdt=0,numo=0;
817   med_float dt=0.0;
818   INTERP_KERNEL::AutoPtr<char> maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
819   INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE);
820   INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
821   med_bool localmesh;
822   //
823   for(int i=0;i<nbFields;i++)
824     {
825       med_int ncomp=MEDfieldnComponent(fid,i+1);
826       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
827       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
828       med_int nbPdt;
829       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
830       std::string curFieldName=MEDLoaderBase::buildStringFromFortran(nomcha,MED_NAME_SIZE+1);
831       std::string curMeshName=MEDLoaderBase::buildStringFromFortran(maa_ass,MED_NAME_SIZE+1);
832       if(nbPdt>0)
833         {
834           int profilesize,nbi;
835           MEDfieldComputingStepInfo(fid,nomcha,1,&numdt,&numo,&dt);
836           med_int nbOfVal=MEDfieldnValueWithProfile(fid,nomcha,numdt,numo,MED_NODE,MED_NONE,1,MED_COMPACT_PFLMODE,
837                                                     pflname,&profilesize,locname,&nbi);
838           if(curMeshName==meshName && nbOfVal>0)
839             {
840               ret.push_back(curFieldName);
841             }
842         }
843     }
844   MEDfileClose(fid);
845   return ret;
846 }
847
848 std::vector< std::pair< std::pair<int,int>, double> > MEDLoader::GetAllFieldIterations(const char *fileName, const char *meshName, const char *fieldName) throw(INTERP_KERNEL::Exception)
849 {
850   CheckFileForRead(fileName);
851   std::string meshNameCpp(meshName);
852   std::vector< std::pair< std::pair<int,int>, double > > ret;
853   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
854   med_int nbFields=MEDnField(fid);
855   //
856   med_field_type typcha;
857   med_int numdt=0,numo=0;
858   med_float dt=0.0;
859   INTERP_KERNEL::AutoPtr<char> maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
860   INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE);
861   INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
862   med_bool localmesh;
863   //
864   for(int i=0;i<nbFields;i++)
865     {
866       med_int ncomp=MEDfieldnComponent(fid,i+1);
867       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
868       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
869       med_int nbPdt;
870       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
871       std::string curFieldName=MEDLoaderBase::buildStringFromFortran(nomcha,MED_NAME_SIZE+1);
872       if(curFieldName==fieldName)
873         {
874           for(int k=0;k<nbPdt;k++)
875             {
876               MEDfieldComputingStepInfo(fid,nomcha,k+1,&numdt,&numo,&dt);
877               ret.push_back(std::make_pair(std::make_pair(numdt,numo),dt));
878             }
879         }
880     }
881   MEDfileClose(fid);
882   return ret;
883 }
884
885 double MEDLoader::GetTimeAttachedOnFieldIteration(const char *fileName, const char *fieldName, int iteration, int order) throw(INTERP_KERNEL::Exception)
886 {
887   CheckFileForRead(fileName);
888   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
889   med_int nbFields=MEDnField(fid);
890   //
891   med_field_type typcha;
892   med_int numdt=0,numo=0;
893   med_float dt=0.0;
894   med_bool local;
895   INTERP_KERNEL::AutoPtr<char> maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
896   INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE);
897   INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
898   //
899   bool found=false;
900   bool found2=false;
901   double ret=std::numeric_limits<double>::max();
902   for(int i=0;i<nbFields && !found;i++)
903     {
904       med_int ncomp=MEDfieldnComponent(fid,i+1);
905       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
906       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
907       med_int nbPdt;
908       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&local,&typcha,comp,unit,dt_unit,&nbPdt);
909       std::string curFieldName=MEDLoaderBase::buildStringFromFortran(nomcha,MED_NAME_SIZE+1);
910       if(curFieldName==fieldName)
911         {
912           found=true;
913           for(int k=0;k<nbPdt;k++)
914             {
915               MEDfieldComputingStepInfo(fid,nomcha,k+1,&numdt,&numo,&dt);
916               if(numdt==iteration && numo==order)
917                 {
918                   found2=true;
919                   ret=dt;
920                 }
921             }
922         }
923     }
924   MEDfileClose(fid);
925   if(!found || !found2)
926     {
927       std::ostringstream oss;
928       oss << "No such field with name \"" << fieldName << "\" and iteration,order=(" << iteration << "," << order << ") exists in file \"" << fileName << "\" !";
929       throw INTERP_KERNEL::Exception(oss.str().c_str());
930     }
931   return ret;
932 }
933
934 std::vector< std::pair<int,int> > MEDLoader::GetFieldIterations(ParaMEDMEM::TypeOfField type, const char *fileName, const char *meshName, const char *fieldName) throw(INTERP_KERNEL::Exception)
935 {
936   CheckFileForRead(fileName);
937   switch(type)
938     {
939     case ON_CELLS:
940       return GetCellFieldIterations(fileName,meshName,fieldName);
941     case ON_NODES:
942       return GetNodeFieldIterations(fileName,meshName,fieldName);
943     default:
944       throw INTERP_KERNEL::Exception("Type of field specified not managed ! manages are ON_NODES or ON_CELLS !");
945     }
946 }
947
948 std::vector< std::pair<int,int> > MEDLoader::GetCellFieldIterations(const char *fileName, const char *meshName, const char *fieldName) throw(INTERP_KERNEL::Exception)
949 {
950   CheckFileForRead(fileName);
951   std::string meshNameCpp(meshName);
952   std::vector< std::pair<int,int> > ret;
953   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
954   med_int nbFields=MEDnField(fid);
955   //
956   med_field_type typcha;
957   med_int numdt=0,numo=0;
958   med_float dt=0.0;
959   char pflname[MED_NAME_SIZE+1]="";
960   char locname[MED_NAME_SIZE+1]="";
961   INTERP_KERNEL::AutoPtr<char> maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
962   INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE);
963   INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
964   med_bool localmesh;
965   //
966   for(int i=0;i<nbFields;i++)
967     {
968       med_int ncomp=MEDfieldnComponent(fid,i+1);
969       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
970       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
971       med_int nbPdt;
972       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
973       std::string curFieldName=MEDLoaderBase::buildStringFromFortran(nomcha,MED_NAME_SIZE+1);
974       if(curFieldName==fieldName)
975         {
976           bool found=false;
977           for(int j=0;j<MED_N_CELL_FIXED_GEO && !found;j++)
978             {
979               for(int k=0;k<nbPdt;k++)
980                 {
981                   int profilesize,nbi;
982                   MEDfieldComputingStepInfo(fid,nomcha,k+1,&numdt,&numo,&dt);
983                   med_int nbOfVal=MEDfieldnValueWithProfile(fid,nomcha,numdt,numo,MED_CELL,typmai[j],1,MED_COMPACT_PFLMODE,
984                                                             pflname,&profilesize,locname,&nbi);
985                   std::string maa_ass_cpp(maa_ass);
986                   if(meshNameCpp==maa_ass_cpp && nbOfVal>0)
987                     {
988                       found=true;
989                       ret.push_back(std::make_pair(numdt,numo));
990                     }
991                 }
992             }
993         }
994     }
995   MEDfileClose(fid);
996   return ret;
997 }
998
999 std::vector< std::pair<int,int> > MEDLoader::GetNodeFieldIterations(const char *fileName, const char *meshName, const char *fieldName) throw(INTERP_KERNEL::Exception)
1000 {
1001   CheckFileForRead(fileName);
1002   std::string meshNameCpp(meshName);
1003   std::vector< std::pair<int,int> > ret;
1004   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
1005   med_int nbFields=MEDnField(fid);
1006   //
1007   med_field_type typcha;
1008   med_int numdt=0,numo=0;
1009   med_float dt=0.0;
1010   char pflname[MED_NAME_SIZE+1]="";
1011   char locname[MED_NAME_SIZE+1]="";
1012   INTERP_KERNEL::AutoPtr<char> maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
1013   INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE);
1014   INTERP_KERNEL::AutoPtr<char> nomcha=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
1015   med_bool localmesh;
1016   //
1017   for(int i=0;i<nbFields;i++)
1018     {
1019       med_int ncomp=MEDfieldnComponent(fid,i+1);
1020       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
1021       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
1022       med_int nbPdt;
1023       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
1024       std::string curFieldName=MEDLoaderBase::buildStringFromFortran(nomcha,MED_NAME_SIZE+1);
1025       if(curFieldName==fieldName)
1026         {
1027           for(int k=0;k<nbPdt;k++)
1028             {
1029               int profilesize,nbi;
1030               MEDfieldComputingStepInfo(fid,nomcha,k+1,&numdt,&numo,&dt);
1031               med_int nbOfVal=MEDfieldnValueWithProfile(fid,nomcha,numdt,numo,MED_NODE,MED_NONE,1,MED_COMPACT_PFLMODE,
1032                                                         pflname,&profilesize,locname,&nbi);
1033                std::string maa_ass_cpp(maa_ass);
1034                if(meshNameCpp==maa_ass_cpp && nbOfVal>0)
1035                  {
1036                    ret.push_back(std::make_pair(numdt,numo));
1037                  }
1038             }
1039         }
1040     }
1041   MEDfileClose(fid);
1042   return ret;
1043 }
1044
1045 /*!
1046  * This method reads all the content of a field 'fieldName' at a time specified by (iteration,order) lying on a mesh 'meshName' with a specified type 'TypeOfOutField'
1047  * The returned values are strored in 'field' (sorted by type of cell), time corresponding to field, and 'infos' to load properly little strings.
1048  * The principle of this method is to put into 'field' only data that fulfills \b perfectly request.
1049  */
1050 void MEDLoaderNS::readFieldDoubleDataInMedFile(const char *fileName, const char *meshName, const char *fieldName, 
1051                                                int iteration, int order, ParaMEDMEM::TypeOfField typeOfOutField,
1052                                                std::list<MEDLoader::MEDFieldDoublePerCellType>& field,
1053                                                double& time, std::vector<std::string>& infos)
1054 {
1055   time=0.;
1056   MEDFileUtilities::CheckFileForRead(fileName);
1057   MEDFileUtilities::AutoFid fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
1058   med_int nbFields=MEDnField(fid);
1059   //
1060   med_field_type typcha;
1061   char nomcha[MED_NAME_SIZE+1]="";
1062   char pflname [MED_NAME_SIZE+1]="";
1063   char locname [MED_NAME_SIZE+1]="";
1064   std::map<ParaMEDMEM::TypeOfField, med_entity_type> tabEnt;
1065   std::map<ParaMEDMEM::TypeOfField, med_geometry_type *> tabType;
1066   std::map<ParaMEDMEM::TypeOfField, int> tabTypeLgth;
1067   med_bool localmesh;
1068   bool found=false;
1069   tabEnt[ON_CELLS]=MED_CELL;
1070   tabType[ON_CELLS]=typmai;
1071   tabTypeLgth[ON_CELLS]=MED_N_CELL_FIXED_GEO;
1072   tabEnt[ON_NODES]=MED_NODE;
1073   tabType[ON_NODES]=typmainoeud;
1074   tabTypeLgth[ON_NODES]=1;
1075   tabEnt[ON_GAUSS_PT]=MED_CELL;
1076   tabType[ON_GAUSS_PT]=typmai;
1077   tabTypeLgth[ON_GAUSS_PT]=MED_N_CELL_FIXED_GEO;
1078   tabEnt[ON_GAUSS_NE]=MED_NODE_ELEMENT;
1079   tabType[ON_GAUSS_NE]=typmai;
1080   tabTypeLgth[ON_GAUSS_NE]=MED_N_CELL_FIXED_GEO;
1081   //
1082   for(int i=0;i<nbFields && !found;i++)
1083     {
1084       med_int ncomp=MEDfieldnComponent(fid,i+1);
1085       INTERP_KERNEL::AutoPtr<char> comp=new char[ncomp*MED_SNAME_SIZE+1];
1086       INTERP_KERNEL::AutoPtr<char> unit=new char[ncomp*MED_SNAME_SIZE+1];
1087       INTERP_KERNEL::AutoPtr<char> dt_unit=new char[MED_LNAME_SIZE+1];
1088       INTERP_KERNEL::AutoPtr<char> maa_ass=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
1089       med_int nbPdt;
1090       MEDfieldInfo(fid,i+1,nomcha,maa_ass,&localmesh,&typcha,comp,unit,dt_unit,&nbPdt);
1091       std::string curMeshName=MEDLoaderBase::buildStringFromFortran(maa_ass,MED_NAME_SIZE+1);
1092       std::string curFieldName=MEDLoaderBase::buildStringFromFortran(nomcha,MED_NAME_SIZE+1);
1093       found=(curFieldName==fieldName) && (curMeshName==meshName);
1094       if(found)
1095         {
1096           infos.resize(ncomp);
1097           for(int ii=0;ii<ncomp;ii++)
1098             infos[ii]=MEDLoaderBase::buildUnionUnit(comp+ii*MED_SNAME_SIZE,MED_SNAME_SIZE,unit+ii*MED_SNAME_SIZE,MED_SNAME_SIZE);
1099           bool found2=false;
1100           med_int numdt=0,numo=0;
1101           med_float dt=0.0;
1102           for(int k=0;k<nbPdt && !found2;k++)
1103             {
1104               MEDfieldComputingStepInfo(fid,fieldName,k+1,&numdt,&numo,&dt);
1105               found2=(numdt==iteration && numo==order);
1106               if(found2)
1107                 time=dt;
1108             }
1109           if(!found2)
1110             {
1111               std::ostringstream oss; oss << "FieldDouble in file \""<< fileName<< "\" with name \"" << fieldName << "\" on mesh \"" <<  meshName;
1112               oss << "\" does not have such time step : iteration=" << iteration << " order=" << order << std::endl;
1113               throw INTERP_KERNEL::Exception(oss.str().c_str());
1114             }
1115           for(int j=0;j<tabTypeLgth[typeOfOutField];j++)
1116             {
1117               if(nbPdt>0)
1118                 {
1119                   INTERP_KERNEL::AutoPtr<char> pflDummy=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
1120                   INTERP_KERNEL::AutoPtr<char> locDummy=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
1121                   int nbProfiles=MEDfieldnProfile(fid,fieldName,numdt,numo,tabEnt[typeOfOutField],tabType[typeOfOutField][j],pflDummy,locDummy);
1122                   for(int kk=0;kk<nbProfiles;kk++)
1123                     {
1124                       int profilesize,nbi;
1125                       int nval=MEDfieldnValueWithProfile(fid,fieldName,numdt,numo,tabEnt[typeOfOutField],tabType[typeOfOutField][j],kk+1,MED_COMPACT_PFLMODE,pflname,&profilesize,locname,&nbi);
1126                       if(nval>0)
1127                         {
1128                           double *valr=new double[ncomp*nval*nbi];
1129                           MEDfieldValueWithProfileRd(fid,fieldName,iteration,order,tabEnt[typeOfOutField],tabType[typeOfOutField][j],MED_COMPACT_PFLMODE,
1130                                                      pflname,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,(unsigned char*)valr);
1131                           std::string tmp(locname);
1132                           if((locname[0]!='\0' && (typeOfOutField!=ON_GAUSS_PT))
1133                              || (locname[0]=='\0' && typeOfOutField==ON_GAUSS_PT))
1134                             {
1135                               delete [] valr;
1136                               continue;
1137                             }
1138                           INTERP_KERNEL::AutoPtr<int> pfl=0;
1139                           if(pflname[0]!='\0')
1140                             {
1141                               pfl=new int[nval];
1142                               MEDprofileRd(fid,pflname,pfl);
1143                             }
1144                           field.push_back(MEDLoader::MEDFieldDoublePerCellType(typmai2[j],valr,ncomp,nval,nbi,pfl,locname));
1145                         }
1146                     }
1147                 }
1148             }
1149         }
1150     }
1151   if(!found)
1152     {
1153       std::ostringstream oss; oss << "MEDLoaderNS::readFieldDoubleDataInMedFile : no such couple meshName=\"" << meshName << "\", fieldName=\"" << fieldName << "\" in file \"" << fileName << "\" !";
1154       throw INTERP_KERNEL::Exception(oss.str().c_str());
1155     }
1156 }
1157
1158 std::vector<int> MEDLoaderNS::getIdsFromFamilies(const char *fileName, const char *meshName, const std::vector<std::string>& fams)
1159 {
1160   std::vector<int> ret;
1161   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
1162   med_int nfam=MEDnFamily(fid,meshName);
1163   char nomfam[MED_NAME_SIZE+1];
1164   med_int numfam;
1165   for(int i=0;i<nfam;i++)
1166     {
1167       int ngro=MEDnFamilyGroup(fid,meshName,i+1);
1168       med_int natt=MEDnFamily23Attribute(fid,meshName,i+1);
1169       INTERP_KERNEL::AutoPtr<med_int> attide=new med_int[natt];
1170       INTERP_KERNEL::AutoPtr<med_int> attval=new med_int[natt];
1171       INTERP_KERNEL::AutoPtr<char> attdes=new char[MED_COMMENT_SIZE*natt+1];
1172       INTERP_KERNEL::AutoPtr<char> gro=new char[MED_LNAME_SIZE*ngro+1];
1173       MEDfamily23Info(fid,meshName,i+1,nomfam,attide,attval,attdes,&numfam,gro);
1174       std::string cur=MEDLoaderBase::buildStringFromFortran(nomfam,sizeof(nomfam));
1175       if(std::find(fams.begin(),fams.end(),cur)!=fams.end())
1176         ret.push_back(numfam);
1177     }
1178   MEDfileClose(fid);
1179   return ret;
1180 }
1181
1182 std::vector<int> MEDLoaderNS::getIdsFromGroups(const char *fileName, const char *meshName, const std::vector<std::string>& grps)
1183 {
1184   std::vector<int> ret;
1185   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
1186   med_int nfam=MEDnFamily(fid,meshName);
1187   char nomfam[MED_NAME_SIZE+1];
1188   med_int numfam;
1189   for(int i=0;i<nfam;i++)
1190     {
1191       int ngro=MEDnFamilyGroup(fid,meshName,i+1);
1192       med_int natt=MEDnFamily23Attribute(fid,meshName,i+1);
1193       INTERP_KERNEL::AutoPtr<med_int> attide=new med_int[natt];
1194       INTERP_KERNEL::AutoPtr<med_int> attval=new med_int[natt];
1195       INTERP_KERNEL::AutoPtr<char> attdes=new char[MED_COMMENT_SIZE*natt+1];
1196       INTERP_KERNEL::AutoPtr<char> gro=new char[MED_LNAME_SIZE*ngro+1];
1197       MEDfamily23Info(fid,meshName,i+1,nomfam,attide,attval,attdes,&numfam,gro);
1198       std::string cur=MEDLoaderBase::buildStringFromFortran(nomfam,sizeof(nomfam));
1199       for(int j=0;j<ngro;j++)
1200         {
1201           std::string cur2=MEDLoaderBase::buildStringFromFortran(gro+j*MED_LNAME_SIZE,MED_LNAME_SIZE);
1202           if(std::find(grps.begin(),grps.end(),cur2)!=grps.end())
1203             {
1204               ret.push_back(numfam);
1205               break;
1206             }
1207         }
1208     }
1209   MEDfileClose(fid);
1210   return ret;
1211 }
1212
1213 med_int MEDLoaderNS::getIdFromMeshName(med_idt fid, const char *meshName, std::string& trueMeshName) throw(INTERP_KERNEL::Exception)
1214 {
1215   if(meshName==0)
1216     {
1217       std::vector<std::string> meshes=getMeshNamesFid(fid);
1218       if(meshes.empty())
1219         throw INTERP_KERNEL::Exception("No mesh in file");
1220       trueMeshName=meshes[0];
1221       return 1;
1222     }
1223   std::string meshNameStr(meshName);
1224   std::vector<std::string> meshes=getMeshNamesFid(fid);
1225   if(meshes.empty())
1226     throw INTERP_KERNEL::Exception("No mesh in file");
1227   std::vector<std::string>::iterator iter=std::find(meshes.begin(),meshes.end(),meshNameStr);
1228   if(iter==meshes.end())
1229     {
1230       std::ostringstream os2;
1231       os2 << "MeshName '" << meshName << "' not in file : meshes available : ";
1232       std::copy(meshes.begin(),meshes.end(),std::ostream_iterator<std::string>(os2," "));
1233       throw INTERP_KERNEL::Exception(os2.str().c_str());
1234     }
1235   trueMeshName=meshName;
1236   return iter-meshes.begin()+1;
1237 }
1238
1239 /*!
1240  * This methods allows to merger all entities and to considerate only cell types.
1241  */
1242 void MEDLoaderNS::dispatchElems(int nbOfElemCell, int nbOfElemFace, int& nbOfElem, med_entity_type& whichEntity)
1243 {
1244   if(nbOfElemCell>=nbOfElemFace)
1245     {
1246       whichEntity=MED_CELL;
1247       nbOfElem=nbOfElemCell;
1248     }
1249   else
1250     {
1251       whichEntity=MED_CELL;
1252       nbOfElem=nbOfElemFace;
1253     }
1254 }
1255
1256 /*!
1257  * This method returns a first quick overview of mesh with name 'meshName' into the file 'fileName'.
1258  * @param possibilities the relativeToMeshDim authorized to returned maxdim. This vector is systematically cleared at the begin of this method.
1259  * @return the maximal mesh dimension of specified mesh. If nothing found -1 is returned.
1260  */
1261 int MEDLoaderNS::readUMeshDimFromFile(const char *fileName, const char *meshName, std::vector<int>& possibilities)
1262 {
1263   possibilities.clear();
1264   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
1265   int ret;
1266   std::set<int> poss;
1267   char nommaa[MED_NAME_SIZE+1];
1268   char maillage_description[MED_COMMENT_SIZE+1];
1269   med_mesh_type type_maillage;
1270   med_int Sdim,Mdim;
1271   std::string trueMeshName;
1272   med_int meshId=getIdFromMeshName(fid,meshName,trueMeshName);
1273   INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE);
1274   med_sorting_type sortingType;
1275   med_int nstep;
1276   med_axis_type axisType;
1277   int naxis=MEDmeshnAxis(fid,meshId);
1278   INTERP_KERNEL::AutoPtr<char> axisname=MEDLoaderBase::buildEmptyString(naxis*MED_SNAME_SIZE);
1279   INTERP_KERNEL::AutoPtr<char> axisunit=MEDLoaderBase::buildEmptyString(naxis*MED_SNAME_SIZE);
1280   MEDmeshInfo(fid,meshId,nommaa,&Sdim,&Mdim,&type_maillage,maillage_description,dt_unit,&sortingType,&nstep,&axisType,axisname,axisunit);
1281   // limitation
1282   if(nstep!=1)
1283     {
1284       throw INTERP_KERNEL::Exception("multisteps on mesh not managed yet !");
1285     } 
1286   med_int numdt,numit;
1287   med_float dt;
1288   MEDmeshComputationStepInfo(fid,nommaa,1,&numdt,&numit,&dt);
1289   // endlimitation
1290   for(int i=0;i<MED_N_CELL_GEO_FIXED_CON;i++)
1291     {
1292       med_geometry_type curMedType=typmai[i];
1293       med_bool changement,transformation;
1294       int curNbOfElemM=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,curMedType,MED_CONNECTIVITY,MED_NODAL,&changement,&transformation);
1295       int curNbOfElemF=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,curMedType,MED_CONNECTIVITY,MED_NODAL,&changement,&transformation);//limitation
1296       int curNbOfElem;
1297       med_entity_type whichEntity;
1298       MEDLoaderNS::dispatchElems(curNbOfElemM,curNbOfElemF,curNbOfElem,whichEntity);
1299       if(curNbOfElem>0)
1300         {
1301           INTERP_KERNEL::NormalizedCellType type=typmai2[i];
1302           int curDim=(int)INTERP_KERNEL::CellModel::GetCellModel(type).getDimension();
1303           poss.insert(curDim);
1304         }
1305     }
1306   MEDfileClose(fid);
1307   if(!poss.empty())
1308     {
1309       ret=*poss.rbegin();
1310       for(std::set<int>::const_reverse_iterator it=poss.rbegin();it!=poss.rend();it++)
1311         possibilities.push_back(*it-ret);
1312     }
1313   else
1314     ret=-2;
1315   return ret;
1316 }
1317
1318 void MEDLoaderNS::readUMeshDataInMedFile(med_idt fid, med_int meshId, DataArrayDouble *&coords, std::list<MEDLoader::MEDConnOfOneElemType>& conn, std::string& description)
1319 {
1320   char nommaa[MED_NAME_SIZE+1];
1321   char maillage_description[MED_COMMENT_SIZE+1];
1322   med_mesh_type type_maillage;
1323   med_int Mdim;
1324   med_int Sdim;
1325   INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE);
1326   med_sorting_type sortingType;
1327   med_int nstep;
1328   med_axis_type axisType;
1329   med_int numdt,numit;
1330   med_float dt;
1331   med_bool changement,transformation;
1332   // endlimitation
1333   Sdim=MEDmeshnAxis(fid,1);
1334   INTERP_KERNEL::AutoPtr<char> comp=MEDLoaderBase::buildEmptyString(Sdim*MED_SNAME_SIZE);
1335   INTERP_KERNEL::AutoPtr<char> unit=MEDLoaderBase::buildEmptyString(Sdim*MED_SNAME_SIZE);
1336   MEDmeshInfo(fid,meshId,nommaa,&Sdim,&Mdim,&type_maillage,maillage_description,dt_unit,&sortingType,&nstep,&axisType,comp,unit);
1337   description=MEDLoaderBase::buildStringFromFortran(maillage_description,sizeof(maillage_description));
1338   MEDmeshComputationStepInfo(fid,nommaa,1,&numdt,&numit,&dt);
1339   int spaceDim=std::max((int)Mdim,(int)Sdim);
1340   int nCoords=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_NODE,MED_NONE,MED_COORDINATE,MED_NO_CMODE,&changement,&transformation);
1341   // limitation
1342   if(nstep!=1)
1343     {
1344       throw INTERP_KERNEL::Exception("multisteps on mesh not managed yet !");
1345     }
1346   coords=DataArrayDouble::New();
1347   coords->alloc(nCoords,spaceDim);
1348   double *coordsPtr=coords->getPointer();
1349   MEDmeshNodeCoordinateRd(fid,nommaa,numdt,numit,MED_FULL_INTERLACE,coordsPtr);
1350   for(int i=0;i<spaceDim;i++)
1351     {
1352       std::string info=MEDLoaderBase::buildUnionUnit(comp+i*MED_SNAME_SIZE,MED_SNAME_SIZE,unit+i*MED_SNAME_SIZE,MED_SNAME_SIZE);
1353       coords->setInfoOnComponent(i,info.c_str());
1354     }
1355   for(int i=0;i<MED_N_CELL_GEO_FIXED_CON;i++)
1356     {
1357       med_geometry_type curMedType=typmai[i];
1358       med_entity_type whichEntity;
1359       int curNbOfElemM=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,curMedType,MED_CONNECTIVITY,MED_NODAL,&changement,&transformation);
1360       int curNbOfElemF=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,curMedType,MED_CONNECTIVITY,MED_NODAL,&changement,&transformation);//limitation
1361       int curNbOfElem;
1362       MEDLoaderNS::dispatchElems(curNbOfElemM,curNbOfElemF,curNbOfElem,whichEntity);
1363       if(curNbOfElem>0)
1364         {
1365           int *connTab=new int[(curMedType%100)*curNbOfElem];
1366           int *fam=new int[curNbOfElem];
1367           MEDLoader::MEDConnOfOneElemType elem(typmai2[i],connTab,0,fam,curNbOfElem,-1);
1368           char *noms=new char[MED_SNAME_SIZE*curNbOfElem+1];
1369           med_bool withname=MED_FALSE,withnumber=MED_FALSE,withfam=MED_FALSE;
1370           int *globArr=new int[curNbOfElem];
1371           MEDmeshElementRd(fid,nommaa,numdt,numit,whichEntity,curMedType,MED_NODAL,MED_FULL_INTERLACE,connTab,&withname,noms,&withnumber,globArr,&withfam,fam);
1372           if(!withfam)
1373             std::fill(fam,fam+curNbOfElem,0);
1374           delete [] noms;
1375           //trying to read global numbering
1376           if(withnumber)
1377             elem.setGlobal(globArr);
1378           else
1379             delete [] globArr;
1380           //limitation manage withfam==false
1381           conn.push_back(elem);
1382         }
1383     }
1384   int curNbOfPolyElem;
1385   int curNbOfPolyElemM=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,MED_POLYGON,MED_INDEX_NODE,MED_NODAL,&changement,&transformation)-1;
1386   int curNbOfPolyElemF=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,MED_POLYGON,MED_INDEX_NODE,MED_NODAL,&changement,&transformation)-1;//limitation
1387   med_entity_type whichPolyEntity;
1388   MEDLoaderNS::dispatchElems(curNbOfPolyElemM,curNbOfPolyElemF,curNbOfPolyElem,whichPolyEntity);
1389   if(curNbOfPolyElem>0)
1390     {
1391       med_int arraySize=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,MED_POLYGON,MED_CONNECTIVITY,MED_NODAL,&changement,&transformation);
1392       int *index=new int[curNbOfPolyElem+1];
1393       int *locConn=new int[arraySize];
1394       int *fam=new int[curNbOfPolyElem];
1395       int *globArr=new int[curNbOfPolyElem];
1396       MEDLoader::MEDConnOfOneElemType elem(INTERP_KERNEL::NORM_POLYGON,locConn,index,fam,curNbOfPolyElem,arraySize);
1397       MEDmeshPolygonRd(fid,nommaa,numdt,numit,MED_CELL,MED_NODAL,index,locConn);
1398       if(MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,MED_POLYGON,MED_FAMILY_NUMBER,MED_NODAL,&changement,&transformation)>0)
1399         {
1400           if(MEDmeshEntityFamilyNumberRd(fid,nommaa,numdt,numit,MED_CELL,MED_POLYGON,fam)!=0)
1401             std::fill(fam,fam+curNbOfPolyElem,0);
1402         }
1403       else
1404         std::fill(fam,fam+curNbOfPolyElem,0);
1405       if(MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,MED_POLYGON,MED_NUMBER,MED_NODAL,&changement,&transformation)>0)
1406         {
1407           if(MEDmeshEntityNumberRd(fid,nommaa,numdt,numit,whichPolyEntity,MED_POLYGON,globArr)==0)
1408             elem.setGlobal(globArr);
1409           else
1410             delete [] globArr;
1411         }
1412       else
1413         delete [] globArr;
1414       conn.push_back(elem);
1415     }
1416   curNbOfPolyElem=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,MED_POLYHEDRON,MED_INDEX_FACE,MED_NODAL,&changement,&transformation)-1;
1417   if(curNbOfPolyElem>0)
1418     {
1419       med_int indexFaceLgth,connFaceLgth;
1420       indexFaceLgth=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,MED_POLYHEDRON,MED_INDEX_NODE,MED_NODAL,&changement,&transformation);
1421       connFaceLgth=MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,MED_POLYHEDRON,MED_CONNECTIVITY,MED_NODAL,&changement,&transformation);
1422       INTERP_KERNEL::AutoPtr<int> index=new int[curNbOfPolyElem+1];
1423       INTERP_KERNEL::AutoPtr<int> indexFace=new int[indexFaceLgth];
1424       INTERP_KERNEL::AutoPtr<int> locConn=new int[connFaceLgth];
1425       int *fam=new int[curNbOfPolyElem];
1426       int *globArr=new int[curNbOfPolyElem];
1427       MEDmeshPolyhedronRd(fid,nommaa,numdt,numit,MED_CELL,MED_NODAL,index,indexFace,locConn);
1428       if(MEDmeshnEntity(fid,nommaa,numdt,numit,whichPolyEntity,MED_POLYHEDRON,MED_FAMILY_NUMBER,MED_NODAL,&changement,&transformation)>0)
1429         {
1430           if(MEDmeshEntityFamilyNumberRd(fid,nommaa,numdt,numit,whichPolyEntity,MED_POLYHEDRON,fam)!=0)
1431             std::fill(fam,fam+curNbOfPolyElem,0);
1432         }
1433       else
1434         std::fill(fam,fam+curNbOfPolyElem,0);
1435       int arraySize=connFaceLgth;
1436       for(int i=0;i<curNbOfPolyElem;i++)
1437         arraySize+=index[i+1]-index[i]-1;
1438       int *finalConn=new int[arraySize];
1439       int *finalIndex=new int[curNbOfPolyElem+1];
1440       finalIndex[0]=1;
1441       int *wFinalConn=finalConn;
1442       for(int i=0;i<curNbOfPolyElem;i++)
1443         {
1444           finalIndex[i+1]=finalIndex[i]+index[i+1]-index[i]-1+indexFace[index[i+1]-1]-indexFace[index[i]-1];
1445           wFinalConn=std::copy(locConn+indexFace[index[i]-1]-1,locConn+indexFace[index[i]]-1,wFinalConn);
1446           for(int j=index[i];j<index[i+1]-1;j++)
1447             {
1448               *wFinalConn++=0;
1449               wFinalConn=std::copy(locConn+indexFace[j]-1,locConn+indexFace[j+1]-1,wFinalConn);
1450             }
1451         }
1452       MEDLoader::MEDConnOfOneElemType elem(INTERP_KERNEL::NORM_POLYHED,finalConn,finalIndex,fam,curNbOfPolyElem,arraySize);
1453       if(MEDmeshnEntity(fid,nommaa,numdt,numit,MED_CELL,MED_POLYHEDRON,MED_NUMBER,MED_NODAL,&changement,&transformation)>0)
1454         {
1455           if(MEDmeshEntityNumberRd(fid,nommaa,numdt,numit,whichPolyEntity,MED_POLYHEDRON,globArr)==0)
1456             elem.setGlobal(globArr);
1457           else
1458             delete [] globArr;
1459         }
1460       else
1461         delete [] globArr;
1462       conn.push_back(elem);
1463     }
1464 }
1465
1466 /// @cond INTERNAL
1467
1468 namespace MEDLoaderNS
1469 {
1470   template<class T>
1471   unsigned calculateHighestMeshDim(const std::list<T>& conn)
1472   {
1473     unsigned ret=0;
1474     for(typename std::list<T>::const_iterator iter=conn.begin();iter!=conn.end();iter++)
1475       {
1476         unsigned curDim=INTERP_KERNEL::CellModel::GetCellModel((*iter).getType()).getDimension();
1477         if(ret<curDim)
1478           ret=curDim;
1479       }
1480     return ret;
1481   }
1482   
1483   template<class T>
1484   void keepSpecifiedMeshDim(typename std::list<T>& conn, unsigned meshDim)
1485   {
1486     for(typename std::list<T>::iterator iter=conn.begin();iter!=conn.end();)
1487       {
1488         unsigned curDim=INTERP_KERNEL::CellModel::GetCellModel((*iter).getType()).getDimension();
1489         if(curDim!=meshDim)
1490           {
1491             (*iter).releaseArray();
1492             iter=conn.erase(iter);
1493           }
1494         else
1495           iter++;
1496       }
1497   }
1498   
1499   template<class T>
1500   void keepTypes(typename std::list<T>& conn, const std::vector<INTERP_KERNEL::NormalizedCellType>& typesToKeep)
1501   {
1502     if(!typesToKeep.empty())
1503       {
1504         for(typename std::list<T>::iterator iter=conn.begin();iter!=conn.end();)
1505           {
1506             INTERP_KERNEL::NormalizedCellType curType=(*iter).getType();
1507             if(std::find(typesToKeep.begin(),typesToKeep.end(),curType)==typesToKeep.end())
1508               {
1509                 (*iter).releaseArray();
1510                 iter=conn.erase(iter);
1511               }
1512             else
1513               iter++;
1514           }
1515       }
1516   }
1517 }
1518
1519 class FieldPerTypeAccumulator
1520 {
1521 public:
1522   int operator()(int res, const MEDLoader::MEDFieldDoublePerCellType& elt) { return res+elt.getNbOfTuple(); }
1523 };
1524
1525 ParaMEDMEM::DataArrayDouble *MEDLoaderNS::buildArrayFromRawData(const std::list<MEDLoader::MEDFieldDoublePerCellType>& fieldPerType,
1526                                                                 const std::vector<std::string>& infos)
1527 {
1528   ParaMEDMEM::DataArrayDouble *ret=ParaMEDMEM::DataArrayDouble::New();
1529   int totalNbOfTuple=std::accumulate(fieldPerType.begin(),fieldPerType.end(),0,FieldPerTypeAccumulator());
1530   int nbOfComp=(*fieldPerType.begin()).getNbComp();
1531   double *ptr=new double[nbOfComp*totalNbOfTuple];
1532   ret->useArray(ptr,true,ParaMEDMEM::CPP_DEALLOC,totalNbOfTuple,nbOfComp);
1533   std::for_each(fieldPerType.begin(),fieldPerType.end(),FieldPerTypeCopier(ptr));
1534   for(int i=0;i<nbOfComp;i++)
1535     ret->setInfoOnComponent(i,infos[i].c_str());
1536   return ret;
1537 }
1538
1539 class PolyCounterForFams
1540 {
1541 public:
1542   PolyCounterForFams(int id, const int *index):_id(id),_index(index),_count(0),_sigma(0) { }
1543   void operator()(int val) { if(val==_id) _sigma+=_index[_count+1]-_index[_count]; _count++; }
1544   int getSigma() const { return _sigma; }
1545 private:
1546   int _id;
1547   const int *_index;
1548   int _count;
1549   int _sigma;
1550 };
1551
1552 /*!
1553  * This method fills unstructured connectivity using basic MED file format 'medConnFrmt'.
1554  * If in each elements of 'medConnFrmt' a renumbering cell array is found the aggregate array 'cellRenum' is returned.
1555  */
1556 void MEDLoaderNS::tradMEDFileCoreFrmt2MEDCouplingUMesh(const std::list<MEDLoader::MEDConnOfOneElemType>& medConnFrmt,
1557                                                        const std::vector<int>& familiesToKeep,
1558                                                        DataArrayInt* &conn,
1559                                                        DataArrayInt* &connIndex,
1560                                                        int *&cellRenum)
1561 {
1562   bool keepAll=familiesToKeep.empty();
1563   if(medConnFrmt.empty())
1564     {
1565       conn=0;
1566       connIndex=0;
1567       cellRenum=0;
1568       return ;
1569     }
1570   std::list<MEDLoader::MEDConnOfOneElemType>::const_iterator iter=medConnFrmt.begin();
1571   int totalNbOfCells=0;
1572   int totalNbOfMedConn=0;
1573   bool renumber=true;
1574   cellRenum=0;
1575   for(;iter!=medConnFrmt.end();iter++)
1576     {
1577       if((*iter).getGlobal()==0)
1578         renumber=false;
1579       const INTERP_KERNEL::CellModel& cellMod=INTERP_KERNEL::CellModel::GetCellModel((*iter).getType());
1580       if(keepAll)
1581         totalNbOfCells+=(*iter).getLength();
1582       else
1583         for(std::vector<int>::const_iterator iter2=familiesToKeep.begin();iter2!=familiesToKeep.end();iter2++)
1584           totalNbOfCells+=std::count((*iter).getFam(),(*iter).getFam()+(*iter).getLength(),*iter2);
1585       if(!cellMod.isDynamic())
1586         if(keepAll)
1587           totalNbOfMedConn+=(*iter).getLength()*cellMod.getNumberOfNodes();
1588         else
1589           for(std::vector<int>::const_iterator iter2=familiesToKeep.begin();iter2!=familiesToKeep.end();iter2++)
1590             totalNbOfMedConn+=std::count((*iter).getFam(),(*iter).getFam()+(*iter).getLength(),*iter2)*cellMod.getNumberOfNodes();
1591       else
1592         if(keepAll)
1593           totalNbOfMedConn+=(*iter).getConnLength();
1594         else
1595           for(std::vector<int>::const_iterator iter2=familiesToKeep.begin();iter2!=familiesToKeep.end();iter2++)
1596             {
1597               PolyCounterForFams res=std::for_each((*iter).getFam(),(*iter).getFam()+(*iter).getLength(),PolyCounterForFams(*iter2,(*iter).getIndex()));
1598               totalNbOfMedConn+=res.getSigma();
1599             }
1600     }
1601   connIndex=DataArrayInt::New();
1602   conn=DataArrayInt::New();
1603   connIndex->alloc(totalNbOfCells+1,1);
1604   int *connIdxPtr=connIndex->getPointer();
1605   int connFillId=0;
1606   conn->alloc(totalNbOfMedConn+totalNbOfCells,1);
1607   int *connPtr=conn->getPointer();
1608   if(renumber)
1609     cellRenum=new int[totalNbOfCells];
1610   int *renumW=cellRenum;
1611   for(iter=medConnFrmt.begin();iter!=medConnFrmt.end();iter++)
1612     {
1613       INTERP_KERNEL::NormalizedCellType type=(*iter).getType();
1614       const int *sourceConn=(*iter).getArray();
1615       const int *sourceIndex=(*iter).getIndex();
1616       const int *globalNum=(*iter).getGlobal();
1617       const INTERP_KERNEL::CellModel& cellMod=INTERP_KERNEL::CellModel::GetCellModel(type);
1618       int nbOfCellsInCurType;
1619       int nbOfNodesIn1Cell=cellMod.getNumberOfNodes();
1620       nbOfCellsInCurType=(*iter).getLength();
1621       bool isDyn=cellMod.isDynamic();
1622       int *tmpConnPtr;
1623       for(int i=0;i<nbOfCellsInCurType;i++)
1624         {
1625           if(keepAll)
1626             {//duplication of next 3 lines needed.
1627               *connIdxPtr=connFillId;
1628               *connPtr++=type;
1629               if(renumber)
1630                 *renumW++=globalNum[i];
1631               if(!isDyn)
1632                 tmpConnPtr=std::transform(sourceConn,sourceConn+nbOfNodesIn1Cell,connPtr,std::bind2nd(std::minus<int>(),1));
1633               else
1634                 tmpConnPtr=std::transform(sourceConn,sourceConn+sourceIndex[i+1]-sourceIndex[i],connPtr,std::bind2nd(std::minus<int>(),1));
1635               connIdxPtr++;
1636               nbOfNodesIn1Cell=tmpConnPtr-connPtr;
1637               connFillId+=nbOfNodesIn1Cell+1;
1638               connPtr=tmpConnPtr;
1639             }
1640           else if(std::find(familiesToKeep.begin(),familiesToKeep.end(),(*iter).getFam()[i])!=familiesToKeep.end())
1641             {//duplication of next 3 lines needed.
1642               *connIdxPtr=connFillId;
1643               *connPtr++=type;
1644               if(renumber)
1645                 *renumW++=globalNum[i];
1646               if(!isDyn)
1647                 tmpConnPtr=std::transform(sourceConn,sourceConn+nbOfNodesIn1Cell,connPtr,std::bind2nd(std::minus<int>(),1));
1648               else//The duplication of code is motivated by the line underneath.
1649                 tmpConnPtr=std::transform((*iter).getArray()+sourceIndex[i]-1,(*iter).getArray()+sourceIndex[i+1]-1,connPtr,std::bind2nd(std::minus<int>(),1));
1650               connIdxPtr++;
1651               nbOfNodesIn1Cell=tmpConnPtr-connPtr;
1652               connFillId+=nbOfNodesIn1Cell+1;
1653               connPtr=tmpConnPtr;
1654             }
1655           sourceConn+=nbOfNodesIn1Cell;
1656         }
1657       *connIdxPtr=connFillId;
1658     }
1659 }
1660
1661 namespace MEDLoaderNS
1662 {
1663   template<class T>
1664   void releaseMEDFileCoreFrmt(typename std::list<T>& medConnFrmt)
1665   {
1666     for(typename std::list<T>::iterator iter=medConnFrmt.begin();iter!=medConnFrmt.end();iter++)
1667       (*iter).releaseArray();
1668     medConnFrmt.clear();
1669   }
1670 }
1671
1672 /*!
1673  * This method builds a sub set of connectivity for a given type 'type'. \b WARNING connV,connVIndex and familiesV must have same size !
1674  * @param connV input containing connectivity with MEDCoupling format.
1675  * @param connVIndex input containing connectivity index in MEDCoupling format.
1676  * @param familiesV input that may be equal to 0. This specifies an array specifying cell family foreach cell.
1677  * @param type input specifying which cell types will be extracted in conn4MEDFile. 
1678  * @param conn4MEDFile output containing the connectivity directly understandable by MEDFile; conn4MEDFile has to be empty before this method called.
1679  * @param connIndex4MEDFile output containing index connectivity understandable by MEDFile; only used by polygons and polyhedrons (it is face nodal connec).
1680  * @param connIndexRk24MEDFile output containing index of rank 2 understandable by MEDFile; only used by polyhedrons.
1681  * @param fam4MEDFile output containing family number of cells whose type is 'type'. This output is updated only if 'families' is different than 0.
1682  * @return nb of elements extracted.
1683  */
1684 int MEDLoaderNS::buildMEDSubConnectivityOfOneTypeStaticTypes(const std::vector<const DataArrayInt *>& connV, const std::vector<const DataArrayInt *>& connVIndex, const std::vector<const DataArrayInt *>& familiesV,
1685                                                              INTERP_KERNEL::NormalizedCellType type, std::vector<int>& conn4MEDFile, std::vector<int>& fam4MEDFile, std::vector<int>& renumber)
1686 {
1687   int ret=0;
1688   int nbOfMeshes=connV.size();
1689   int renumOffset=0;
1690   for(int i=0;i<nbOfMeshes;i++)
1691     {
1692       const DataArrayInt *conn=connV[i];
1693       const DataArrayInt *connIndex=connVIndex[i];
1694       const DataArrayInt *families=familiesV[i];
1695       int nbOfElem=connIndex->getNbOfElems()-1;
1696       const int *connPtr=conn->getConstPointer();
1697       const int *connIdxPtr=connIndex->getConstPointer();
1698       const int *famPtr=0;
1699       if(families)
1700         famPtr=families->getConstPointer();
1701       for(int ii=0;ii<nbOfElem;ii++)
1702         {
1703           int delta=connIdxPtr[1]-connIdxPtr[0];
1704           if(*connPtr==type)
1705             {
1706               conn4MEDFile.insert(conn4MEDFile.end(),connPtr+1,connPtr+delta);
1707               if(families)
1708                 fam4MEDFile.push_back(famPtr[ii]);
1709               renumber.push_back(ii+1+renumOffset);
1710               ret++;
1711             }
1712           connIdxPtr++;
1713           connPtr+=delta;
1714         }
1715       renumOffset+=nbOfElem;
1716     }
1717   std::transform(conn4MEDFile.begin(),conn4MEDFile.end(),conn4MEDFile.begin(),std::bind2nd(std::plus<int>(),1));
1718   return ret;
1719 }
1720
1721 int MEDLoaderNS::buildMEDSubConnectivityOfOneTypesPolyg(const std::vector<const DataArrayInt *>&connV, const std::vector<const DataArrayInt *>& connVIndex, const std::vector<const DataArrayInt *>& familiesV,
1722                                                         std::vector<int>& conn4MEDFile, std::vector<int>& connIndex4MEDFile, std::vector<int>& fam4MEDFile, std::vector<int>& renumber)
1723 {
1724   int ret=0;
1725   int nbOfMeshes=connV.size();
1726   connIndex4MEDFile.push_back(1);
1727   int renumOffset=0;
1728   for(int i=0;i<nbOfMeshes;i++)
1729     {
1730       const DataArrayInt *conn=connV[i];
1731       const DataArrayInt *connIndex=connVIndex[i];
1732       const DataArrayInt *families=familiesV[i];
1733       int nbOfElem=connIndex->getNbOfElems()-1;
1734       const int *connPtr=conn->getConstPointer();
1735       const int *connIdxPtr=connIndex->getConstPointer();
1736       const int *famPtr=0;
1737       if(families)
1738         famPtr=families->getConstPointer();
1739       for(int ii=0;ii<nbOfElem;ii++)
1740         {
1741           int delta=connIdxPtr[1]-connIdxPtr[0];
1742           if(*connPtr==INTERP_KERNEL::NORM_POLYGON)
1743             {
1744               conn4MEDFile.insert(conn4MEDFile.end(),connPtr+1,connPtr+delta);
1745               connIndex4MEDFile.push_back(connIndex4MEDFile.back()+delta-1);
1746               if(families)
1747                 fam4MEDFile.push_back(famPtr[ii]);
1748               renumber.push_back(ii+1+renumOffset);
1749               ret++;
1750             }
1751           connIdxPtr++;
1752           connPtr+=delta;
1753         }
1754       renumOffset+=nbOfElem;
1755     }
1756   std::transform(conn4MEDFile.begin(),conn4MEDFile.end(),conn4MEDFile.begin(),std::bind2nd(std::plus<int>(),1));
1757   return ret;
1758 }
1759   
1760 int MEDLoaderNS::buildMEDSubConnectivityOfOneTypesPolyh(const std::vector<const DataArrayInt *>& connV, const std::vector<const DataArrayInt *>& connVIndex, const std::vector<const DataArrayInt *>& familiesV,
1761                                                         std::vector<int>& conn4MEDFile, std::vector<int>& connIndex4MEDFile, std::vector<int>& connIndexRk24MEDFile,
1762                                                         std::vector<int>& fam4MEDFile, std::vector<int>& renumber)
1763 {
1764   int ret=0;
1765   int nbOfMeshes=connV.size();
1766   connIndexRk24MEDFile.push_back(1);
1767   connIndex4MEDFile.push_back(1);
1768   int renumOffset=0;
1769   for(int i=0;i<nbOfMeshes;i++)
1770     {
1771       const DataArrayInt *conn=connV[i];
1772       const DataArrayInt *connIndex=connVIndex[i];
1773       const DataArrayInt *families=familiesV[i];
1774       int nbOfElem=connIndex->getNbOfElems()-1;
1775       const int *connPtr=conn->getConstPointer();
1776       const int *connIdxPtr=connIndex->getConstPointer();
1777       const int *famPtr=0;
1778       if(families)
1779         famPtr=families->getConstPointer();
1780       for(int ii=0;ii<nbOfElem;ii++)
1781         {
1782           int delta=connIdxPtr[1]-connIdxPtr[0];
1783           if(*connPtr==INTERP_KERNEL::NORM_POLYHED)
1784             {
1785               int nbOfFacesOfPolyh=std::count(connPtr+1,connPtr+delta,-1)+1;
1786               const int *work=connPtr+1;
1787               while(work!=connPtr+delta)
1788                 {
1789                   const int *end=std::find(work,connPtr+delta,-1);
1790                   conn4MEDFile.insert(conn4MEDFile.end(),work,end);
1791                   connIndex4MEDFile.push_back(connIndex4MEDFile.back()+std::distance(work,end));
1792                   if(end==connPtr+delta)
1793                     work=connPtr+delta;
1794                   else
1795                     work=end+1;
1796                 }
1797               connIndexRk24MEDFile.push_back(connIndexRk24MEDFile.back()+nbOfFacesOfPolyh);
1798               if(families)
1799                 fam4MEDFile.push_back(famPtr[ii]);
1800               renumber.push_back(ii+1+renumOffset);
1801               ret++;
1802             }
1803           connIdxPtr++;
1804           connPtr+=delta;
1805         }
1806       renumOffset+=nbOfElem;
1807     }
1808   std::transform(conn4MEDFile.begin(),conn4MEDFile.end(),conn4MEDFile.begin(),std::bind2nd(std::plus<int>(),1));
1809   return ret;
1810 }
1811   
1812 /*!
1813  * This method builds a sub set of connectivity for a given type 'type'.
1814  * @param conn input containing connectivity with MEDCoupling format.
1815  * @param connIndex input containing connectivity index in MEDCoupling format.
1816  * @param families input containing, if any, the family number of each cells
1817  * @param type input specifying which cell types will be extracted in conn4MEDFile. 
1818  * @param conn4MEDFile output containing the connectivity directly understandable by MEDFile; conn4MEDFile has to be empty before this method called.
1819  * @param connIndex4MEDFile output containing index connectivity understandable by MEDFile; only used by polygons and polyhedrons (it is face nodal connec).
1820  * @param connIndexRk24MEDFile output containing index of rank 2 understandable by MEDFile; only used by polyhedrons.
1821  * @param fam4MEDFile output containing families id of cells whose type is 'type'.
1822  * @return nb of elements extracted.
1823  */
1824 int MEDLoaderNS::buildMEDSubConnectivityOfOneType(const std::vector<const DataArrayInt *>& conn, const std::vector<const DataArrayInt *>& connIndex, const std::vector<const DataArrayInt *>& families,
1825                                                   INTERP_KERNEL::NormalizedCellType type, std::vector<int>& conn4MEDFile,
1826                                                   std::vector<int>& connIndex4MEDFile, std::vector<int>& connIndexRk24MEDFile, std::vector<int>& fam4MEDFile, std::vector<int>& renumber)
1827 {
1828     
1829   const INTERP_KERNEL::CellModel& cellMod=INTERP_KERNEL::CellModel::GetCellModel(type);
1830   if(!cellMod.isDynamic())
1831     return buildMEDSubConnectivityOfOneTypeStaticTypes(conn,connIndex,families,type,conn4MEDFile,fam4MEDFile,renumber);
1832   else
1833     {
1834       if(type==INTERP_KERNEL::NORM_POLYGON)
1835         return buildMEDSubConnectivityOfOneTypesPolyg(conn,connIndex,families,conn4MEDFile,connIndex4MEDFile,fam4MEDFile,renumber);
1836       else
1837         return buildMEDSubConnectivityOfOneTypesPolyh(conn,connIndex,families,conn4MEDFile,connIndex4MEDFile,connIndexRk24MEDFile,fam4MEDFile,renumber);
1838     }
1839 }
1840   
1841 /*!
1842  * @param ids is a in vector containing families ids whose cells have to be kept. If empty all cells are kept.
1843  * @param typesToKeep is a in vector that indicates which types to keep after dimension filtering.
1844  * @param meshDimExtract out parameter that gives the mesh dimension.
1845  * @param cellRenum out parameter that specifies the renumbering (if !=0) of cells in file.
1846  */
1847 MEDCouplingUMesh *MEDLoaderNS::readUMeshFromFileLev1(const char *fileName, const char *meshName, int meshDimRelToMax, const std::vector<int>& ids,
1848                                                      const std::vector<INTERP_KERNEL::NormalizedCellType>& typesToKeep, unsigned& meshDimExtract, int *&cellRenum) throw(INTERP_KERNEL::Exception)
1849 {
1850   if(meshDimRelToMax>0)
1851     throw INTERP_KERNEL::Exception("meshDimRelToMax must be <=0 !");
1852   //Extraction data from MED file.
1853   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDONLY);
1854   std::string trueMeshName;
1855   med_int mid=getIdFromMeshName(fid,meshName,trueMeshName);
1856   DataArrayDouble *coords=0;
1857   std::list<MEDLoader::MEDConnOfOneElemType> conn;
1858   std::string descr;
1859   readUMeshDataInMedFile(fid,mid,coords,conn,descr);
1860   meshDimExtract=MEDLoaderNS::calculateHighestMeshDim<MEDLoader::MEDConnOfOneElemType>(conn);
1861   meshDimExtract=meshDimExtract+meshDimRelToMax;
1862   MEDLoaderNS::keepSpecifiedMeshDim<MEDLoader::MEDConnOfOneElemType>(conn,meshDimExtract);
1863   MEDLoaderNS::keepTypes<MEDLoader::MEDConnOfOneElemType>(conn,typesToKeep);
1864   MEDfileClose(fid);
1865   //Put data in returned data structure.
1866   MEDCouplingUMesh *ret=MEDCouplingUMesh::New();
1867   ret->setName(trueMeshName.c_str());
1868   ret->setDescription(descr.c_str());
1869   ret->setMeshDimension(meshDimExtract);
1870   //
1871   ret->setCoords(coords);
1872   coords->decrRef();
1873   //
1874   DataArrayInt *connArr,*connIndexArr;
1875   tradMEDFileCoreFrmt2MEDCouplingUMesh(conn,ids,connArr,connIndexArr,cellRenum);
1876   ret->setConnectivity(connArr,connIndexArr);
1877   //clean-up
1878   if(connArr)
1879     connArr->decrRef();
1880   if(connIndexArr)
1881     connIndexArr->decrRef();
1882   releaseMEDFileCoreFrmt<MEDLoader::MEDConnOfOneElemType>(conn);
1883   return ret;
1884 }
1885
1886 ParaMEDMEM::MEDCouplingFieldDouble *MEDLoaderNS::readFieldDoubleLev2(const char *fileName, ParaMEDMEM::TypeOfField typeOfOutField, unsigned meshDim, const int *cellRenum, const ParaMEDMEM::MEDCouplingUMesh *mesh,
1887                                                                      const std::vector<std::string>& infos, const char *fieldName, int iteration, int order, double time,
1888                                                                      std::list<MEDLoader::MEDFieldDoublePerCellType>& fieldPerCellType) throw(INTERP_KERNEL::Exception)
1889 {
1890   if(typeOfOutField==ON_CELLS || typeOfOutField==ON_GAUSS_PT || typeOfOutField==ON_GAUSS_NE)
1891     MEDLoaderNS::keepSpecifiedMeshDim<MEDLoader::MEDFieldDoublePerCellType>(fieldPerCellType,meshDim);
1892   if(fieldPerCellType.empty())
1893     {
1894       std::ostringstream oss; oss << "Error on reading file \"" << fileName << "\" meshName=\"" << mesh->getName();
1895       oss << std::endl << "FieldName=\"" << fieldName << "\" (iteration=" << iteration << ",order=" << order << ")" << std::endl;
1896       if(typeOfOutField==ON_CELLS || typeOfOutField==ON_GAUSS_PT || typeOfOutField==ON_GAUSS_NE)
1897         oss << "Request for cell field, maybe it is an ON_NODES field ?";
1898       else
1899         oss << "Request for a node field, maybe it is an ON_CELLS field ?";
1900       throw INTERP_KERNEL::Exception(oss.str().c_str());
1901     }
1902   //for profiles
1903   MEDCouplingAutoRefCountObjectPtr<ParaMEDMEM::MEDCouplingUMesh> newMesh;
1904   std::string mName(mesh->getName());
1905   if(typeOfOutField==ON_NODES)
1906     {
1907       for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=fieldPerCellType.begin();iter!=fieldPerCellType.end();iter++)
1908         {
1909           const std::vector<int>& cellIds=(*iter).getCellIdPerType();
1910           if(!cellIds.empty())
1911             {
1912               std::vector<int> ci(cellIds.size());
1913               std::transform(cellIds.begin(),cellIds.end(),ci.begin(),std::bind2nd(std::plus<int>(),-1));
1914               MEDCouplingAutoRefCountObjectPtr<ParaMEDMEM::MEDCouplingUMesh> mesh2;
1915               MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da,da2;
1916               if((const ParaMEDMEM::MEDCouplingUMesh *)newMesh)
1917                 {
1918                   if((int)ci.size()!=newMesh->getNumberOfNodes())
1919                     {
1920                       da=newMesh->getCellIdsFullyIncludedInNodeIds(&ci[0],&ci[ci.size()]);
1921                       DataArrayInt *tmpp=0;
1922                       mesh2=dynamic_cast<MEDCouplingUMesh *>(newMesh->buildPartAndReduceNodes(da->begin(),da->end(),tmpp)); da2=tmpp;
1923                     }
1924                 }
1925               else
1926                 {
1927                   if((int)ci.size()!=mesh->getNumberOfNodes())
1928                     {
1929                       da=mesh->getCellIdsFullyIncludedInNodeIds(&ci[0],&ci[ci.size()]);
1930                       DataArrayInt *tmpp=0;
1931                       mesh2=dynamic_cast<MEDCouplingUMesh *>(mesh->buildPartAndReduceNodes(da->begin(),da->end(),tmpp)); da2=tmpp;
1932                       //
1933                       int nnodes=mesh2->getNumberOfNodes();
1934                       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da3=DataArrayInt::New();
1935                       const int *da2Ptr=da2->getConstPointer();
1936                       da3->alloc(nnodes,1);
1937                       int *da3Ptr=da3->getPointer();
1938                       for(int i=0;i<(int)ci.size();i++)
1939                         {
1940                           int val=da2Ptr[ci[i]];
1941                           if(val!=-1)
1942                             da3Ptr[val]=i;
1943                         }
1944                       mesh2->renumberNodes(da3->getConstPointer(),nnodes);
1945                     }
1946                   else
1947                     {
1948                       mesh2=mesh->clone(true);
1949                       da=DataArrayInt::New();
1950                       da->alloc((int)ci.size(),1);
1951                       std::copy(ci.begin(),ci.end(),da->getPointer());
1952                       da2=da->invertArrayO2N2N2O(ci.size());
1953                       mesh2->renumberNodes(da2->getConstPointer(),(int)ci.size());
1954                     }
1955                 }
1956               newMesh=mesh2;
1957             }
1958         }
1959     }
1960   else
1961     {
1962       newMesh=const_cast<ParaMEDMEM::MEDCouplingUMesh *>(static_cast<const ParaMEDMEM::MEDCouplingUMesh *>(mesh)); mesh->incrRef();
1963       std::vector<INTERP_KERNEL::NormalizedCellType> types;
1964       for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=fieldPerCellType.begin();iter!=fieldPerCellType.end();iter++)
1965         if(std::find(types.begin(),types.end(),(*iter).getType())==types.end())
1966           types.push_back((*iter).getType());
1967       for(std::vector<INTERP_KERNEL::NormalizedCellType>::const_iterator it=types.begin();it!=types.end();it++)
1968         {
1969           std::vector<int> cids;
1970           for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=fieldPerCellType.begin();iter!=fieldPerCellType.end();iter++)
1971             {
1972               if((*iter).getType()==*it)
1973                 {
1974                   const std::vector<int>& cellIds=(*iter).getCellIdPerType();
1975                   if(!cellIds.empty())
1976                     std::transform(cellIds.begin(),cellIds.end(),std::back_insert_iterator< std::vector<int> >(cids),std::bind2nd(std::plus<int>(),-1));
1977                 }
1978             }
1979           if(!cids.empty())
1980             newMesh=newMesh->keepSpecifiedCells(*it,&cids[0],&cids[0]+cids.size());
1981         }
1982     }
1983   //
1984   ParaMEDMEM::MEDCouplingFieldDouble *ret=ParaMEDMEM::MEDCouplingFieldDouble::New(typeOfOutField,ONE_TIME);
1985   ret->setName(fieldName);
1986   ret->setTime(time,iteration,order);
1987   ParaMEDMEM::DataArrayDouble *arr=buildArrayFromRawData(fieldPerCellType,infos);
1988   ret->setArray(arr);
1989   arr->decrRef();
1990   if((const ParaMEDMEM::MEDCouplingUMesh *)newMesh)
1991     {
1992       newMesh->setName(mName.c_str());//retrieving mesh name to avoid renaming due to mesh restriction in case of profile.
1993       ret->setMesh(newMesh);
1994     }
1995   else
1996     ret->setMesh(mesh);
1997   if(typeOfOutField==ON_GAUSS_PT)
1998     fillGaussDataOnField(fileName,fieldPerCellType,ret);
1999   if(cellRenum)
2000     ret->renumberCellsWithoutMesh(cellRenum,true);
2001   return ret;
2002 }
2003
2004 ParaMEDMEM::MEDCouplingFieldDouble *MEDLoaderNS::readFieldDoubleLev1(const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName, int iteration, int order,
2005                                                                      ParaMEDMEM::TypeOfField typeOfOutField) throw(INTERP_KERNEL::Exception)
2006 {
2007   std::list<MEDLoader::MEDFieldDoublePerCellType> fieldPerCellType;
2008   double time;
2009   std::vector<std::string> infos;
2010   readFieldDoubleDataInMedFile(fileName,meshName,fieldName,iteration,order,typeOfOutField,fieldPerCellType,time,infos);
2011   std::vector<int> familiesToKeep;
2012   std::vector<INTERP_KERNEL::NormalizedCellType> typesToKeep;
2013   if(typeOfOutField==ON_CELLS || typeOfOutField==ON_GAUSS_PT || typeOfOutField==ON_GAUSS_NE)
2014     for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=fieldPerCellType.begin();iter!=fieldPerCellType.end();iter++)
2015       typesToKeep.push_back((*iter).getType());
2016   unsigned meshDim;
2017   int *cellRenum;
2018   if(fieldPerCellType.empty())
2019     {
2020       std::ostringstream oss; oss << "Error on reading file \"" << fileName << "\" meshName=\"" << meshName << "\" meshDimRelToMax=" << meshDimRelToMax;
2021       oss << std::endl << "FieldName=\"" << fieldName << "\" (iteration=" << iteration << ",order=" << order << ")" << std::endl;
2022       if(typeOfOutField==ON_CELLS || typeOfOutField==ON_GAUSS_PT || typeOfOutField==ON_GAUSS_NE)
2023         oss << "Request for cell field, maybe it is a node instead or by changing meshDimRelToMax ?";
2024       else
2025         oss << "Request for a node field, maybe it is a cell field instead ?";
2026       throw INTERP_KERNEL::Exception(oss.str().c_str());
2027       }
2028   MEDCouplingAutoRefCountObjectPtr<ParaMEDMEM::MEDCouplingUMesh> mesh=readUMeshFromFileLev1(fileName,meshName,meshDimRelToMax,familiesToKeep,typesToKeep,meshDim,cellRenum);
2029   ParaMEDMEM::MEDCouplingFieldDouble *ret=readFieldDoubleLev2(fileName,typeOfOutField,meshDim,cellRenum,mesh,infos,fieldName,iteration,order,time,fieldPerCellType);
2030   if(cellRenum)
2031     mesh->renumberCells(cellRenum,true);
2032   //clean-up
2033   delete [] cellRenum;
2034   releaseMEDFileCoreFrmt<MEDLoader::MEDFieldDoublePerCellType>(fieldPerCellType);
2035   return ret;
2036 }
2037
2038 /// @endcond
2039
2040 MEDCouplingUMesh *MEDLoader::ReadUMeshFromFile(const char *fileName, const char *meshName, int meshDimRelToMax) throw(INTERP_KERNEL::Exception)
2041 {
2042   CheckFileForRead(fileName);
2043   std::vector<int> familiesToKeep;
2044   std::vector<INTERP_KERNEL::NormalizedCellType> typesToKeep;
2045   unsigned meshDim;
2046   int *cellRenum;
2047   ParaMEDMEM::MEDCouplingUMesh *ret=MEDLoaderNS::readUMeshFromFileLev1(fileName,meshName,meshDimRelToMax,familiesToKeep,typesToKeep,meshDim,cellRenum);
2048   if(cellRenum)
2049     {
2050       ret->renumberCells(cellRenum,true);
2051       delete [] cellRenum;
2052     }
2053   return ret;
2054 }
2055
2056 ParaMEDMEM::MEDCouplingUMesh *MEDLoader::ReadUMeshFromFile(const char *fileName, int meshDimRelToMax) throw(INTERP_KERNEL::Exception)
2057 {
2058   CheckFileForRead(fileName);
2059   std::vector<int> familiesToKeep;
2060   std::vector<INTERP_KERNEL::NormalizedCellType> typesToKeep;
2061   unsigned meshDim;
2062   int *cellRenum;
2063   ParaMEDMEM::MEDCouplingUMesh *ret=MEDLoaderNS::readUMeshFromFileLev1(fileName,0,meshDimRelToMax,familiesToKeep,typesToKeep,meshDim,cellRenum);
2064   if(cellRenum)
2065     {
2066       ret->renumberCells(cellRenum,true);
2067       delete [] cellRenum;
2068     }
2069   return ret;
2070 }
2071
2072 int MEDLoader::ReadUMeshDimFromFile(const char *fileName, const char *meshName) throw(INTERP_KERNEL::Exception)
2073 {
2074   CheckFileForRead(fileName);
2075   std::vector<int> poss;
2076   return MEDLoaderNS::readUMeshDimFromFile(fileName,meshName,poss);
2077 }
2078
2079 ParaMEDMEM::MEDCouplingUMesh *MEDLoader::ReadUMeshFromFamilies(const char *fileName, const char *meshName, int meshDimRelToMax, const std::vector<std::string>& fams) throw(INTERP_KERNEL::Exception)
2080 {
2081   CheckFileForRead(fileName);
2082   std::vector<int> familiesToKeep=MEDLoaderNS::getIdsFromFamilies(fileName,meshName,fams);
2083   std::vector<INTERP_KERNEL::NormalizedCellType> typesToKeep;
2084   unsigned meshDim;
2085   int *cellRenum;
2086   ParaMEDMEM::MEDCouplingUMesh *ret=MEDLoaderNS::readUMeshFromFileLev1(fileName,meshName,meshDimRelToMax,familiesToKeep,typesToKeep,meshDim,cellRenum);
2087   if(fams.size()==1)
2088     ret->setName(fams.back().c_str());
2089   if(cellRenum)
2090     {
2091       ret->renumberCells(cellRenum,true);
2092       delete [] cellRenum;
2093     }
2094   return ret;
2095 }
2096
2097 ParaMEDMEM::MEDCouplingUMesh *MEDLoader::ReadUMeshFromGroups(const char *fileName, const char *meshName, int meshDimRelToMax, const std::vector<std::string>& grps) throw(INTERP_KERNEL::Exception)
2098 {
2099   CheckFileForRead(fileName);
2100   std::vector<int> familiesToKeep=MEDLoaderNS::getIdsFromGroups(fileName,meshName,grps);
2101   std::vector<INTERP_KERNEL::NormalizedCellType> typesToKeep;
2102   unsigned meshDim;
2103   int *cellRenum;
2104   ParaMEDMEM::MEDCouplingUMesh *ret=MEDLoaderNS::readUMeshFromFileLev1(fileName,meshName,meshDimRelToMax,familiesToKeep,typesToKeep,meshDim,cellRenum);
2105   if(grps.size()==1)
2106     ret->setName(grps.back().c_str());
2107   if(cellRenum)
2108     {
2109       ret->renumberCells(cellRenum,true);
2110       delete [] cellRenum;
2111     }
2112   return ret;
2113 }
2114
2115 ParaMEDMEM::MEDCouplingFieldDouble *MEDLoader::ReadField(ParaMEDMEM::TypeOfField type, const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName, int iteration, int order) throw(INTERP_KERNEL::Exception)
2116 {
2117   CheckFileForRead(fileName);
2118   switch(type)
2119     {
2120     case ON_CELLS:
2121       return ReadFieldCell(fileName,meshName,meshDimRelToMax,fieldName,iteration,order);
2122     case ON_NODES:
2123       return ReadFieldNode(fileName,meshName,meshDimRelToMax,fieldName,iteration,order);
2124     case ON_GAUSS_PT:
2125       return ReadFieldGauss(fileName,meshName,meshDimRelToMax,fieldName,iteration,order);
2126     case ON_GAUSS_NE:
2127       return ReadFieldGaussNE(fileName,meshName,meshDimRelToMax,fieldName,iteration,order);
2128     default:
2129       throw INTERP_KERNEL::Exception("Type of field specified not managed ! manages are ON_NODES, ON_CELLS, ON_GAUSS_PT or ON_GAUSS_NE !");
2130     } 
2131 }
2132
2133 std::vector<ParaMEDMEM::MEDCouplingFieldDouble *> MEDLoader::ReadFieldsOnSameMesh(ParaMEDMEM::TypeOfField type, const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName,
2134                                                                                   const std::vector<std::pair<int,int> >& its) throw(INTERP_KERNEL::Exception)
2135 {
2136   if(its.empty())
2137     return std::vector<ParaMEDMEM::MEDCouplingFieldDouble *>();
2138   CheckFileForRead(fileName);
2139   std::vector<ParaMEDMEM::MEDCouplingFieldDouble *> ret(its.size());
2140   if(its.empty())
2141     return ret;
2142   //Retrieving mesh of rank 0 and field on rank 0 too.
2143   std::list<MEDLoader::MEDFieldDoublePerCellType> fieldPerCellType;
2144   double time;
2145   std::vector<std::string> infos;
2146   MEDLoaderNS::readFieldDoubleDataInMedFile(fileName,meshName,fieldName,its[0].first,its[0].second,type,fieldPerCellType,time,infos);
2147   std::vector<int> familiesToKeep;
2148   std::vector<INTERP_KERNEL::NormalizedCellType> typesToKeep;
2149   if(type==ON_CELLS || type==ON_GAUSS_PT || type==ON_GAUSS_NE)
2150     for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=fieldPerCellType.begin();iter!=fieldPerCellType.end();iter++)
2151       typesToKeep.push_back((*iter).getType());
2152   unsigned meshDim;
2153   int *cellRenum;
2154   MEDCouplingAutoRefCountObjectPtr<ParaMEDMEM::MEDCouplingUMesh> m1=MEDLoaderNS::readUMeshFromFileLev1(fileName,meshName,meshDimRelToMax,familiesToKeep,typesToKeep,meshDim,cellRenum);
2155   ret[0]=MEDLoaderNS::readFieldDoubleLev2(fileName,type,meshDim,cellRenum,m1,infos,fieldName,its[0].first,its[0].second,time,fieldPerCellType);
2156   if(cellRenum)
2157     m1->renumberCells(cellRenum,true);
2158   MEDLoaderNS::releaseMEDFileCoreFrmt<MEDLoader::MEDFieldDoublePerCellType>(fieldPerCellType);
2159   //
2160   for(int itId=1;itId<(int)its.size();itId++)
2161     {
2162       std::list<MEDLoader::MEDFieldDoublePerCellType> fieldPerCellType2;
2163       double timmee;
2164       std::vector<std::string> infoss;
2165       MEDLoaderNS::readFieldDoubleDataInMedFile(fileName,meshName,fieldName,its[itId].first,its[itId].second,type,fieldPerCellType2,timmee,infoss);
2166       ret[itId]=MEDLoaderNS::readFieldDoubleLev2(fileName,type,meshDim,cellRenum,m1,infoss,fieldName,its[itId].first,its[itId].second,timmee,fieldPerCellType2);
2167       //clean-up
2168       MEDLoaderNS::releaseMEDFileCoreFrmt<MEDLoader::MEDFieldDoublePerCellType>(fieldPerCellType2);
2169     }
2170   delete [] cellRenum;
2171   return ret;
2172 }
2173
2174 std::vector<ParaMEDMEM::MEDCouplingFieldDouble *> MEDLoader::ReadFieldsCellOnSameMesh(const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName,
2175                                                                                             const std::vector<std::pair<int,int> >& its) throw(INTERP_KERNEL::Exception)
2176 {
2177   return ReadFieldsOnSameMesh(ON_CELLS,fileName,meshName,meshDimRelToMax,fieldName,its);
2178 }
2179
2180 std::vector<ParaMEDMEM::MEDCouplingFieldDouble *> MEDLoader::ReadFieldsNodeOnSameMesh(const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName,
2181                                                                                       const std::vector<std::pair<int,int> >& its) throw(INTERP_KERNEL::Exception)
2182 {
2183   return ReadFieldsOnSameMesh(ON_NODES,fileName,meshName,meshDimRelToMax,fieldName,its);
2184 }
2185
2186 std::vector<ParaMEDMEM::MEDCouplingFieldDouble *> MEDLoader::ReadFieldsGaussOnSameMesh(const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName,
2187                                                                                        const std::vector<std::pair<int,int> >& its) throw(INTERP_KERNEL::Exception)
2188 {
2189   return ReadFieldsOnSameMesh(ON_GAUSS_PT,fileName,meshName,meshDimRelToMax,fieldName,its);
2190 }
2191
2192 std::vector<ParaMEDMEM::MEDCouplingFieldDouble *> MEDLoader::ReadFieldsGaussNEOnSameMesh(const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName,
2193                                                                                          const std::vector<std::pair<int,int> >& its) throw(INTERP_KERNEL::Exception)
2194 {
2195   return ReadFieldsOnSameMesh(ON_GAUSS_NE,fileName,meshName,meshDimRelToMax,fieldName,its);
2196 }
2197
2198 ParaMEDMEM::MEDCouplingFieldDouble *MEDLoader::ReadFieldCell(const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName, int iteration, int order) throw(INTERP_KERNEL::Exception)
2199 {
2200   return MEDLoaderNS::readFieldDoubleLev1(fileName,meshName,meshDimRelToMax,fieldName,iteration,order,ON_CELLS);
2201 }
2202
2203 ParaMEDMEM::MEDCouplingFieldDouble *MEDLoader::ReadFieldNode(const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName, int iteration, int order) throw(INTERP_KERNEL::Exception)
2204 {
2205   return MEDLoaderNS::readFieldDoubleLev1(fileName,meshName,meshDimRelToMax,fieldName,iteration,order,ON_NODES);
2206 }
2207
2208 ParaMEDMEM::MEDCouplingFieldDouble *MEDLoader::ReadFieldGauss(const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName, int iteration, int order) throw(INTERP_KERNEL::Exception)
2209 {
2210   return MEDLoaderNS::readFieldDoubleLev1(fileName,meshName,meshDimRelToMax,fieldName,iteration,order,ON_GAUSS_PT);
2211 }
2212
2213 ParaMEDMEM::MEDCouplingFieldDouble *MEDLoader::ReadFieldGaussNE(const char *fileName, const char *meshName, int meshDimRelToMax, const char *fieldName, int iteration, int order) throw(INTERP_KERNEL::Exception)
2214 {
2215   return MEDLoaderNS::readFieldDoubleLev1(fileName,meshName,meshDimRelToMax,fieldName,iteration,order,ON_GAUSS_NE);
2216 }
2217
2218 /*!
2219  * @param families input parameter that specifies the field on int on each cells of 'mesh'.
2220  * @param isRenumbering output parameter that specifies if a renumbering of mesh has been needed.
2221  */
2222 void MEDLoaderNS::writeUMeshesDirectly(const char *fileName, const std::vector<const ParaMEDMEM::MEDCouplingUMesh *>& mesh, const std::vector<const DataArrayInt *>& families, bool forceFromScratch, bool &isRenumbering)
2223 {
2224   med_idt fid=MEDfileOpen(fileName,forceFromScratch?MED_ACC_CREAT:MED_ACC_RDWR);
2225   std::string meshName(mesh[0]->getName());
2226   if(meshName=="")
2227     {
2228       MEDfileClose(fid);
2229       throw INTERP_KERNEL::Exception("MEDCouplingMesh must have a not null name !");
2230     }
2231   isRenumbering=false;
2232   bool isFamilies=true;
2233   std::vector<const DataArrayInt *> conn;
2234   std::vector<const DataArrayInt *> connIndex;
2235   std::set<INTERP_KERNEL::NormalizedCellType> allTypes;
2236   for(std::vector<const ParaMEDMEM::MEDCouplingUMesh *>::const_iterator iter=mesh.begin();iter!=mesh.end();iter++)
2237     {
2238       isRenumbering|=!(*iter)->checkConsecutiveCellTypesAndOrder(typmai2,typmai2+MED_N_CELL_FIXED_GEO);
2239       isFamilies&=(families[std::distance(mesh.begin(),iter)]!=0);
2240       conn.push_back((*iter)->getNodalConnectivity());
2241       connIndex.push_back((*iter)->getNodalConnectivityIndex());
2242       const std::set<INTERP_KERNEL::NormalizedCellType>& curTypes=(*iter)->getAllTypes();
2243       allTypes.insert(curTypes.begin(),curTypes.end());
2244     }
2245   INTERP_KERNEL::AutoPtr<char> maa=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2246   INTERP_KERNEL::AutoPtr<char> desc=MEDLoaderBase::buildEmptyString(MED_COMMENT_SIZE);
2247   MEDLoaderBase::safeStrCpy(meshName.c_str(),MED_NAME_SIZE,maa,MEDLoader::_TOO_LONG_STR);
2248   MEDLoaderBase::safeStrCpy(mesh[0]->getDescription(),MED_COMMENT_SIZE,desc,MEDLoader::_TOO_LONG_STR);
2249   const int spaceDim=mesh[0]->getSpaceDimension();
2250   const int meshDim=mesh[0]->getMeshDimension();
2251   const DataArrayDouble *arr=mesh[0]->getCoords();
2252   INTERP_KERNEL::AutoPtr<char> comp=MEDLoaderBase::buildEmptyString(spaceDim*MED_SNAME_SIZE);
2253   INTERP_KERNEL::AutoPtr<char> unit=MEDLoaderBase::buildEmptyString(spaceDim*MED_SNAME_SIZE);
2254   for(int i=0;i<spaceDim;i++)
2255     {
2256       std::string info=arr->getInfoOnComponent(i);
2257       std::string c,u;
2258       MEDLoaderBase::splitIntoNameAndUnit(info,c,u);
2259       MEDLoaderBase::safeStrCpy2(c.c_str(),MED_SNAME_SIZE-1,comp+i*MED_SNAME_SIZE,MEDLoader::_TOO_LONG_STR);//MED_TAILLE_PNOM-1 to avoid to write '\0' on next compo
2260       MEDLoaderBase::safeStrCpy2(u.c_str(),MED_SNAME_SIZE-1,unit+i*MED_SNAME_SIZE,MEDLoader::_TOO_LONG_STR);//MED_TAILLE_PNOM-1 to avoid to write '\0' on next compo
2261     }
2262   MEDmeshCr(fid,maa,spaceDim,meshDim,MED_UNSTRUCTURED_MESH,desc,"",MED_SORT_DTIT,MED_CARTESIAN,comp,unit);
2263   for(std::vector<const ParaMEDMEM::MEDCouplingUMesh *>::const_iterator iter=mesh.begin();iter!=mesh.end();iter++)
2264     {
2265       for(int i=0;i<MED_N_CELL_FIXED_GEO;i++)
2266         {
2267           med_geometry_type curMedType=typmai[i];
2268           INTERP_KERNEL::NormalizedCellType curType=typmai2[i];
2269           if(allTypes.find(curType)!=allTypes.end())
2270             {
2271               std::vector<int> medConn;
2272               std::vector<int> medConnIndex;
2273               std::vector<int> medConnIndex2;
2274               std::vector<int> fam;
2275               std::vector<int> renumber;
2276               int nbOfElt=MEDLoaderNS::buildMEDSubConnectivityOfOneType(conn,connIndex,families,curType,medConn,medConnIndex,medConnIndex2,fam,renumber);
2277               if(curMedType!=MED_POLYGON && curMedType!=MED_POLYHEDRON)
2278                 MEDmeshElementConnectivityWr(fid,maa,-1,-1,0.,MED_CELL,curMedType,MED_NODAL,MED_FULL_INTERLACE,nbOfElt,&medConn[0]);
2279               else
2280                 {
2281                   if(curMedType==MED_POLYGON)
2282                     MEDmeshPolygonWr(fid,maa,-1,-1,0.,MED_CELL,MED_NODAL,medConnIndex.size(),&medConnIndex[0],&medConn[0]);
2283                   if(curMedType==MED_POLYHEDRON)
2284                     {
2285                       MEDmeshPolyhedronWr(fid,maa,-1,-1,0.,MED_CELL,MED_NODAL,medConnIndex2.size(),&medConnIndex2[0],medConnIndex.size(),&medConnIndex[0],
2286                                          &medConn[0]);
2287                     }
2288                 }
2289               if(isFamilies)
2290                 MEDmeshEntityFamilyNumberWr(fid,maa,-1,-1,MED_CELL,curMedType,nbOfElt,&fam[0]);
2291               if(isRenumbering)
2292                 MEDmeshEntityNumberWr(fid,maa,-1,-1,MED_CELL,curMedType,nbOfElt,&renumber[0]);
2293             }
2294         }
2295     }
2296   char familyName[MED_NAME_SIZE+1];
2297   std::fill(familyName,familyName+MED_NAME_SIZE+1,'\0');
2298   const char DftFamilyName[]="DftFamily";
2299   std::copy(DftFamilyName,DftFamilyName+sizeof(DftFamilyName),familyName);
2300   MEDfamilyCr(fid,maa,familyName,0,0,0);
2301   
2302   MEDmeshNodeCoordinateWr(fid,maa,-1,-1,0.,MED_FULL_INTERLACE,mesh[0]->getNumberOfNodes(),arr->getConstPointer());
2303   MEDfileClose(fid);
2304 }
2305
2306 /*!
2307  * In this method meshes are assumed to shared the same coords.
2308  * This method makes the assumption that 'meshes' is not empty, no check on that is done (responsability of the caller)
2309  */
2310 void MEDLoaderNS::writeUMeshesPartitionDirectly(const char *fileName, const char *meshName, const std::vector<const ParaMEDMEM::MEDCouplingUMesh *>& meshes, bool forceFromScratch)
2311 {
2312   std::string meshNameCpp(meshName);
2313   INTERP_KERNEL::AutoPtr<char> maa=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2314   MEDLoaderBase::safeStrCpy(meshName,MED_NAME_SIZE,maa,MEDLoader::_TOO_LONG_STR);
2315   if(meshNameCpp=="")
2316     throw INTERP_KERNEL::Exception("writeUMeshesPartitionDirectly : Invalid meshName : Must be different from \"\" !");
2317   std::vector< DataArrayInt * > corr;
2318   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m=ParaMEDMEM::MEDCouplingUMesh::FuseUMeshesOnSameCoords(meshes,0,corr);
2319   m->setName(meshName);
2320   std::vector< std::vector<int> > fidsOfGroups;
2321   std::vector< const DataArrayInt * > corr2(corr.begin(),corr.end());
2322   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arr2=DataArrayInt::MakePartition(corr2,m->getNumberOfCells(),fidsOfGroups);
2323   for(std::vector< DataArrayInt * >::iterator it=corr.begin();it!=corr.end();it++)
2324     (*it)->decrRef();
2325   bool isRenumbering;
2326   std::vector<const MEDCouplingUMesh *> mv(1); mv[0]=m;
2327   std::vector<const DataArrayInt *> famv(1); famv[0]=arr2;
2328   writeUMeshesDirectly(fileName,mv,famv,forceFromScratch,isRenumbering);
2329   // families creation
2330   std::set<int> familyIds;
2331   for(std::vector< std::vector<int> >::const_iterator it1=fidsOfGroups.begin();it1!=fidsOfGroups.end();it1++)
2332     for(std::vector<int>::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++)
2333       familyIds.insert(*it2);
2334   std::vector< std::vector<int> > gidsOfFamilies(familyIds.size());
2335   int fid=0;
2336   for(std::set<int>::const_iterator it=familyIds.begin();it!=familyIds.end();it++,fid++)
2337     {
2338       int gid=0;
2339       for(std::vector< std::vector<int> >::const_iterator it1=fidsOfGroups.begin();it1!=fidsOfGroups.end();it1++,gid++)
2340         for(std::vector<int>::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++)
2341           if(*it2==*it)
2342             gidsOfFamilies[fid].push_back(gid);
2343     }
2344   fid=0;
2345   med_idt fid2=MEDfileOpen(fileName,MED_ACC_RDWR);
2346   for(std::set<int>::const_iterator it=familyIds.begin();it!=familyIds.end();it++,fid++)
2347     {
2348       int ngro=gidsOfFamilies[fid].size();
2349       INTERP_KERNEL::AutoPtr<char> groName=MEDLoaderBase::buildEmptyString(MED_LNAME_SIZE*ngro);
2350       for(int i=0;i<ngro;i++)
2351         MEDLoaderBase::safeStrCpy2(meshes[gidsOfFamilies[fid][i]]->getName(),MED_LNAME_SIZE-1,groName+i*MED_LNAME_SIZE,MEDLoader::_TOO_LONG_STR);//MED_LNAME_SIZE-1 to avoid to write '\0' on next compo
2352       std::ostringstream oss; oss << "Family_" << *it;
2353       INTERP_KERNEL::AutoPtr<char> famName=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2354       MEDLoaderBase::safeStrCpy(oss.str().c_str(),MED_NAME_SIZE,famName,MEDLoader::_TOO_LONG_STR);
2355       MEDfamilyCr(fid2,maa,famName,*it,ngro,groName);
2356     }
2357   MEDfileClose(fid2);
2358 }
2359
2360 /*!
2361  * This method makes the assumption that f->getMesh() nodes are fully included in already written mesh in 'fileName'.
2362  * @param thisMeshNodeIds points to a tab of size f->getMesh()->getNumberOfNodes() that says for a node i in f->getMesh() that its id is thisMeshNodeIds[i] is already written mesh.
2363  */
2364 void MEDLoaderNS::appendNodeProfileField(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, const int *thisMeshNodeIds)
2365 {
2366   med_int numdt,numo;
2367   med_float dt;
2368   INTERP_KERNEL::AutoPtr<char> nommaa=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2369   MEDLoaderBase::safeStrCpy(f->getMesh()->getName(),MED_NAME_SIZE,nommaa,MEDLoader::_TOO_LONG_STR);
2370   med_idt fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
2371   int nbOfNodes=f->getMesh()->getNumberOfNodes();
2372   const double *pt=f->getArray()->getConstPointer();
2373   INTERP_KERNEL::AutoPtr<int> profile=new int[nbOfNodes];
2374   std::ostringstream oss; oss << "Pfln" << f->getName();
2375   INTERP_KERNEL::AutoPtr<char> profileName=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2376   MEDLoaderBase::safeStrCpy(oss.str().c_str(),MED_NAME_SIZE,profileName,MEDLoader::_TOO_LONG_STR);
2377   std::transform(thisMeshNodeIds,thisMeshNodeIds+nbOfNodes,(int *)profile,std::bind2nd(std::plus<int>(),1));
2378   MEDprofileWr(fid,profileName,nbOfNodes,profile);
2379   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);
2380   MEDfileClose(fid);
2381 }
2382
2383 /*!
2384  * This method makes the assumption that f->getMesh() cells are fully included in already written mesh in 'fileName'.
2385  * @param thisMeshCellIdsPerType points to a tab of size f->getMesh()->getNumberOfCells() that says for a cell i in f->getMesh() that its id is thisMeshCellIds[i] of corresponding type is already written mesh.
2386  */
2387 void MEDLoaderNS::appendCellProfileField(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, const int *thisMeshCellIdsPerType)
2388 {
2389   med_int numdt,numo;
2390   med_float dt;
2391   int nbComp=f->getNumberOfComponents();
2392   med_idt fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
2393   std::list<MEDLoader::MEDFieldDoublePerCellType> split;
2394   prepareCellFieldDoubleForWriting(f,thisMeshCellIdsPerType,split);
2395   const double *pt=f->getArray()->getConstPointer();
2396   int number=0;
2397   for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=split.begin();iter!=split.end();iter++)
2398     {
2399       INTERP_KERNEL::AutoPtr<char> nommaa=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2400       MEDLoaderBase::safeStrCpy(f->getMesh()->getName(),MED_NAME_SIZE,nommaa,MEDLoader::_TOO_LONG_STR);
2401       INTERP_KERNEL::AutoPtr<char> profileName=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2402       std::ostringstream oss; oss << "Pfl" << f->getName() << "_" << number++;
2403       MEDLoaderBase::safeStrCpy(oss.str().c_str(),MED_NAME_SIZE,profileName,MEDLoader::_TOO_LONG_STR);
2404       const std::vector<int>& ids=(*iter).getCellIdPerType();
2405       INTERP_KERNEL::AutoPtr<int> profile=new int [ids.size()];
2406       std::transform(ids.begin(),ids.end(),(int *)profile,std::bind2nd(std::plus<int>(),1));
2407       MEDprofileWr(fid,profileName,ids.size(),profile);
2408       MEDfieldValueWithProfileWr(fid,f->getName(),numdt,numo,dt,MED_CELL,typmai3[(int)(*iter).getType()],MED_COMPACT_PFLMODE,profileName,
2409                                  MED_NO_LOCALIZATION,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,(*iter).getNbOfTuple(),(const unsigned char*)pt);
2410       pt+=(*iter).getNbOfTuple()*nbComp;
2411     }
2412   MEDfileClose(fid);
2413 }
2414
2415 void MEDLoaderNS::appendNodeElementProfileField(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, const int *thisMeshCellIdsPerType)
2416 {
2417   med_int numdt,numo;
2418   med_float dt;
2419   int nbComp=f->getNumberOfComponents();
2420   med_idt fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
2421   std::list<MEDLoader::MEDFieldDoublePerCellType> split;
2422   prepareCellFieldDoubleForWriting(f,thisMeshCellIdsPerType,split);
2423   const double *pt=f->getArray()->getConstPointer();
2424   int number=0;
2425   for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=split.begin();iter!=split.end();iter++)
2426     {
2427       INTERP_KERNEL::AutoPtr<char> nommaa=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2428       MEDLoaderBase::safeStrCpy(f->getMesh()->getName(),MED_NAME_SIZE,nommaa,MEDLoader::_TOO_LONG_STR);
2429       INTERP_KERNEL::AutoPtr<char> profileName=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2430       std::ostringstream oss; oss << "Pfl" << f->getName() << "_" << number++;
2431       MEDLoaderBase::safeStrCpy(oss.str().c_str(),MED_NAME_SIZE,profileName,MEDLoader::_TOO_LONG_STR);
2432       const std::vector<int>& ids=(*iter).getCellIdPerType();
2433       INTERP_KERNEL::AutoPtr<int> profile=new int [ids.size()];
2434       std::transform(ids.begin(),ids.end(),(int *)profile,std::bind2nd(std::plus<int>(),1));
2435       MEDprofileWr(fid,profileName,ids.size(),profile);
2436       int nbPtPerCell=(int)INTERP_KERNEL::CellModel::GetCellModel((*iter).getType()).getNumberOfNodes();
2437       int nbOfEntity=f->getMesh()->getNumberOfCellsWithType((*iter).getType());
2438       int nbOfValues=nbPtPerCell*nbOfEntity;
2439       MEDfieldValueWithProfileWr(fid,f->getName(),numdt,numo,dt,MED_NODE_ELEMENT,typmai3[(int)(*iter).getType()],
2440                                  MED_COMPACT_PFLMODE,profileName,
2441                                  MED_NO_LOCALIZATION,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,
2442                                  nbOfEntity,(const unsigned char*)pt);
2443       pt+=nbOfValues*nbComp;
2444     }
2445   MEDfileClose(fid);
2446 }
2447
2448 /*!
2449  * This method performs the classical job for fields before any values setting.
2450  */
2451 med_idt MEDLoaderNS::appendFieldSimpleAtt(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, med_int& numdt, med_int& numo, med_float& dt)
2452 {
2453   std::string fieldName(f->getName());
2454   if(fieldName.empty())
2455     throw INTERP_KERNEL::Exception("MEDLoaderNS::appendFieldSimpleAtt : Trying to store a field with no name ! MED file format requires a NON EMPTY field name !");
2456   med_idt fid=MEDfileOpen(fileName,MED_ACC_RDWR);
2457   int nbComp=f->getNumberOfComponents();
2458   INTERP_KERNEL::AutoPtr<char> comp=MEDLoaderBase::buildEmptyString(nbComp*MED_SNAME_SIZE);
2459   INTERP_KERNEL::AutoPtr<char> unit=MEDLoaderBase::buildEmptyString(nbComp*MED_SNAME_SIZE);
2460   for(int i=0;i<nbComp;i++)
2461     {
2462       std::string info=f->getArray()->getInfoOnComponent(i);
2463       std::string c,u;
2464       MEDLoaderBase::splitIntoNameAndUnit(info,c,u);
2465       MEDLoaderBase::safeStrCpy2(c.c_str(),MED_SNAME_SIZE-1,comp+i*MED_SNAME_SIZE,MEDLoader::_TOO_LONG_STR);
2466       MEDLoaderBase::safeStrCpy2(u.c_str(),MED_SNAME_SIZE-1,unit+i*MED_SNAME_SIZE,MEDLoader::_TOO_LONG_STR);
2467     }
2468   INTERP_KERNEL::AutoPtr<char> dt_unit=MEDLoaderBase::buildEmptyString(MED_SNAME_SIZE);
2469   INTERP_KERNEL::AutoPtr<char> maaname=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2470   INTERP_KERNEL::AutoPtr<char> fname=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2471   MEDLoaderBase::safeStrCpy(f->getName(),MED_NAME_SIZE,fname,MEDLoader::_TOO_LONG_STR);
2472   MEDLoaderBase::safeStrCpy(f->getMesh()->getName(),MED_NAME_SIZE,maaname,MEDLoader::_TOO_LONG_STR);
2473   MEDLoaderBase::safeStrCpy(f->getTimeUnit(),MED_SNAME_SIZE,dt_unit,MEDLoader::_TOO_LONG_STR);
2474   MEDfieldCr(fid,fname,MED_FLOAT64,nbComp,comp,unit,dt_unit,maaname);
2475   ParaMEDMEM::TypeOfTimeDiscretization td=f->getTimeDiscretization();
2476   if(td==ParaMEDMEM::NO_TIME)
2477     {
2478       numdt=MED_NO_DT; numo=MED_NO_IT; dt=0.0;
2479     }
2480   else if(td==ParaMEDMEM::ONE_TIME)
2481     {
2482       int tmp1,tmp2;
2483       double tmp0=f->getTime(tmp1,tmp2);
2484       numdt=(med_int)tmp1; numo=(med_int)tmp2;
2485       dt=(med_float)tmp0;
2486     }
2487   return fid;
2488 }
2489
2490 void MEDLoaderNS::appendFieldDirectly(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f2)
2491 {
2492   med_int numdt,numo;
2493   med_float dt;
2494   //renumbering
2495   const ParaMEDMEM::MEDCouplingFieldDouble *f=f2;
2496   const MEDCouplingMesh *mesh=f->getMesh();
2497   const MEDCouplingUMesh *meshC=dynamic_cast<const MEDCouplingUMesh *>(mesh);
2498   if(!meshC)
2499     throw INTERP_KERNEL::Exception("Not implemented yet for not unstructured mesh !");
2500   bool renum=!meshC->checkConsecutiveCellTypesAndOrder(typmai2,typmai2+MED_N_CELL_FIXED_GEO);
2501   if(renum)
2502     {
2503       ParaMEDMEM::MEDCouplingFieldDouble *f3=f2->clone(true);
2504       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da=meshC->getRenumArrForConsecutiveCellTypesSpec(typmai2,typmai2+MED_N_CELL_FIXED_GEO);
2505       f3->renumberCells(da->getConstPointer(),false);
2506       f=f3;
2507     }
2508   //end renumbering
2509   int nbComp=f->getNumberOfComponents();
2510   med_idt fid=appendFieldSimpleAtt(fileName,f,numdt,numo,dt);
2511   const double *pt=f->getArray()->getConstPointer();
2512   INTERP_KERNEL::AutoPtr<char> nommaa=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2513   MEDLoaderBase::safeStrCpy(f->getMesh()->getName(),MED_NAME_SIZE,nommaa,MEDLoader::_TOO_LONG_STR);
2514   switch(f->getTypeOfField())
2515     {
2516     case ParaMEDMEM::ON_CELLS:
2517       {
2518         std::list<MEDLoader::MEDFieldDoublePerCellType> split;
2519         prepareCellFieldDoubleForWriting(f,0,split);
2520         for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=split.begin();iter!=split.end();iter++)
2521           {
2522             MEDfieldValueWithProfileWr(fid,f->getName(),numdt,numo,dt,MED_CELL,typmai3[(int)(*iter).getType()],MED_COMPACT_PFLMODE,
2523                                        MED_ALLENTITIES_PROFILE,MED_NO_LOCALIZATION,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,(*iter).getNbOfTuple(),(const unsigned char*)pt);
2524             pt+=(*iter).getNbOfTuple()*nbComp;
2525           }
2526         break;
2527       }
2528     case ParaMEDMEM::ON_NODES:
2529       {
2530         int nbOfTuples=f->getArray()->getNumberOfTuples();
2531         MEDfieldValueWithProfileWr(fid,f->getName(),numdt,numo,dt,MED_NODE,MED_NONE,MED_COMPACT_PFLMODE,
2532                                    MED_ALLENTITIES_PROFILE,MED_NO_LOCALIZATION,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,nbOfTuples,(const unsigned char*)pt);
2533         break;
2534       }
2535     case ParaMEDMEM::ON_GAUSS_PT:
2536       {
2537         INTERP_KERNEL::AutoPtr<char> profileName=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2538         std::list<MEDLoader::MEDFieldDoublePerCellType> split;
2539         prepareCellFieldDoubleForWriting(f,0,split);
2540         int idGp=0,offset=0,offset2=0;
2541         const double *pt2=0;
2542         INTERP_KERNEL::NormalizedCellType prevType=INTERP_KERNEL::NORM_ERROR;
2543         for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=split.begin();iter!=split.end();iter++)
2544           {
2545             if((*iter).getType()!=prevType)
2546               {
2547                 offset=offset2;
2548                 prevType=(*iter).getType();
2549               }
2550             INTERP_KERNEL::AutoPtr<char> nomGauss=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2551             std::ostringstream oss; oss << "GP_" << f->getName() << idGp++;
2552             MEDLoaderBase::safeStrCpy(oss.str().c_str(),MED_NAME_SIZE,nomGauss,MEDLoader::_TOO_LONG_STR);
2553             std::ostringstream ossPfl;
2554             int id=-1,nbOfEntity=-1;
2555             MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> arrTmp;
2556             if((*iter).getCellIdPerType().empty())
2557               {
2558                 id=f->getGaussLocalizationIdOfOneType((*iter).getType());
2559                 nbOfEntity=f->getMesh()->getNumberOfCellsWithType((*iter).getType());
2560               }
2561             else
2562               {
2563                 id=f->getGaussLocalizationIdOfOneCell((*iter).getCellIdPerType()[0]+offset);
2564                 nbOfEntity=(int)(*iter).getCellIdPerType().size();
2565                 ossPfl << "Pfl" << f->getName() << "_" << id;
2566                 MEDLoaderBase::safeStrCpy(ossPfl.str().c_str(),MED_NAME_SIZE,profileName,MEDLoader::_TOO_LONG_STR);
2567                 INTERP_KERNEL::AutoPtr<int> profile=new int[(*iter).getCellIdPerType().size()];
2568                 std::transform((*iter).getCellIdPerType().begin(),(*iter).getCellIdPerType().end(),(int *)profile,std::bind2nd(std::plus<int>(),1));
2569                 MEDprofileWr(fid,profileName,(*iter).getCellIdPerType().size(),profile);
2570                 //
2571                 MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da3=DataArrayInt::New();
2572                 da3->useArray(const_cast<int *>(&((*iter).getCellIdPerType()[0])),false,CPP_DEALLOC,(int)(*iter).getCellIdPerType().size(),1);
2573                 MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da4=da3->deepCpy();
2574                 da4->applyLin(1,offset);
2575                 //
2576                 const MEDCouplingFieldDiscretizationGauss *disc2=static_cast<const MEDCouplingFieldDiscretizationGauss *>(f->getDiscretization());
2577                 MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arr=disc2->getOffsetArr(f->getMesh());
2578                 MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp=DataArrayInt::New();
2579                 int trueNval=0;
2580                 for(const int *pt3=da4->begin();pt3!=da4->end();pt3++)
2581                   trueNval+=arr->getIJ(*pt3+1,0)-arr->getIJ(*pt3,0);
2582                 tmp->alloc(trueNval,1);
2583                 int *tmpPtr=tmp->getPointer();
2584                 for(const int *pt3=da4->begin();pt3!=da4->end();pt3++)
2585                   for(int j=arr->getIJ(*pt3,0);j<arr->getIJ(*pt3+1,0);j++)
2586                     *tmpPtr++=j;
2587                 arrTmp=f->getArray()->selectByTupleId(tmp->begin(),tmp->end());
2588                 pt2=arrTmp->getConstPointer();
2589               }
2590             const MEDCouplingGaussLocalization& gl=f->getGaussLocalization(id);
2591             MEDlocalizationWr(fid,nomGauss,typmai3[(int)(*iter).getType()],mesh->getMeshDimension(),&gl.getRefCoords()[0],MED_FULL_INTERLACE,
2592                               gl.getNumberOfGaussPt(),&gl.getGaussCoords()[0],&gl.getWeights()[0],MED_NO_INTERPOLATION, MED_NO_MESH_SUPPORT);
2593             int nbOfValues=gl.getNumberOfGaussPt()*nbOfEntity;
2594             INTERP_KERNEL::AutoPtr<char> fieldname=MEDLoaderBase::buildEmptyString(MED_NAME_SIZE);
2595             MEDLoaderBase::safeStrCpy(f->getName(),MED_NAME_SIZE,fieldname,MEDLoader::_TOO_LONG_STR);
2596             if((*iter).getCellIdPerType().empty())
2597               {
2598                 MEDfieldValueWithProfileWr(fid,fieldname,numdt,numo,dt,MED_CELL,typmai3[(int)(*iter).getType()],MED_COMPACT_PFLMODE,
2599                                            MED_ALLENTITIES_PROFILE,nomGauss,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,nbOfEntity,(const unsigned char*)pt);
2600               }
2601             else
2602               MEDfieldValueWithProfileWr(fid,fieldname,numdt,numo,dt,MED_CELL,typmai3[(int)(*iter).getType()],MED_COMPACT_PFLMODE,
2603                                          profileName,nomGauss,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,nbOfEntity,(const unsigned char*)pt2);
2604             pt+=nbOfValues*nbComp;
2605             offset2+=(*iter).getNbOfGeoElt();
2606           }
2607         break;
2608       }
2609     case ParaMEDMEM::ON_GAUSS_NE:
2610       {
2611         std::list<MEDLoader::MEDFieldDoublePerCellType> split;
2612         prepareCellFieldDoubleForWriting(f,0,split);
2613         for(std::list<MEDLoader::MEDFieldDoublePerCellType>::const_iterator iter=split.begin();iter!=split.end();iter++)
2614           {
2615             int nbPtPerCell=(int)INTERP_KERNEL::CellModel::GetCellModel((*iter).getType()).getNumberOfNodes();
2616             int nbOfEntity=f->getMesh()->getNumberOfCellsWithType((*iter).getType());
2617             int nbOfValues=nbPtPerCell*nbOfEntity;
2618             MEDfieldValueWithProfileWr(fid,f->getName(),numdt,numo,dt,MED_NODE_ELEMENT,typmai3[(int)(*iter).getType()],MED_COMPACT_PFLMODE,
2619                                        MED_ALLENTITIES_PROFILE,MED_NO_LOCALIZATION,MED_FULL_INTERLACE,MED_ALL_CONSTITUENT,nbOfEntity,(const unsigned char*)pt);
2620             pt+=nbOfValues*nbComp;
2621           }
2622         break;
2623       }
2624     default:
2625       throw INTERP_KERNEL::Exception("Not managed this type of FIELD !");
2626     }
2627   MEDfileClose(fid);
2628   if(renum)
2629     f->decrRef();
2630 }
2631
2632 /*!
2633  * This method splits field 'f' into types to be ready for writing.
2634  * @param cellIdsPerType this parameter can be 0 if not in profile mode. If it is != 0 this array is of size f->getMesh()->getNumberOfCells().
2635  */
2636 void MEDLoaderNS::prepareCellFieldDoubleForWriting(const ParaMEDMEM::MEDCouplingFieldDouble *f, const int *cellIdsPerType, std::list<MEDLoader::MEDFieldDoublePerCellType>& split)
2637 {
2638   int nbComp=f->getNumberOfComponents();
2639   const MEDCouplingMesh *mesh=f->getMesh();
2640   const MEDCouplingUMesh *meshC=dynamic_cast<const MEDCouplingUMesh *>(mesh);
2641   if(!meshC)
2642     throw INTERP_KERNEL::Exception("Not implemented yet for not unstructured mesh !");
2643   if(!meshC->checkConsecutiveCellTypesAndOrder(typmai2,typmai2+MED_N_CELL_FIXED_GEO))
2644     throw INTERP_KERNEL::Exception("Unstructuded mesh has not consecutive cell types !");
2645   const int *connI=meshC->getNodalConnectivityIndex()->getConstPointer();
2646   const int *conn=meshC->getNodalConnectivity()->getConstPointer();
2647   int nbOfCells=meshC->getNumberOfCells();
2648   INTERP_KERNEL::NormalizedCellType curType;
2649   const int *wCellIdsPT=cellIdsPerType;
2650   for(const int *pt=connI;pt!=connI+nbOfCells;)
2651     {
2652       curType=(INTERP_KERNEL::NormalizedCellType)conn[*pt];
2653       const int *pt2=std::find_if(pt+1,connI+nbOfCells,ConnReaderML(conn,(int)curType));
2654       int szOfChunk=std::distance(pt,pt2);
2655       if(f->getTypeOfField()!=ON_GAUSS_PT)
2656         {
2657           if(!cellIdsPerType)
2658             split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,szOfChunk,1,0,0));
2659           else
2660             {
2661               split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,szOfChunk,1,wCellIdsPT,0));
2662               wCellIdsPT+=szOfChunk;
2663             }
2664         }
2665       else
2666         {
2667           const MEDCouplingFieldDiscretizationGauss *disc=static_cast<const MEDCouplingFieldDiscretizationGauss *>(f->getDiscretization());
2668           const DataArrayInt *arr=disc->getArrayOfDiscIds();
2669           MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da,daTmp1;
2670           if(!cellIdsPerType)
2671             da=arr->selectByTupleId2(std::distance(connI,pt),std::distance(connI,pt2),1);
2672           else
2673             {
2674               daTmp1=DataArrayInt::New();
2675               daTmp1->useArray(const_cast<int *>(cellIdsPerType),false,CPP_DEALLOC,szOfChunk,1);
2676               MEDCouplingAutoRefCountObjectPtr<DataArrayInt> daTmp2=daTmp1->deepCpy();
2677               daTmp2->applyLin(1,std::distance(connI,pt));
2678               da=arr->selectByTupleId(daTmp2->begin(),daTmp2->end());
2679             }
2680           std::vector<int> differentIds;
2681           std::vector<DataArrayInt *> parts=da->partitionByDifferentValues(differentIds);
2682           std::vector< MEDCouplingAutoRefCountObjectPtr<DataArrayInt> > partsAuto(parts.size());
2683           int jj=0;
2684           for(std::vector<DataArrayInt *>::const_iterator it=parts.begin();it!=parts.end();it++,jj++)
2685             partsAuto[jj]=parts[jj];
2686           jj=0;
2687           for(std::vector<DataArrayInt *>::const_iterator it=parts.begin();it!=parts.end();it++,jj++)
2688             {
2689               if(!cellIdsPerType)
2690                 {
2691                   if(parts[jj]->getNumberOfTuples()==szOfChunk && parts[jj]->isIdentity())
2692                     split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,szOfChunk,1,0,0));
2693                   else
2694                     split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,parts[jj]->getNumberOfTuples(),1,parts[jj]->getConstPointer(),0));
2695                 }
2696               else
2697                 {
2698                   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp=daTmp1->selectByTupleId(parts[jj]->begin(),parts[jj]->end());
2699                   split.push_back(MEDLoader::MEDFieldDoublePerCellType(curType,0,nbComp,tmp->getNumberOfTuples(),1,tmp->getConstPointer(),0));
2700                 }
2701             }
2702           if(!cellIdsPerType)
2703             wCellIdsPT+=szOfChunk;
2704         }
2705       pt=pt2;
2706     }
2707 }
2708
2709 void MEDLoaderNS::writeFieldAndMeshDirectly(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, bool forceFromScratch)
2710 {
2711   f->checkCoherency();
2712   std::string meshName(f->getMesh()->getName());
2713   if(meshName.empty())
2714     throw INTERP_KERNEL::Exception("Trying to write a mesh (f->getMesh()) with no name ! MED file format needs a not empty mesh name !");
2715   std::string fieldName(f->getName());
2716   if(fieldName.empty())
2717     throw INTERP_KERNEL::Exception("Trying to write a field with no name ! MED file format needs a not empty field name !");
2718   MEDCouplingUMesh *mesh=dynamic_cast<MEDCouplingUMesh *>(const_cast<MEDCouplingMesh *>(f->getMesh()));
2719   if(mesh)
2720     {
2721       bool isRenumbering;
2722       std::vector<const MEDCouplingUMesh *> meshV(1); meshV[0]=mesh;
2723       std::vector<const DataArrayInt *> famV(1); famV[0]=0;
2724       writeUMeshesDirectly(fileName,meshV,famV,forceFromScratch,isRenumbering);
2725       if(isRenumbering)
2726         {
2727           MEDCouplingAutoRefCountObjectPtr<ParaMEDMEM::MEDCouplingFieldDouble> f2=f->clone(true);
2728           MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da=mesh->getRenumArrForConsecutiveCellTypesSpec(typmai2,typmai2+MED_N_CELL_FIXED_GEO);
2729           f2->renumberCells(da->getConstPointer(),false);
2730           appendFieldDirectly(fileName,f2);
2731         }
2732       else
2733         appendFieldDirectly(fileName,f);
2734       return ;
2735     }
2736   throw INTERP_KERNEL::Exception("The mesh underlying field is not unstructured ! Only unstructured mesh supported for writting now !");
2737 }
2738
2739 /*!
2740  * When called this method expectes that file 'fileName' is already existing and has a mesh with name equal to
2741  * f->getMesh()->getName(). If not the behaviour of this method is not warranted.
2742  * This method reads the corresponding mesh into the file and try to fit it with f->getMesh().
2743  * If it appears that f->getMesh() equals exactly mesh into the file 
2744  */
2745 void MEDLoaderNS::writeFieldTryingToFitExistingMesh(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f)
2746 {
2747   std::vector<int> poss;
2748   int mDimInFile=MEDLoaderNS::readUMeshDimFromFile(fileName,f->getMesh()->getName(),poss);
2749   int mdim=f->getMesh()->getMeshDimension();
2750   int f2=mdim-mDimInFile;
2751   if(std::find(poss.begin(),poss.end(),f2)==poss.end())
2752     {
2753       std::ostringstream oss; oss << "Trying to fit with the existing \"" << f->getMesh()->getName() << "mesh in file \"" << fileName;
2754       oss << "\" but meshdimension does not match !";
2755       throw INTERP_KERNEL::Exception(oss.str().c_str());
2756     }
2757   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m=MEDLoader::ReadUMeshFromFile(fileName,f->getMesh()->getName(),f2);
2758   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m2=MEDCouplingUMesh::MergeUMeshes(m,static_cast<const MEDCouplingUMesh *>(f->getMesh()));
2759   bool areNodesMerged;
2760   int newNbOfNodes;
2761   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da=m2->mergeNodes(MEDLoader::_EPS_FOR_NODE_COMP,areNodesMerged,newNbOfNodes);
2762   if(!areNodesMerged || newNbOfNodes!=m->getNumberOfNodes())
2763     {
2764       std::ostringstream oss; oss << "Nodes in already written mesh \"" << f->getMesh()->getName() << "\" in file \"" << fileName << "\" does not fit coordinates of unstructured grid f->getMesh() !";
2765       throw INTERP_KERNEL::Exception(oss.str().c_str());
2766     }
2767   switch(f->getTypeOfField())
2768     {
2769     case ParaMEDMEM::ON_CELLS:
2770       {
2771         MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da2=m2->zipConnectivityTraducer(MEDLoader::_COMP_FOR_CELL);
2772         if(m2->getNumberOfCells()!=m->getNumberOfCells())
2773           {
2774             std::ostringstream oss1; oss1 << "Cells in already written mesh \"" << f->getMesh()->getName() << "\" in file \"" << fileName << "\" does not fit connectivity of unstructured grid f->getMesh() !";
2775             throw INTERP_KERNEL::Exception(oss1.str().c_str());
2776           }
2777         da=m2->convertCellArrayPerGeoType(da2);
2778         MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da3=da->substr(m2->getNumberOfCells());
2779         da2=m2->convertCellArrayPerGeoType(da3);
2780         appendCellProfileField(fileName,f,da2->getConstPointer());
2781         break;
2782       }
2783     case ParaMEDMEM::ON_GAUSS_NE:
2784       {
2785         MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da2=m2->zipConnectivityTraducer(MEDLoader::_COMP_FOR_CELL);
2786         if(m2->getNumberOfCells()!=m->getNumberOfCells())
2787           {
2788             std::ostringstream oss1; oss1 << "Cells in already written mesh \"" << f->getMesh()->getName() << "\" in file \"" << fileName << "\" does not fit connectivity of unstructured grid f->getMesh() !";
2789             throw INTERP_KERNEL::Exception(oss1.str().c_str());
2790           }
2791         da=m2->convertCellArrayPerGeoType(da2);
2792         MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da3=da->substr(m2->getNumberOfCells());
2793         da2=m2->convertCellArrayPerGeoType(da3);
2794         appendNodeElementProfileField(fileName,f,da2->getConstPointer());
2795         break;
2796       }
2797     case ParaMEDMEM::ON_NODES:
2798       {
2799         appendNodeProfileField(fileName,f,da->getConstPointer()+m->getNumberOfNodes());
2800         break;
2801       }
2802     default:
2803       {
2804         throw INTERP_KERNEL::Exception("Not implemented other profile fitting from already written mesh for fields than on NODES and on CELLS.");
2805       }
2806     }
2807 }
2808
2809 void MEDLoader::WriteUMesh(const char *fileName, const ParaMEDMEM::MEDCouplingUMesh *mesh, bool writeFromScratch) throw(INTERP_KERNEL::Exception)
2810 {
2811   std::string meshName(mesh->getName());
2812   if(meshName.empty())
2813     throw INTERP_KERNEL::Exception("Trying to write a unstructured mesh with no name ! MED file format needs a not empty mesh name !");
2814   int status=MEDLoaderBase::getStatusOfFile(fileName);
2815   bool isRenumbering;
2816   if(status!=MEDLoaderBase::EXIST_RW && status!=MEDLoaderBase::NOT_EXIST)
2817     {
2818       std::ostringstream oss; oss << "File with name \'" << fileName << "\' has not valid permissions !";
2819       throw INTERP_KERNEL::Exception(oss.str().c_str());
2820     }
2821   std::vector<const ParaMEDMEM::MEDCouplingUMesh *> meshV(1); meshV[0]=mesh;
2822   std::vector<const ParaMEDMEM::DataArrayInt *> famV(1); famV[0]=0;
2823   if(writeFromScratch)
2824     {
2825       MEDLoaderNS::writeUMeshesDirectly(fileName,meshV,famV,true,isRenumbering);
2826       return ;
2827     }
2828   if(status==MEDLoaderBase::NOT_EXIST)
2829     {
2830       MEDLoaderNS::writeUMeshesDirectly(fileName,meshV,famV,true,isRenumbering);
2831       return;
2832     }
2833   else
2834     {
2835       std::vector<std::string> meshNames=GetMeshNames(fileName);
2836       if(std::find(meshNames.begin(),meshNames.end(),meshName)==meshNames.end())
2837         MEDLoaderNS::writeUMeshesDirectly(fileName,meshV,famV,false,isRenumbering);
2838       else
2839         {
2840           std::ostringstream oss; oss << "File \'" << fileName << "\' already exists and has already a mesh called \"";
2841           oss << meshName << "\" !";
2842           throw INTERP_KERNEL::Exception(oss.str().c_str());
2843         }
2844     }
2845 }
2846
2847 void MEDLoader::WriteUMeshDep(const char *fileName, const ParaMEDMEM::MEDCouplingUMesh *mesh, bool writeFromScratch) throw(INTERP_KERNEL::Exception)
2848 {
2849   std::string meshName(mesh->getName());
2850   if(meshName.empty())
2851     throw INTERP_KERNEL::Exception("Trying to write a unstructured mesh with no name ! MED file format needs a not empty mesh name !");
2852   int status=MEDLoaderBase::getStatusOfFile(fileName);
2853   bool isRenumbering;
2854   if(status!=MEDLoaderBase::EXIST_RW && status!=MEDLoaderBase::NOT_EXIST)
2855     {
2856       std::ostringstream oss; oss << "File with name \'" << fileName << "\' has not valid permissions !";
2857       throw INTERP_KERNEL::Exception(oss.str().c_str());
2858     }
2859   std::vector<const ParaMEDMEM::MEDCouplingUMesh *> meshV(1); meshV[0]=mesh;
2860   std::vector<const ParaMEDMEM::DataArrayInt *> famV(1); famV[0]=0;
2861   if(writeFromScratch)
2862     {
2863       MEDLoaderNS::writeUMeshesDirectly(fileName,meshV,famV,true,isRenumbering);
2864       return ;
2865     }
2866   if(status==MEDLoaderBase::NOT_EXIST)
2867     {
2868       MEDLoaderNS::writeUMeshesDirectly(fileName,meshV,famV,true,isRenumbering);
2869       return;
2870     }
2871   else
2872     MEDLoaderNS::writeUMeshesDirectly(fileName,meshV,famV,false,isRenumbering);
2873 }
2874
2875 void MEDLoader::WriteUMeshesPartition(const char *fileName, const char *meshNameC, const std::vector<const ParaMEDMEM::MEDCouplingUMesh *>& meshes, bool writeFromScratch) throw(INTERP_KERNEL::Exception)
2876 {
2877   std::string meshName(meshNameC);
2878   if(meshName.empty())
2879     throw INTERP_KERNEL::Exception("Trying to write a unstructured mesh with no name ! MED file format needs a not empty mesh name : change 2nd parameter !");
2880   int status=MEDLoaderBase::getStatusOfFile(fileName);
2881   if(status!=MEDLoaderBase::EXIST_RW && status!=MEDLoaderBase::NOT_EXIST)
2882     {
2883       std::ostringstream oss; oss << "File with name \'" << fileName << "\' has not valid permissions !";
2884       throw INTERP_KERNEL::Exception(oss.str().c_str());
2885     }
2886   if(meshes.empty())
2887     throw INTERP_KERNEL::Exception("List of meshes must be not empty !");
2888   const DataArrayDouble *coords=meshes.front()->getCoords();
2889   for(std::vector<const ParaMEDMEM::MEDCouplingUMesh *>::const_iterator iter=meshes.begin();iter!=meshes.end();iter++)
2890     if(coords!=(*iter)->getCoords())
2891       throw INTERP_KERNEL::Exception("Meshes does not not share the same coordinates : try method MEDCouplingPointSet::tryToShareSameCoords !");
2892   std::set<std::string> tmp;
2893   for(std::vector<const ParaMEDMEM::MEDCouplingUMesh *>::const_iterator iter=meshes.begin();iter!=meshes.end();iter++)
2894     {
2895       if(tmp.find((*iter)->getName())==tmp.end())
2896         tmp.insert((*iter)->getName());
2897       else
2898         throw INTERP_KERNEL::Exception("The names of meshes must be different each other !");
2899     }
2900   tmp.clear();
2901   if(writeFromScratch)
2902     {
2903       MEDLoaderNS::writeUMeshesPartitionDirectly(fileName,meshNameC,meshes,true);
2904       return ;
2905     }
2906   if(status==MEDLoaderBase::NOT_EXIST)
2907     {
2908       MEDLoaderNS::writeUMeshesPartitionDirectly(fileName,meshNameC,meshes,true);
2909       return;
2910     }
2911   else
2912     {
2913       std::vector<std::string> meshNames=GetMeshNames(fileName);
2914       if(std::find(meshNames.begin(),meshNames.end(),meshName)==meshNames.end())
2915         MEDLoaderNS::writeUMeshesPartitionDirectly(fileName,meshNameC,meshes,false);
2916       else
2917         {
2918           std::ostringstream oss; oss << "File \'" << fileName << "\' already exists and has already a mesh called \"";
2919           oss << meshName << "\" !";
2920           throw INTERP_KERNEL::Exception(oss.str().c_str());
2921         }
2922     }
2923 }
2924
2925 void MEDLoader::WriteUMeshesPartitionDep(const char *fileName, const char *meshNameC, const std::vector<const ParaMEDMEM::MEDCouplingUMesh *>& meshes, bool writeFromScratch) throw(INTERP_KERNEL::Exception)
2926 {
2927   std::string meshName(meshNameC);
2928   if(meshName.empty())
2929     throw INTERP_KERNEL::Exception("Trying to write a unstructured mesh with no name ! MED file format needs a not empty mesh name : change 2nd parameter !");
2930   int status=MEDLoaderBase::getStatusOfFile(fileName);
2931   if(status!=MEDLoaderBase::EXIST_RW && status!=MEDLoaderBase::NOT_EXIST)
2932     {
2933       std::ostringstream oss; oss << "File with name \'" << fileName << "\' has not valid permissions !";
2934       throw INTERP_KERNEL::Exception(oss.str().c_str());
2935     }
2936   if(meshes.empty())
2937     throw INTERP_KERNEL::Exception("List of meshes must be not empty !");
2938   const DataArrayDouble *coords=meshes.front()->getCoords();
2939   for(std::vector<const ParaMEDMEM::MEDCouplingUMesh *>::const_iterator iter=meshes.begin();iter!=meshes.end();iter++)
2940     if(coords!=(*iter)->getCoords())
2941       throw INTERP_KERNEL::Exception("Meshes does not not share the same coordinates : try method MEDCouplingPointSet::tryToShareSameCoords !");
2942   std::set<std::string> tmp;
2943   for(std::vector<const ParaMEDMEM::MEDCouplingUMesh *>::const_iterator iter=meshes.begin();iter!=meshes.end();iter++)
2944     {
2945       if(tmp.find((*iter)->getName())==tmp.end())
2946         tmp.insert((*iter)->getName());
2947       else
2948         throw INTERP_KERNEL::Exception("The names of meshes must be different each other !");
2949     }
2950   tmp.clear();
2951   if(writeFromScratch)
2952     {
2953       MEDLoaderNS::writeUMeshesPartitionDirectly(fileName,meshNameC,meshes,true);
2954       return ;
2955     }
2956   if(status==MEDLoaderBase::NOT_EXIST)
2957     {
2958       MEDLoaderNS::writeUMeshesPartitionDirectly(fileName,meshNameC,meshes,true);
2959       return;
2960     }
2961   else
2962     {
2963       MEDLoaderNS::writeUMeshesPartitionDirectly(fileName,meshNameC,meshes,false);
2964     }
2965 }
2966
2967 void MEDLoader::WriteUMeshes(const char *fileName, const std::vector<const ParaMEDMEM::MEDCouplingUMesh *>& meshes, bool writeFromScratch) throw(INTERP_KERNEL::Exception)
2968 {
2969   int status=MEDLoaderBase::getStatusOfFile(fileName);
2970   if(status!=MEDLoaderBase::EXIST_RW && status!=MEDLoaderBase::NOT_EXIST)
2971     {
2972       std::ostringstream oss; oss << "File with name \'" << fileName << "\' has not valid permissions !";
2973       throw INTERP_KERNEL::Exception(oss.str().c_str());
2974     }
2975   if(meshes.empty())
2976     throw INTERP_KERNEL::Exception("List of meshes must be not empty !");
2977   std::string meshName(meshes[0]->getName());
2978   if(meshName.empty())
2979     throw INTERP_KERNEL::Exception("Trying to write a unstructured mesh with no name ! MED file format needs a not empty mesh name : change name of first element of 2nd parameter !");
2980   const DataArrayDouble *coords=meshes.front()->getCoords();
2981   for(std::vector<const ParaMEDMEM::MEDCouplingUMesh *>::const_iterator iter=meshes.begin();iter!=meshes.end();iter++)
2982     if(coords!=(*iter)->getCoords())
2983       throw INTERP_KERNEL::Exception("Meshes does not not share the same coordinates : try method MEDCouplingPointSet::tryToShareSameCoords !");
2984   std::set<int> tmp;
2985   for(std::vector<const ParaMEDMEM::MEDCouplingUMesh *>::const_iterator iter=meshes.begin();iter!=meshes.end();iter++)
2986     {
2987       if(tmp.find((*iter)->getMeshDimension())==tmp.end())
2988         tmp.insert((*iter)->getMeshDimension());
2989       else
2990         throw INTERP_KERNEL::Exception("The mesh dimension of meshes must be different each other !");
2991     }
2992   tmp.clear();
2993   bool isRenumbering;
2994   std::vector<const DataArrayInt *> families(meshes.size());
2995   if(writeFromScratch)
2996     {
2997       MEDLoaderNS::writeUMeshesDirectly(fileName,meshes,families,true,isRenumbering);
2998       return ;
2999     }
3000   if(status==MEDLoaderBase::NOT_EXIST)
3001     {
3002       MEDLoaderNS::writeUMeshesDirectly(fileName,meshes,families,true,isRenumbering);
3003       return;
3004     }
3005   else
3006     {
3007       MEDLoaderNS::writeUMeshesDirectly(fileName,meshes,families,false,isRenumbering);
3008       return;
3009     }
3010 }
3011
3012 void MEDLoader::WriteField(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, bool writeFromScratch) throw(INTERP_KERNEL::Exception)
3013 {
3014   int status=MEDLoaderBase::getStatusOfFile(fileName);
3015   if(status!=MEDLoaderBase::EXIST_RW && status!=MEDLoaderBase::NOT_EXIST)
3016     {
3017       std::ostringstream oss; oss << "File with name \'" << fileName << "\' has not valid permissions !";
3018       throw INTERP_KERNEL::Exception(oss.str().c_str());
3019     }
3020   if(writeFromScratch)
3021     {
3022       MEDLoaderNS::writeFieldAndMeshDirectly(fileName,f,true);
3023      return ;
3024     }
3025   if(status==MEDLoaderBase::NOT_EXIST)
3026     {
3027      MEDLoaderNS::writeFieldAndMeshDirectly(fileName,f,true);
3028      return ;
3029     }
3030   else
3031     {
3032       std::vector<std::string> meshNames=GetMeshNames(fileName);
3033       std::string fileNameCpp(f->getMesh()->getName());
3034       if(std::find(meshNames.begin(),meshNames.end(),fileNameCpp)==meshNames.end())
3035         MEDLoaderNS::writeFieldAndMeshDirectly(fileName,f,false);
3036       else
3037         MEDLoaderNS::writeFieldTryingToFitExistingMesh(fileName,f);
3038     }
3039 }
3040
3041 void MEDLoader::WriteFieldDep(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f, bool writeFromScratch) throw(INTERP_KERNEL::Exception)
3042 {
3043   int status=MEDLoaderBase::getStatusOfFile(fileName);
3044   if(status!=MEDLoaderBase::EXIST_RW && status!=MEDLoaderBase::NOT_EXIST)
3045     {
3046       std::ostringstream oss; oss << "File with name \'" << fileName << "\' has not valid permissions !";
3047       throw INTERP_KERNEL::Exception(oss.str().c_str());
3048     }
3049   if(writeFromScratch)
3050     {
3051       MEDLoaderNS::writeFieldAndMeshDirectly(fileName,f,true);
3052      return ;
3053     }
3054   if(status==MEDLoaderBase::NOT_EXIST)
3055     {
3056      MEDLoaderNS::writeFieldAndMeshDirectly(fileName,f,true);
3057      return ;
3058     }
3059   else
3060     MEDLoaderNS::writeFieldAndMeshDirectly(fileName,f,false);
3061 }
3062
3063 void MEDLoader::WriteFieldUsingAlreadyWrittenMesh(const char *fileName, const ParaMEDMEM::MEDCouplingFieldDouble *f) throw(INTERP_KERNEL::Exception)
3064 {
3065   f->checkCoherency();
3066   int status=MEDLoaderBase::getStatusOfFile(fileName);
3067   if(status!=MEDLoaderBase::EXIST_RW)
3068     {
3069       std::ostringstream oss; oss << "File with name \'" << fileName << "\' has not valid permissions or not exists !";
3070       throw INTERP_KERNEL::Exception(oss.str().c_str());
3071     }
3072   MEDLoaderNS::appendFieldDirectly(fileName,f);
3073 }