function fl = doChordID(testFileList, scratchDir, resultsDir, skip)
% fl = doChordID(testFileList, scratchDir, resultsDir)
%    Perform testing for MIREX08 chord recognition.
%      testFileList is a list of test files
%      scratchDir is the temporary directory where trained models live
%      resultsDir is where to write the per-file results
% 2008-08-21 Dan Ellis dpwe@ee.columbia.edu

% doChordID "/path/to/testFileList.txt" "/path/to/scratchDir" "/path/to/resultsDir"

if nargin < 4; skip = 0; end

% make sure path is OK
if exist('viterbi_path') ~= 2
  addpath('KPMtools');
  addpath('KPMstats');
  addpath('KPMhmm');
end

% Load models
modelfile = fullfile(scratchDir,'MODELS');
load(modelfile); % loads M, txnn

tfl = listfileread(testFileList);

% Calculate features for test item
tstf = calcbeatchroma(testFileList,'','',scratchDir,'-400.mat', skip, 400);
tstf2 = calcbeatchroma(testFileList,'','',scratchDir,'-100.mat', skip, 100);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  test  %%%%%%%%%%%%

for ti = 1:length(tstf)

  % load test data
  [F,B] = loadftrs_mirex(tstf(ti)); % pass a 1 element cell array

  % output file name
  [pathstr,name,ext] = fileparts(tfl{ti});
  opf = fullfile(resultsDir,[name,ext,'.txt']);

  nf = size(F,2);
  luul2 = 25;  % num models

  pp=[];
  % evaluate each frame under all models
  for j = 1:luul2; 
    pp(j,:) = gaussian_prob(F,M(j).mean,M(j).cov); 
  end

  %gt = L;

  %ppn = pp./repmat(sum(pp),luul2,1);
  ppnnn = pp(1:end-1,:)./repmat(sum(pp(1:end-1,:)),luul2-1,1);

  %[vv,xx] = max(ppnnn);

  %disp(['raw classification, no N=',num2str(mean(xx==gt))]);

  %imgsc(ppnnn)
  % find viterbi path
  pth = viterbi_path(ones(1,luul2-1)/luul2-1,txnn,ppnnn);
  %hold on; plot(pth,'-r'); hold off
  
  %noN = (L ~= 25);

  %S = mean(pth(noN)==gt(noN));
  %C = confus(pth(noN),gt(noN));

  %disp(['HMM classification, no N=',num2str(S)]);

  %T = txnn;

  % write output file
  % (write label states as origin-zero)
  rslt = [B',(pth-1)'];
  %save(opf,'-ascii',rslt);
  f = fopen(opf,'w');
  fprintf(f,'%f %d\n',rslt');
  fclose(f);

  disp([datestr(rem(now,1),'HH:MM:SS'), ' song ',num2str(ti),' wrote ', ...
        opf]);


  
end