#include <Python.h>              /*Python seen from C*/
#include <Numeric/arrayobject.h> /*NumPy  seen from C*/
#include <math.h>


static PyObject *sumarray(PyObject *self, PyObject* args)
{
  PyArrayObject *array; /* C representation of Numeric array */
  int i,n;              /* number of array entries  */
  double result = 0.0;
  double* a;            /* ptr to the NumPy array */

  /* parse the arguments  */
  if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &array)) {
    return NULL;  /* Error indicator */
  }

  /* check that we have a one-dimensional array */
  if (array->nd != 1) {
    /* throw a Python exception (ValueError) */
    PyErr_SetString(PyExc_ValueError,
                    "the NumPy array must be one-dimensional");
    return NULL;
  }
  /* check that the datatype is NumPy-float, (C double ) */
  if (array->descr->type_num != PyArray_DOUBLE) {
    PyErr_SetString(PyExc_ValueError,
                    "the NumPy array must consist of floats");
    return NULL;
  }

  n = array->dimensions[0];    /* length of the array */
  a = (double*) array->data;   /* pointer to the NumPy data */

  /* compute the sum of elements in array  */
  for (i=0; i<n; i++) {
    result = result + a[i];
  }

  Py_INCREF(Py_None);  
  return Py_BuildValue("d", result); 
}   

/* Doc strings: */
static char cnumpy_sumarray_doc[] = "sumarray(a)";
static char cnumpy_doc[] = "module cnumpy:\n sumarray(a)";


/* Method table */
static PyMethodDef cnumpyMethods[] = {
  {"sumarray", /* name of func when called from Python */
   sumarray,   /* corresponding C function */
   METH_VARARGS,
   cnumpy_sumarray_doc}, /* doc string for function */
  {NULL, NULL}
};

/* init */
void initcnumpy()
{
  (void) Py_InitModule3("cnumpy", cnumpyMethods,cnumpy_doc );
  import_array();   /* NumPy initialization */
}




