function model = model_train_chroma(trnset,ngmm,nsamp,twin,alig);
% model = model_train_chroma(trnset,ngmm,nsamp,twin,alig)
%   trnset is a list (cell array) of data files defining a class
%   ngmm is the number of gaussian components (default 20), 
%   nsamp is the max number of frames to use (randomly selected).
%   twin is the number of successive frames to wrap into a feature.
%   optional alig=1 means to try to transpose-align each dataset
%   model is the model we return with fields mean, sigma, prior, nmix
%   Each record in trnset is row-rotated to make the best total model
%   (transposition alignment).
% 2007-04-03 Dan Ellis dpwe@ee.columbia.edu  artist ID demo system

% How many gaussian components?
if nargin < 2;  ngmm = 1; end
if nargin < 3;  nsamp = 1000; end
if nargin < 4;  twin = 1; end
if nargin < 5;  alig = 0; end

data = load_data(trnset);

if alig
  % Chroma-align
  [mod,offs] = align_chroma(data);

  % Apply rotations
  for i = 1:length(trnset)
    data{i} = chromrot(data{i},offs(i));
  end
else
  % simplified model, just to make sure
  mod = [];
end

% put all data into one matrix for mixgauss_em
dd = [];
for i = 1:length(trnset)
  dd = [dd,data{i}];
end

if size(dd,2) > nsamp
  % random subselection
  ri = randperm(size(dd,2));
  dd = dd(:,ri(1:nsamp));
end

%%%%%%% Apply tcontext %%%%%%%%
dd = addtcontext(dd,twin);

% (Re) build models
if ngmm == 1
%  mm = mod.mean;
%  ss = mod.sigma;
%  [mm,ss] = gaussian_rot_chroma(data, zeros(1,length(data)));
%  pp = 1;
  cov_type = 'full';
  [mm,ss,pp] = mixgauss_em(dd, ngmm, 'cov_type', cov_type);
else
  cov_type = 'diag';
  [mm,ss,pp] = mixgauss_em(dd, ngmm, 'cov_type', cov_type);
end

% Return results
model.mean = mm;
model.sigma = ss;
if ngmm == 1
  model.invsigma = inv(ss);
end
% default single-gauss model for alignment
model.rmodel = mod;
model.prior = pp;
model.nmix = ngmm;
