#include <math.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "gpk_std.h"
#include "gpklib.h"
#include "gpkNaN.h"
#include "gpkieee754.h"

#define TYPE int
#define TYPEALLOC int1alloc
#define TYPEFREE int1free
#define ISNAN(x) (x == INT_NAN)


LOCAL int cmp(C void *a, C void *b)
{
 C TYPE *aa = (C TYPE *)a;
 C TYPE *bb = (C TYPE *)b;

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



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

 int i, ii;
 for(i=ii=0; ii<n; ii++)
	if(!ISNAN(xx[ii]))
		x[i++] = xx[ii];

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

 qsort(x, i, sizeof(TYPE), 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]));
 TYPEFREE(x);

 return rv;
}
