Index: /codes/icosagcm/devel/Python/dynamico/xios.py
===================================================================
--- /codes/icosagcm/devel/Python/dynamico/xios.py	(revision 694)
+++ /codes/icosagcm/devel/Python/dynamico/xios.py	(revision 694)
@@ -0,0 +1,68 @@
+import numpy as np
+import cxios
+from unstructured import ker
+from dynamico.meshes import radian
+from cxios import finalize
+
+def cf_boundaries(degree,points,lon,lat):
+    n, nvertex = len(degree), degree.max()
+    bnd_lon, bnd_lat = np.zeros((n,nvertex)),np.zeros((n,nvertex))
+    for ij in range(n):
+        nb=degree[ij]
+        for k in range(nb):
+            vertex = points[ij,k]
+            bnd_lon[ij,k]=lon[vertex]
+            bnd_lat[ij,k]=lat[vertex]
+        for k in range(nb,nvertex):   # repeat last vertex if nb<nvertex
+            bnd_lon[ij,k]=bnd_lon[ij,nb-1]
+            bnd_lat[ij,k]=bnd_lat[ij,nb-1]
+    return bnd_lon, bnd_lat
+
+def setup_domain(cat,id, degree,vertex,lon,lat,lon_v,lat_v, ncell_glo, index_glo, displ): # cat in 'domain','domaingroup'
+    bnd_lon, bnd_lat = cf_boundaries(degree, vertex, lon_v, lat_v)
+    ncell, nvertex = bnd_lon.shape
+    mesh = cxios.Handle(cat,id)
+    mesh.set_attr(type='unstructured')
+    mesh.set_attr(ni_glo=ncell_glo, ni=ncell, ibegin=displ, i_index=index_glo)
+    mesh.set_attr(lonvalue_1d=lon, latvalue_1d=lat)
+    mesh.set_attr(nvertex=nvertex,bounds_lon_1d=bnd_lon, bounds_lat_1d=bnd_lat)
+
+class XIOS_Context:
+    def __init__(self, pmesh, mesh,nqtot):
+        self.mesh=mesh
+        ker.dynamico_setup_xios()
+        # vertical axis, nq
+        llm = mesh.llm
+        lev, levp1, nq = [cxios.Handle('axis',name) for name in 'lev', 'levp1', 'nq']
+        lev.set_attr(n_glo=llm, value=np.arange(llm))
+        levp1.set_attr(n_glo=llm+1, value=np.arange(llm+1))
+        nq.set_attr(n_glo=nqtot, value=np.arange(nqtot))
+        # primal mesh
+        lon_i, lat_i, lon_v, lat_v = [x*radian for x in mesh.lon_i, mesh.lat_i, mesh.lon_v, mesh.lat_v]
+        mesh_i=setup_domain('domaingroup','i', mesh.primal_own_deg, mesh.primal_vertex,
+                            lon_i[mesh.primal_own_loc], lat_i[mesh.primal_own_loc],
+                            lon_v, lat_v,
+                            pmesh.dim_primal.n, mesh.primal_own_glo, mesh.displ)
+        # calendar
+        calendar=cxios.Handle('calendar_wrapper')
+        dtime = cxios.Duration(second=3600.)
+        calendar.set_attr(timestep=dtime)
+        calendar.update_timestep()
+        std=cxios.Handle('fieldgroup','standard_output')
+        std.set_attr(freq_op=dtime)
+        freq_offset = cxios.Duration(second=0)
+        std.set_attr(freq_offset=freq_offset)
+        print 'cxios.context_close_definition()'
+        cxios.context_close_definition()
+    def send_field_primal(self,name, data):
+        own_loc = self.mesh.primal_own_loc
+        if data.ndim==1:
+            data = data[own_loc]
+        if data.ndim==2:
+            data = data[:,own_loc]
+        data = np.ascontiguousarray(data)
+        cxios.send_field(name, data)
+    def update_calendar(self, i):
+        ker.dynamico_xios_update_calendar(i)
+    def finalize(self):
+        cxios.context_finalize()
Index: /codes/icosagcm/devel/Python/src/cxios.pyx
===================================================================
--- /codes/icosagcm/devel/Python/src/cxios.pyx	(revision 694)
+++ /codes/icosagcm/devel/Python/src/cxios.pyx	(revision 694)
@@ -0,0 +1,110 @@
+from dynamico.libs import libxios
+import dynamico.wrap as wrap
+import numpy as np
+
+from ctypes import c_int, c_double, c_bool, c_void_p, c_char_p, byref, POINTER, Structure
+c_void_pp=POINTER(c_void_p) # used in prototype
+c_void_p_byref=type(byref(c_void_p())) # used in py2c because byref creates an object of this type, not c_void_pp
+
+# ------------- Direct cython interfaces ----------------- #
+
+cdef extern from "functions.h":
+     cdef void cxios_context_close_definition()
+     cdef void cxios_context_finalize()
+     cdef void cxios_finalize()
+     cdef void cxios_write_data_k81(char*, int, double*, int)
+     cdef void cxios_write_data_k82(char*, int, double*, int,int)
+     cdef void cxios_write_data_k83(char*, int, double*, int,int,int)
+
+def context_close_definition(): cxios_context_close_definition()
+def context_finalize(): cxios_context_finalize()
+def finalize(): cxios_finalize()
+
+cdef send_field1(char* id, int idlen, double[:] data):     cxios_write_data_k81(id, idlen, &data[0],     data.shape[0])
+cdef send_field2(char* id, int idlen, double[:,:] data):   cxios_write_data_k82(id, idlen, &data[0,0],   data.shape[0],data.shape[1])
+cdef send_field3(char* id, int idlen, double[:,:,:] data): cxios_write_data_k83(id, idlen, &data[0,0,0], data.shape[0],data.shape[1],data.shape[2])
+
+def send_field(bytes id, data):
+    cdef char* idptr = id
+    cdef int idlen = len(id)
+    print 'cxios.write_data', id, data.shape
+    ndim=data.ndim
+    if ndim==1: send_field1(idptr,idlen,data)
+    if ndim==2: send_field2(idptr,idlen,data)
+    if ndim==3: send_field3(idptr,idlen,data)
+
+# -------------------------------------------------------- #
+
+lib=wrap.Struct()
+cxios = wrap.SharedLib(vars(lib), libxios, prefix_so='cxios_')
+
+class Duration(Structure):
+    _fields_ = [(name, c_double) for name in ('year', 'month', 'day', 'hour', 'minute', 'second', 'timestep') ]
+class Date(Structure):
+    _fields_ = [(name, c_int) for name in ('year', 'month', 'day', 'hour', 'minute', 'second') ]
+
+print Duration.from_param
+
+for x in c_void_p_byref, Duration, Date : wrap.py2c[x]=wrap.noop # accept arguments of type (void*)&, Duration, ...
+
+def SHAPE(data): return np.asarray(list(reversed(data.shape)),c_int) # reverse shape to follow Fortran convention
+
+class Handle:
+    def __init__(self, cat, id=None):
+        self.handle = c_void_p()
+        if id is None:
+            id='default'
+            create_fun = cxios.vardict['get_current_'+cat]
+            create_fun(byref(self.handle))
+        else:
+            create_fun = cxios.vardict[cat+'_handle_create']
+            create_fun(byref(self.handle), id, c_int(len(id)))
+        self.cat, self.prefix_set, self.id = cat, 'set_'+cat+'_', id
+        print 'Handle', cat, self.id, self.handle
+    def set_attr(self, **kwargs):
+        prefix, handle = self.prefix_set, self.handle
+        for key, value in kwargs.iteritems():
+            fun = cxios.vardict[prefix+key]
+            extra=value
+            if type(value) in (int,c_int):
+                fun(handle,c_int(value))
+            elif type(value) is np.ndarray:
+                extra=SHAPE(value)
+                fun(handle,value,extra)
+            elif type(value) is str:
+                fun(handle,value,c_int(len(value)))
+            elif type(value) in (Duration, Date):
+                fun(handle,value)
+            else:
+                raise(TypeError)
+            print self.id+'.'+prefix+key, type(value), extra
+    def update_timestep(self):
+        lib.update_calendar_timestep(self.handle)
+
+def import_set_attr(cats, *args): #attr_int, attr_array, attr_str):
+    for arg in args:
+        argtype = arg.pop(0)
+        if argtype is str:
+            argtype = [c_void_p, c_char_p, c_int] #char *str, int strlen
+        elif argtype is np.ndarray:
+            argtype = [c_void_p, c_void_p, c_void_p] # void *handle, double *data, int* SHAPE(data)
+        else:
+            argtype = [c_void_p, argtype] #void *handle, argtype data
+        for cat in cats:
+            cxios.import_funs( [arg + argtype], prefix='set_'+cat+'_')
+
+def import_cxios_functions():
+    cats=['axis','domain','domaingroup','field','fieldgroup'] # XIOS categories
+    cxios.import_funs([
+                       [cat+'_handle_create' for cat in cats]+[c_void_pp,c_char_p,c_int],
+                       ['get_current_'+'calendar_wrapper',c_void_pp],
+                       ['update_calendar_timestep',c_void_p],
+                       ['update_calendar',c_int] ])
+
+    import_set_attr(['domain','domaingroup'], [c_int,'ni_glo','ibegin','ni','nvertex','data_dim'], [str,'type'],
+                        [np.ndarray, 'i_index','lonvalue_1d','latvalue_1d','bounds_lat_1d','bounds_lon_1d'])
+    import_set_attr(['field','fieldgroup'], [Duration,'freq_op','freq_offset'])
+    import_set_attr(['axis'], [c_int,'n_glo'], [np.ndarray,'value'])
+    import_set_attr(['calendar_wrapper'], [Duration,'timestep'])
+
+import_cxios_functions()
Index: /codes/icosagcm/devel/Python/src/setup.py
===================================================================
--- /codes/icosagcm/devel/Python/src/setup.py	(revision 693)
+++ /codes/icosagcm/devel/Python/src/setup.py	(revision 694)
@@ -4,5 +4,5 @@
 setup(  name = "DYNAMICO kernels for unstructured mesh",
         ext_modules = cythonize([
-            Extension("xios",["xios.pyx"],libraries=["xios"]),
+            Extension("cxios",["cxios.pyx"],libraries=["xios"]),
             Extension("unstructured",["unstructured.pyx"],libraries=["icosa","xios"])
             ])
Index: des/icosagcm/devel/Python/src/xios.pyx
===================================================================
--- /codes/icosagcm/devel/Python/src/xios.pyx	(revision 693)
+++ 	(revision )
@@ -1,110 +1,0 @@
-from dynamico.libs import libxios
-import dynamico.wrap as wrap
-import numpy as np
-
-from ctypes import c_int, c_double, c_bool, c_void_p, c_char_p, byref, POINTER, Structure
-c_void_pp=POINTER(c_void_p) # used in prototype
-c_void_p_byref=type(byref(c_void_p())) # used in py2c because byref creates an object of this type, not c_void_pp
-
-# ------------- Direct cython interfaces ----------------- #
-
-cdef extern from "functions.h":
-     cdef void cxios_context_close_definition()
-     cdef void cxios_context_finalize()
-     cdef void cxios_finalize()
-     cdef void cxios_write_data_k81(char*, int, double*, int)
-     cdef void cxios_write_data_k82(char*, int, double*, int,int)
-     cdef void cxios_write_data_k83(char*, int, double*, int,int,int)
-
-def context_close_definition(): cxios_context_close_definition()
-def context_finalize(): cxios_context_finalize()
-def finalize(): cxios_finalize()
-
-cdef send_field1(char* id, int idlen, double[:] data):     cxios_write_data_k81(id, idlen, &data[0],     data.shape[0])
-cdef send_field2(char* id, int idlen, double[:,:] data):   cxios_write_data_k82(id, idlen, &data[0,0],   data.shape[0],data.shape[1])
-cdef send_field3(char* id, int idlen, double[:,:,:] data): cxios_write_data_k83(id, idlen, &data[0,0,0], data.shape[0],data.shape[1],data.shape[2])
-
-def send_field(bytes id, data):
-    cdef char* idptr = id
-    cdef int idlen = len(id)
-    print 'cxios.write_data', id, data.shape
-    ndim=data.ndim
-    if ndim==1: send_field1(idptr,idlen,data)
-    if ndim==2: send_field2(idptr,idlen,data)
-    if ndim==3: send_field3(idptr,idlen,data)
-
-# -------------------------------------------------------- #
-
-lib=wrap.Struct()
-cxios = wrap.SharedLib(vars(lib), libxios, prefix_so='cxios_')
-
-class Duration(Structure):
-    _fields_ = [(name, c_double) for name in ('year', 'month', 'day', 'hour', 'minute', 'second', 'timestep') ]
-class Date(Structure):
-    _fields_ = [(name, c_int) for name in ('year', 'month', 'day', 'hour', 'minute', 'second') ]
-
-print Duration.from_param
-
-for x in c_void_p_byref, Duration, Date : wrap.py2c[x]=wrap.noop # accept arguments of type (void*)&, Duration, ...
-
-def SHAPE(data): return np.asarray(list(reversed(data.shape)),c_int) # reverse shape to follow Fortran convention
-
-class Handle:
-    def __init__(self, cat, id=None):
-        self.handle = c_void_p()
-        if id is None:
-            id='default'
-            create_fun = cxios.vardict['get_current_'+cat]
-            create_fun(byref(self.handle))
-        else:
-            create_fun = cxios.vardict[cat+'_handle_create']
-            create_fun(byref(self.handle), id, c_int(len(id)))
-        self.cat, self.prefix_set, self.id = cat, 'set_'+cat+'_', id
-        print 'Handle', cat, self.id, self.handle
-    def set_attr(self, **kwargs):
-        prefix, handle = self.prefix_set, self.handle
-        for key, value in kwargs.iteritems():
-            fun = cxios.vardict[prefix+key]
-            extra=value
-            if type(value) in (int,c_int):
-                fun(handle,c_int(value))
-            elif type(value) is np.ndarray:
-                extra=SHAPE(value)
-                fun(handle,value,extra)
-            elif type(value) is str:
-                fun(handle,value,c_int(len(value)))
-            elif type(value) in (Duration, Date):
-                fun(handle,value)
-            else:
-                raise(TypeError)
-            print self.id+'.'+prefix+key, type(value), extra
-    def update_timestep(self):
-        lib.update_calendar_timestep(self.handle)
-
-def import_set_attr(cats, *args): #attr_int, attr_array, attr_str):
-    for arg in args:
-        argtype = arg.pop(0)
-        if argtype is str:
-            argtype = [c_void_p, c_char_p, c_int] #char *str, int strlen
-        elif argtype is np.ndarray:
-            argtype = [c_void_p, c_void_p, c_void_p] # void *handle, double *data, int* SHAPE(data)
-        else:
-            argtype = [c_void_p, argtype] #void *handle, argtype data
-        for cat in cats:
-            cxios.import_funs( [arg + argtype], prefix='set_'+cat+'_')
-
-def import_cxios_functions():
-    cats=['axis','domain','domaingroup','field','fieldgroup'] # XIOS categories
-    cxios.import_funs([
-                       [cat+'_handle_create' for cat in cats]+[c_void_pp,c_char_p,c_int],
-                       ['get_current_'+'calendar_wrapper',c_void_pp],
-                       ['update_calendar_timestep',c_void_p],
-                       ['update_calendar',c_int] ])
-
-    import_set_attr(['domain','domaingroup'], [c_int,'ni_glo','ibegin','ni','nvertex','data_dim'], [str,'type'],
-                        [np.ndarray, 'i_index','lonvalue_1d','latvalue_1d','bounds_lat_1d','bounds_lon_1d'])
-    import_set_attr(['field','fieldgroup'], [Duration,'freq_op','freq_offset'])
-    import_set_attr(['axis'], [c_int,'n_glo'], [np.ndarray,'value'])
-    import_set_attr(['calendar_wrapper'], [Duration,'timestep'])
-
-import_cxios_functions()
Index: /codes/icosagcm/devel/Python/test/py/test_xios.py
===================================================================
--- /codes/icosagcm/devel/Python/test/py/test_xios.py	(revision 693)
+++ /codes/icosagcm/devel/Python/test/py/test_xios.py	(revision 694)
@@ -1,8 +1,5 @@
-#print 'import dynamico'
-#import dynamico
 import dynamico.unstructured as unst
 import dynamico.xios as xios
-#from dynamico.meshes import MPAS_Format, Unstructured_Mesh, radian
-from dynamico.meshes import radian, MPAS_Format, Unstructured_Mesh, Unstructured_PMesh as PMesh, Local_Mesh as Mesh
+from dynamico.meshes import radian, MPAS_Format, Unstructured_PMesh as PMesh, Local_Mesh as Mesh
 
 from mpi4py import MPI
@@ -14,18 +11,4 @@
 import cProfile
 import re
-
-def boundaries(degree,points,lon,lat):
-    n, nvertex = len(degree), degree.max()
-    bnd_lon, bnd_lat = np.zeros((n,nvertex)),np.zeros((n,nvertex))
-    for ij in range(n):
-        nb=degree[ij]
-        for k in range(nb):
-            vertex = points[ij,k]
-            bnd_lon[ij,k]=lon[vertex]
-            bnd_lat[ij,k]=lat[vertex]
-        for k in range(nb,nvertex):   # repeat last vertex if nb<nvertex
-            bnd_lon[ij,k]=bnd_lon[ij,nb-1]
-            bnd_lat[ij,k]=bnd_lat[ij,nb-1]
-    return bnd_lon, bnd_lat
 
 #----------------------------- read MPAS mesh --------------------------------
@@ -39,109 +22,30 @@
 print 'Reading MPAS mesh ...'
 meshfile = MPAS_Format('grids/x1.%d.grid.nc'%grid)
-#mesh = Unstructured_Mesh(meshfile, llm, nqdyn, radius, f)
 pmesh = PMesh(comm,meshfile)
 mesh = Mesh(pmesh, llm, nqdyn, radius, f)
-ni_glo = pmesh.dim_primal.n
-ni_loc = len(mesh.primal_own_glo)
 print '...Done'
 
-lon_i, lat_i, lon_v, lat_v = [x*radian for x in mesh.lon_i, mesh.lat_i, mesh.lon_v, mesh.lat_v]
+#--------------------------------- write some data ----------------------------------------
 
-#--------------------------------- initialize XIOS --------------------------
+context=xios.XIOS_Context(pmesh,mesh,nqtot)
 
-def setup_domain(cat,id, degree,vertex,lon,lat,lon_v,lat_v, ncell_glo=None, index_glo=None, displ=None): # cat in 'domain','domaingroup'
-    bnd_lon, bnd_lat = boundaries(degree, vertex, lon_v, lat_v)
-    ncell, nvertex = bnd_lon.shape
-    if ncell_glo is None :
-        ncell_glo = ncell
-        index_glo = np.arange(ncell, dtype=np.int32)
-        displ = 0
-    mesh = xios.Handle(cat,id)
-    mesh.set_attr(type='unstructured')
-    mesh.set_attr(ni_glo=ncell_glo, ni=ncell, ibegin=displ, i_index=index_glo)
-    mesh.set_attr(lonvalue_1d=lon, latvalue_1d=lat)
-    mesh.set_attr(nvertex=nvertex,bounds_lon_1d=bnd_lon, bounds_lat_1d=bnd_lat)
-
-unst.ker.dynamico_setup_xios()
-
-if True:
-    lev, levp1, nq = [xios.Handle('axis',name) for name in 'lev', 'levp1', 'nq']
-    lev.set_attr(n_glo=llm, value=np.arange(llm))
-    levp1.set_attr(n_glo=llm+1, value=np.arange(llm+1))
-    nq.set_attr(n_glo=nqtot, value=np.arange(nqtot))
-     # primal mesh
-    mesh_i=setup_domain('domaingroup','i', mesh.primal_own_deg, mesh.primal_vertex,
-                            lon_i[mesh.primal_own_loc], lat_i[mesh.primal_own_loc],
-                            lon_v, lat_v,
-                            pmesh.dim_primal.n, mesh.primal_own_glo, mesh.displ)
-#    mesh_i=setup_domain('domaingroup','i', mesh.primal_deg, mesh.primal_vertex-1, lon_i, lat_i, lon_v, lat_v) # primal mesh
-#    mesh_v=setup_domain('domain','v', mesh.dual_deg, mesh.dual_vertex-1, lon_v, lat_v, lon_i, lat_i) # dual mesh
-
-#   CALL xios_set_domain_attr("u",ni_glo=ncell_tot, ibegin=displ, ni=ncell)                                                                              
-#   CALL xios_set_domain_attr("u", data_dim=1, type='unstructured' , nvertex=2, i_index=ind_glo)                                                         
-#   CALL xios_set_domain_attr("u",lonvalue_1d=lon, latvalue_1d=lat, bounds_lon_1d=bounds_lon, bounds_lat_1d=bounds_lat)                                   
-#mesh_e = xios.Handle('domain','u')
-
-# works up to that point !
-
-dtime = xios.Duration(second=3600.)
-
-#   CALL xios_set_timestep(dtime)                                                                                                                        
-if True:
-    calendar=xios.Handle('calendar_wrapper')
-    print (dtime.year, dtime.month, dtime.day, dtime.hour, dtime.second)
-    calendar.set_attr(timestep=dtime)
-    calendar.update_timestep()
-else:
-    unst.ker.dynamico_xios_set_timestep(3600.)
-
-#   CALL xios_set_fieldgroup_attr("standard_output", freq_op=itau_out*xios_timestep, freq_offset=(itau_out-1)*xios_timestep)                             
-if False:
-    std=xios.Handle('fieldgroup','standard_output')
-    std.set_attr(freq_op=dtime)
-    freq_offset = xios.Duration(second=0)
-    std.set_attr(freq_offset=freq_offset)
-
-if True:
-    print 'xios.context_close_definition()'
-    xios.context_close_definition()
-
+lat_i = radian*mesh.lat_i
 lat_ik, junk  = np.meshgrid(lat_i, np.arange(llm), indexing='xy')
 
-def send_field1_primal(name, data):
-#    print 'send_field1_primal :', data.shape
-    data = data[mesh.primal_own_loc]
-    data = np.ascontiguousarray(data)
-    print 'send_field1_primal :', data.shape
-    xios.send_field(name, data)
-def send_field2_primal(name, data):
-#    print 'send_field2_primal :', data.shape
-    data = data[:,mesh.primal_own_loc]
-    data = np.ascontiguousarray(data)
-    print 'send_field2_primal :', data.shape
-    xios.send_field(name, data)
-    
 no_error=True
 try:
     for i in range(100):
-        if True:
-            unst.ker.dynamico_xios_update_calendar(i)
-        else:
-            xios.update_calendar(i)
+        context.update_calendar(i)
         print 'send_field', i
-        send_field1_primal('ps', lat_i)
-        send_field2_primal('theta', lat_ik)
+        context.send_field_primal('ps', lat_i)
+        context.send_field_primal('theta', lat_ik)
 except:
     print 'An error has occured, trying to close XIOS properly'
     no_error=False
-# CALL xios_recv_field(name,field)                                                                                                                       
-# CALL xios_send_field(name,field_tmp)                                                                                                                   
 
 print 'xios.context_finalize()'
-xios.context_finalize()
-
+context.finalize()
 print 'xios.finalize()'
 xios.finalize()
-
 print 'Done'
 
Index: /codes/icosagcm/devel/make_python
===================================================================
--- /codes/icosagcm/devel/make_python	(revision 693)
+++ /codes/icosagcm/devel/make_python	(revision 694)
@@ -96,5 +96,5 @@
     cd $DYNAMICO_ROOT
 
-    for module in xios unstructured meshes dyn time_step DCMIP; do
+    for module in cxios unstructured meshes dyn time_step DCMIP; do
 	echo "from dynamico import $module"
 	LD_PRELOAD=$PYTHON_PRELOAD python -c "from dynamico import $module"
