function AMT_res = AMT_analysis(Problem, solver)
%%% Automatic Music Transcription results analysis
%   Ivan Damnjanovic 2009
%   
%   If wav file that is transcribed is generated from midi file (i.e. if
%   groundtruth exists) transcription is comapred to the original notes and
%   AMT_res structure is generated. It contains following fields:
%   -   tp_notes - true positive notes (notes corectly transcribed)
%   -   oe_notes - octave errors (erroes due to imperfect pitch estimation)
%   -   fn_notes_wo_oe - false negative notes without octave errors
%                        (notes that were not detected)
%   -   fp_notes_wo_oe - false positive notes without octave erors
%   -   TP - number of true positives
%   -   FN - number of false negatives
%   -   FP - number of false positives

timeOr=Problem.notesOriginal(:,5);
noteOr=Problem.notesOriginal(:,3);
timeTr=solver.reconstructed.notes(:,5);
noteTr=solver.reconstructed.notes(:,3);
n=size(timeOr,1);
m=size(timeTr,1);

%   tolerance (ts) is set to one window before and after the reference offset
%   time

ts=(Problem.windowSize)/Problem.fs;

Hits=[];
OE=[];

for i=1:n
    Hit= find((noteTr(:)==noteOr(i))&(abs(timeOr(i)-timeTr(:))<ts));
    if size(Hit,1)>1 Hit=Hit(1); end
    if ~isempty(Hit) Hits=[Hits; i , Hit];
    else
        OctErr=find(((noteTr(:)==noteOr(i)-12)|(noteTr(:)==noteOr(i)-24))&(abs(timeOr(i)-timeTr(:))<ts), 1);
        if ~isempty(OctErr) OE=[OE; i , OctErr]; end
    end
end

AMT_res.tp_notes = [Problem.notesOriginal(Hits(:,1),[3 5]) solver.reconstructed.notes(Hits(:,2),[3 5])];
AMT_res.oe_notes = [Problem.notesOriginal(OE(:,1),[3 5]) solver.reconstructed.notes(OE(:,2),[3 5])];
AMT_res.fn_notes_wo_oe = Problem.notesOriginal(setdiff([1:n],union(Hits(:,1),OE(:,1))),[3 5]);
AMT_res.fp_notes_wo_oe = solver.reconstructed.notes(setdiff([1:m],union(Hits(:,2),OE(:,2))),[3 5]);
AMT_res.TP=size(Hits,1);
AMT_res.FN=n-AMT_res.TP;
AMT_res.FP=m-AMT_res.TP;
end