

#include "std-dev.h"

extern double  sqrt(double x);

static float square_float(float x)
{
  return(x*x);
}

static float sqrt_float(float x)
{
  return(sqrt(x));
}

FloatImage imStdDev(FloatImage img, int w)
{
  FloatImage isqr,isqrb,ibsqr;
  float *scan,*end,*out;
  float N = 1.0/square_float(2.0*w+1.0), NN = N*N;

  isqr = imDup(img);
  imApplyV(square_float, isqr);
  isqrb = boxFilterFloat(isqr,w,w,w,w);

  ibsqr = boxFilterFloatUsingStorage(img,w,w,w,w,isqr);
  imApplyV(square_float, ibsqr);
  
  scan = imGetStore(ibsqr);
  end = scan+imGetStoreLen(ibsqr);
  out = imGetStore(isqrb);

  for(;scan<end;out++,scan++) {
    *out = *out*N - *scan*NN;
    if(*out<0.0){
      fprintf(stderr,"%10.4f\n",*out);
    }
  }

  imFree(ibsqr);

  imApplyV(sqrt_float,isqrb);
  
  return(isqrb);
}


