#include <assert.h>
#include <math.h>
#include <malloc.h>
#include "gpk_std.h"
#include "gpklib.h"
#include "numerics.h"



double *amoeba_center(C double *C* p, int n)
{
 double *pc = (double *)malloc(n*sizeof(double));
 double *tmp = new double[n+1];
 assert(pc && tmp);

 int ii;
 for(ii=0;ii<n;ii++)	{
	int j;
	for(j=0;j<=n;j++)
		tmp[j] = p[j][ii];
	pc[ii] = median(tmp, n+1);
	}
 delete [] tmp;

 return pc;
}


double *
amoeba_spread(C double *C* p, int n)
{
 int i;
 double *rv = (double *)malloc(n * sizeof(double));
 double *rvc = amoeba_center(p, n);

 assert(p);
 assert(*p);
 if(!rv)	return 0;

 for(i=0;i<n;i++)
 	rv[i] = 0.0;

 for(i=0;i<=n;i++)	{
	int j;
	C double *pi = p[i];
	for(j=0;j<n;j++)	{
		C double tmp = pi[j]-rvc[j];
		rv[j] += tmp*tmp;
		}
 	}

 free(rvc);

 for(i=0;i<n;i++)
 	rv[i] = sqrt(rv[i]/n);

 return rv;
}
