function model = trainBackgroundGmm(y, fs, Ng);

% Train a Gaussian Mixture Model on a sound so that very unlikely
% frames of another sound based on the same background model can be
% assumed to be interesting.

frame = 32;
maxFrames = 1e4;
modelopts = foptions;
covartype = 'full';
if(nargin < 3) Ng = 10; end  % number of gaussians


S = log(abs(specgram(y, frame, fs)));
good = find(isfinite(sum(S)));
Sg = S(:,good);
N = size(Sg, 2)

% If we have too many frames, just take randomly as many as we can
% handle
if(N > maxFrames)
  p = randperm(N);
  p = p(1:maxFrames);
  Sg = Sg(:,p);
end

model = gmm(size(Sg, 1), Ng, covartype)
model = gmminit(model, Sg', modelopts)
model = gmmem(model, Sg', modelopts)
