function experiments = analyse_results_rmse(bPrintPDF, controlExperiments)
%
%
if nargin < 2
    controlExperiments = analyse_results_control;
end
if nargin < 1
    bPrintPDF = false;
end

resultPath = './../results';
azimuths = controlExperiments(1).azimuths;
experiments = struct('brir', {controlExperiments.brir}, ...
                     'snr', {controlExperiments.snr}, ...
                     'azimuths', azimuths);
nExperiments = numel(experiments);
nAzimuths = length(azimuths);
nMaskerPatterns = 5;
nIDs = 5;
nTrials = nIDs * nMaskerPatterns * nAzimuths;

for ii = 1:nExperiments
    
    fprintf('-- Processing responses for BRIR = %s , SNR = %d dB\n', experiments(ii).brir, experiments(ii).snr);
    allFiles = dir(fullfile(resultPath, sprintf('results_%s_*_snr_%d.txt', experiments(ii).brir, experiments(ii).snr)));
    nSubjects = length(allFiles);
    experiments(ii).nSubjects = nSubjects;
    [experiments(ii).rmseFixed, experiments(ii).rmseMixed] = ...
        deal(zeros(nSubjects, nAzimuths, nMaskerPatterns));
    
    for ss = 1:nSubjects

        % Extract responses for both fixed and mixed masker conditions
        % nTrials x 3: [resp ref maskerPat]
        [rspnFixed, rspnMixed] = deal(zeros(nTrials, 3));
        
        fprintf('   %d/%d: ', ss, nSubjects);
        filename = fullfile(resultPath, allFiles(ss).name);
        fprintf('%s ', filename);
        % read the data
        ifp = fopen(filename,'r');
        data = textscan(ifp,'%d%s%d');
        fclose(ifp);
        names = data{2};
        rspn = data{3};
        cntFixed = 0; cntMixed = 0;
        for rr = 1:length(rspn)
            [runType, tPos, mPat] = parse_file_name(names{rr});
            switch runType
                case 'fixed'
                    cntFixed = cntFixed + 1;
                    rspnFixed(cntFixed,:) = [rspn(rr), tPos, mPat];
                case 'mixed'
                    cntMixed = cntMixed + 1;
                    rspnMixed(cntMixed,:) = [rspn(rr), tPos, mPat];
                case 'fixed_catch'
                    
                case 'mixed_catch'
            end
        end
        fprintf('%d fixed responses and %d mixed responses\n', cntFixed, cntMixed);
        
        % Work out miss rate at each azimith for each masker pattern
        for mPat = 1:nMaskerPatterns
            for tPos = 1:nAzimuths

                azRef = azimuths(tPos);
                
                % Fixed maskers
                idx = (rspnFixed(:,2) == tPos) & (rspnFixed(:,3) == mPat);
                rspn = rspnFixed(idx,1);
                idx = rspn > 0;
                azRspn = azimuths(rspn(idx));
                experiments(ii).rmseFixed(ss,tPos,mPat) = sqrt(mean((azRspn-azRef).^2));
               
                % Mixed maskers
                idx = (rspnMixed(:,2) == tPos) & (rspnMixed(:,3) == mPat);
                rspn = rspnMixed(idx,1);
                idx = rspn > 0;
                azRspn = azimuths(rspn(idx));
                experiments(ii).rmseMixed(ss,tPos,mPat) = sqrt(mean((azRspn-azRef).^2));
                
            end
        end    
    end
    % Subtract control rmse for each subject to show increase RMSE due to
    % maskers
    experiments(ii).rmseIncMixed = bsxfun(@minus, ...
        experiments(ii).rmseMixed, controlExperiments(ii).rmse);
    experiments(ii).rmseIncFixed = bsxfun(@minus, ...
        experiments(ii).rmseFixed, controlExperiments(ii).rmse);
end

% plot it
plotPath = './graphics';
if ~exist(plotPath, 'dir')
    mkdir(plotPath);
end
faceColourList = {[0 0 0], [1 1 1]};
FontSize = 16;
xticks = [-50 0 50];
yticks = 0:10:40;
xmax = 70;
ymax = 45;
maskerMarkerPos = -15;
plotLabelList = {'A)', 'B)', 'C)', 'D)', 'E)', 'F)', 'G)', 'H)', 'I)', 'J)'};

% Plot RMSE
plotFile = fullfile(plotPath, 'kopco_rmse');
open(strcat(plotFile, '.fig'));
%figure

axPosList = cell(nMaskerPatterns*nExperiments, 1);
for ii = 1:nExperiments

    for mPat = 1:nMaskerPatterns
        
        % Plot masker positions
        switch (mPat)
            case 1
                maskerPositions = [1 2 3 4];
            case 2
                maskerPositions = [8 9 10 11];
            case 3
                maskerPositions = [4 5 7 8];
            case 4
                maskerPositions = [1 2 10 11];
            case 5
                maskerPositions = [2 5 7 10];
            otherwise
                maskerPositions = [];
        end
        plotNo = (ii-1)*nMaskerPatterns+mPat;
        subplot(2, nMaskerPatterns, plotNo);
        hold off
        plot(azimuths(maskerPositions), maskerMarkerPos+1, 'MarkerSize',6,'Marker',...
            '^','LineStyle','none','Color',[0 0 0],'MarkerFaceColor',[0 0 0]);
        if ii == 1
            title(sprintf('Pattern %d', mPat), 'FontSize', FontSize, 'FontWeight', 'Normal');
        end

        % Add plot label
        text(4-xmax, ymax-4, plotLabelList{plotNo}, 'FontSize', FontSize);

        % Plot miss rates
        hold on;
        
        AVG = nanmean(experiments(ii).rmseIncMixed(:,:,mPat));
        SEM = nanstd(experiments(ii).rmseIncMixed(:,:,mPat)) ./ sqrt(experiments(ii).nSubjects);
        errorbar(azimuths, AVG, SEM, ...
            'MarkerSize', 8, 'Marker', 'd', 'LineStyle', '-', ...
            'Color',[0 0 0], 'MarkerFaceColor', faceColourList{ii});
    
        AVG = nanmean(experiments(ii).rmseIncFixed(:,:,mPat));
        SEM = nanstd(experiments(ii).rmseIncFixed(:,:,mPat)) ./ sqrt(experiments(ii).nSubjects);
        errorbar(azimuths, AVG, SEM, ...
            'MarkerSize', 8, 'Marker', 's', 'LineStyle', '-', ...
            'Color',[0 0 0], 'MarkerFaceColor', faceColourList{ii});
  
        % Plot a dotted line
        plot([-xmax xmax], [0 0], '--k');
        
        axis([-xmax xmax maskerMarkerPos ymax]);
        if ii == 1
            set(gca,'XTick',xticks,'XTickLabel',{},'FontSize', FontSize);
        else
            set(gca,'XTick',xticks,'XTickLabel',{'-50','0','50'},'FontSize', FontSize);
        end
        set(gca,'YTick',yticks,'YTickLabel',{},'FontSize', FontSize);
        
        axPosList{plotNo} = get(gca, 'Position');
    end
end

% Add labels
subplot(2, nMaskerPatterns, 1);
set(gca,'YTickLabel',yticks,'FontSize', FontSize);
h = ylabel('Increase in RMS Error due to Maskers [\circ]', 'FontSize', FontSize);
set(h,'Position',get(h,'Position') - [5 30 0])

subplot(2, nMaskerPatterns, 6);
set(gca,'YTickLabel',yticks,'FontSize', FontSize);

subplot(2, nMaskerPatterns, 8);
xlabel('Target Azimuth [\circ]', 'FontSize', FontSize);

% Plot legend grid
subplot(2, nMaskerPatterns, nMaskerPatterns);
x1 = -40; x2 = 0; x3 = 35;
y1 = ymax - 6;
%text(x1,y1,'TMR','FontSize', FontSize)
text(x2,y1,'Mixed','FontSize', FontSize)
text(x3,y1,'Fixed','FontSize', FontSize)

x2 = [0 26]; x3 = [36 62];
y2 = ymax - 12;
text(x1,y2,'Dry','FontSize', FontSize)
ii = 1;
plot(x2, [y2 y2], 'k')
plot(mean(x2), y2, 'MarkerSize',8,'Marker','d','LineStyle','-','Color',[0 0 0],'MarkerFaceColor',faceColourList{ii});
plot(x3, [y2 y2], 'k')
plot(mean(x3), y2, 'MarkerSize',8,'Marker','s','LineStyle','-','Color',[0 0 0],'MarkerFaceColor',faceColourList{ii});

y3 = ymax - 18;
text(x1,y3,'Reverb','FontSize', FontSize)
ii = 2;
plot(x2, [y3 y3], 'k')
plot(mean(x2), y3, 'MarkerSize',8,'Marker','d','LineStyle','-','Color',[0 0 0],'MarkerFaceColor',faceColourList{ii});
plot(x3, [y3 y3], 'k')
plot(mean(x3), y3, 'MarkerSize',8,'Marker','s','LineStyle','-','Color',[0 0 0],'MarkerFaceColor',faceColourList{ii});

% Resize subplots
wd = (axPosList{2}(1) - axPosList{1}(1));
ht = (axPosList{1}(2) - axPosList{6}(2) - axPosList{1}(4)) / 2 + axPosList{1}(4);
for n = 1:length(axPosList)
    subplot(2, nMaskerPatterns, n)
    pos = axPosList{n};
    %pos = get(subplotList(m), 'Position');
    if n < 6
        pos(2) = pos(2)-(ht-pos(4));
    end
    pos(3:4) = [wd ht];
    set(gca, 'Position', pos);
end

% Print PDF file
if bPrintPDF
    set(gcf,'Units','inches');
    pos = get(gcf,'Position');
    set(gcf, 'PaperPosition',[0 0 pos(3:4)],'PaperSize', pos(3:4));
    print('-dpdf', strcat(plotFile, '.pdf'));
end

