#define BIG 20000
#define AFAC 1.5
#define AMP 1.5

void fastmeds(short data[], int num, float *med)
{

  int np,nm,j;
  short xx;
  float xp,xm,sum,sumx,eps,stemp,dum,ap,am,aa,a;

  a=*med;
  eps=1;
  am=-(ap=BIG);

  for(;;){

    sum=sumx=0.0;
    np=nm=0;
    xm=-(xp=BIG);

    for(j=0; j<num; j++){
      xx=data[j];
      if(xx!=a){
	if(xx > a){
	  np++;
	  if(xx < xp) xp=xx;
	} else if (xx < a){
	  nm++;
	  if(xx > xm) xm=xx;
	}
	sum+=dum=1.0/(eps+fabs(xx-a));
	sumx+=xx*dum;
      } 
    }

    if(fabs(ap-am)<=5){   /*  modified 2010.8.30   2->5  */ 
      *med=0.5*(ap+am);
      return;
    }

    stemp=(sumx/sum)-a;
    if(np-nm >= 2){
      am=a;
      aa = stemp < 0.0 ? xp : xp+stemp*AMP;
      if(aa > ap) aa=0.5*(a+ap);
      eps = AFAC*fabs(aa-a);
      a=aa;
    } else if (nm-np >= 2){
      ap=a;
      aa = stemp > 0.0 ? xm : xm+stemp*AMP;
      if(aa < am) aa=0.5*(a+am);
      eps = AFAC*fabs(aa-a);
      a=aa;
    } else {
      if(num%2==0){
	*med= 0.5*(np==nm ? xp+xm : np>nm ? a+xp : xm+a);
      } else {
	*med= np == nm ? a : np > nm ? xp : xm;
      }
      return;
    }

  }

}
