function [lhood,bestrr] = model_match_chroma(model, data, twin, rrin, rmodel)
% [lhood,bestrr] = model_match_chroma(model, data, twin, rrin, rmodel)
%    Evaluate how well data fits model, returning total log likelihood.
%    All possible row-rotations (chroma transpositions) of data are tried, 
%    best is returned.
%    optional twin specifies number of successive frames to concatenate
%    optional rrin specifies the rotations to use
%    rmodel, if provided, is a single-gauss model used to choose the
%    best rotation.
%    Data can be a cell array, in which case lhood sums up all fields, but 
%    bestrr is a vector.
%    Data is assumed to have one feature vector per COLUMN (sgram-style).
% 2007-04-04

if nargin < 3;  twin = 1; end
if nargin < 4;  rrin = []; end
if nargin < 5;  rmodel =[]; end

if iscell(data)

  % Branch 1: if data is a cell array, decompose and recurse
  
  lhood = 0;
  rrinon = rrin;
  for i = 1:length(data)
    if length(rrin) > 1
      rrinon = rrin(i);
    end
    [lh,rr] = model_match_chroma(model,data{i},twin,rrinon,rmodel);
    lhood = lhood + lh;
    bestrr(i) = rr;
  end
  
else
  
  if length(rrin) == 0
    rrs = 0:(length(model.mean)-1);
  else
    rrs = rrin;
  end
  
  % Maybe use rmodel first?
  if ~isempty(rmodel)

    for rrsix = 1:length(rrs)
    
      rdata = chromrot(data,rrs(rrsix));  % no t-context for rmodel
      % rmodel always single gauss
      lhoods(rrsix) = sum(gaussian_prob_invC(rdata,rmodel.mean,rmodel.invsigma,1));
    end
  
    [lhood,bestrrix] = max(lhoods);
    % fake out remainder by having just one rotation available
    rrs = rrs(bestrrix);
  end
  
  % redo with main model
  lhoods = [];
  for rrsix = 1:length(rrs)
    
    rdata = addtcontext(chromrot(data,rrs(rrsix)), twin);
    % gmm?
    if size(model.mean,2) == 1
      lhoods(rrsix) = sum(gaussian_prob_invC(rdata,model.mean,model.invsigma,1));
    else
      lhoods(rrsix) = sum(log(sum(mixgauss_prob(rdata,model.mean,model.sigma,model.prior))));
    end
  end
  [lhood,bestrrix] = max(lhoods);
  bestrr = rrs(bestrrix);
end