// utils.C

#include "Float.H"
#include "utils.H"

namespace xrml {

// samples the discrete pdf w with n components and sum of weights sumw.
// Rescales xi so it will properly lay into the interval [0,1) again.
int SampleDiscretePDF(float *w, int n, float sumw, float *xi)
{
  float x = *xi;
  if (x < 0.) x = 0.;
  if (x > 1.-EPSILON) x = 1.-EPSILON;
  x *= sumw;
  int chosen = 0;
  while (x >= 0. && chosen < n) {
    x -= w[chosen];
    chosen++;
  }
  chosen--;
  x = -x / w[chosen];
  if (x < 0.) x = 0.;
  if (x > 1.-EPSILON) x = 1.-EPSILON;
  *xi = x;
  return chosen;
}

}  // namespace xrml
