#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "gpk_std.h"
#include "gpklib/assert.h"
#include "gpklib/innerloop2.h"
#include "gpklib.h"
#include "gpklib/ieee754.h"


LOCAL int d_cmp(C void *a, C void *b)
{
 C double *aa = (C double *)a;
 C double *bb = (C double *)b;

 return *aa>*bb ? 1 : (*aa<*bb ? -1 : 0);
}






double median(C double *xx, int n)
{
 double *x = double1alloc(n);
 assert(x);

 int i = 0;
 INNERLOOP(ii, 0, n, if(!isnan(xx[ii])) x[i++] = xx[ii]);

 if(i == 0)
	return quiet_nan(0);

 qsort(x, i, sizeof(double), d_cmp);
 C double rv =  i%2==1 ? x[i/2] :
			(x[(i-1)/2]==x[i/2] ? x[i/2] : 0.5*(x[(i-1)/2] + x[i/2]));
 double1free(x);

 return rv;
}
