subject = {'Alina','Angela','Anton','Bob','Carly','Edward','Evan','Joanna', 'Latisha','Laura','Miguel','Norene','Shauna','Teddy','Tony'};
VOWSTIM_LIST={'@','A','E','I','O','R','U','W','Y','a','c','e','i','o','u'};
CONSTIM_LIST={'C','D','G','H','J','S','T','Z','b','d','f','g','h','k','l','m','n','p','r','s','t','v','w','y','z'};

CM_COUNT = 1;
%Load 4 sets of CMs
[CM] = loadcm(subject{1}); %remove the "ID/"

%Remove rows and cols given zero presentations
rowsum = sum(CM{1},2);
for i = 2:CM_COUNT  %JBA: i=1 was done on the previous line
  rowsum=rowsum+sum(CM{i},2);
end %for i=2:SNR_COUNT
KEEP=find(rowsum>0)'; %dont keep when all the rowsums are zero

%JBA: We need a loop over SNRs, but there doesnt seem to be one
%JBA: This sets the SNR for the entropy + stack'ed bar plot
for snr_i = 1:CM_COUNT; %%%SUBJ_SNR{subj}; %maping from subj to snr_i

%Stacked-Errors Bar Plots

%For the next few lines we will compute the total entropy
CM_total = zeros(15,15); % collapse 5 CM's into one

%JBA: snr_i is a flag to indicate an average over all SNRs
if snr_i == 0
    for i=1:SNR_COUNT;
        CM_total = CM_total + CM{i};
    end
else
    CM_total = CM{snr_i};
end %if snr_i == 0

if (0)
    % hack to distribute ? responses uniformly
    for i=1:16
        q = CM_total(i, 17) / 16;
        CM_total(i,17) = 0;
        CM_total(i,1:16) = CM_total(i,1:16) + q;
    end
end

% Finally, compute row entropy
N = sum(CM_total, 2);
Nrep = repmat(N, 1, 15);   % create a normalization matrix for ./

% only keep those consonants that had presentations
%This is now done above, based on row-sums
% tmp = find(N == 0);
% KEEP = [1:16];  % keep all initially
% for i=1:length(tmp);
%     KEEP(find(KEEP == tmp(i))) = '';   % delete if not presented
% end

%Note that the entropy is  computed including the last 17th row, of '?'
Prow = CM_total ./ Nrep; 
Hrow = sum(log2(Prow.^-Prow), 2);  % contains entropy for each row

%Hrow(find(isnan(Hrow))) = 0;

%
fprintf('2^{Entropy} =');
fprintf(' %2.1f', 2.^Hrow); fprintf('\n');

% compute overall response entropy
%Pall = CM_total / sum(sum(CM_total));   % P 
%Hall = sum(sum(log2(Pall.^-Pall)));


tmp = Hrow(KEEP);
tmp = tmp(find(~isnan(tmp)));
Havg = mean(tmp);  % only compute entropy average if presentation > 0.

% make a bar graph
Pe_row = zeros(size(Prow));  %last row for question mark response

pe_order = zeros(15,2);
for i=1:15
    pe = 1 - Prow(i,i);
    pe_order(i,:) = [pe, i];
    Pe_row(i,:) = Prow(i,:);
    Pe_row(i,i) = 0;
end

a = find(isnan(pe_order(:,1)));
pe_order(a, 1) = zeros(length(a), 1);   % remove nan's (xta, xda)

pe_order = pe_order(KEEP, :);

pe_order = sortrows(pe_order);  % comment out to disable sorting of responses
s_order = pe_order(:,2);

figure(1);
bar(Pe_row(s_order, :)*100, 'stack') %CS: 'stacked' instead of 'stack'?

x = 1:length(Pe_row(s_order));
p = sum(Pe_row(s_order,:), 2);
e = sqrt(p.*(1-p)./N(s_order));
hold on
errorbar(x-0.45,p*100,e*100, '.', 'Color', [0,0,0])
hold off


set(gca,'XTick',1:1:length(s_order),'XTickLabel',VOWSTIM_LIST(s_order),'Fontsize',16);
%set(gca,'XDir','reverse');
xlim([0, length(s_order)] + 0.5);
ylim([0, 120])
set(gca,'YTick',0:20:120,'YTickLabel',{0, 20, 40, 60, 80, 100, ''},'Fontsize',16);
xlabel('Ranked-Order Vowels as Stimuli','Fontsize',18);
ylabel('Sum of Confusions in P_e [%]','Fontsize',18);

legend(VOWSTIM_LIST,'Location','NorthEastoutside','Fontsize',14);

%Fix the title to remove the '/'
%subject(3)='-';

if snr_i == 0
    title(subject);
else
    title(sprintf('NSCM %s: Confusion of Vowels in Inital Position ', subject{1}),'Fontsize',18);
end

for x=1:16;
    x2 = find(KEEP == x); % this translates the index in the original data set to the index in the reduced data set
    if isempty(x2)
        continue;
    end
    tok = s_order(x2);  % index translation, x along axis corresonds to a different token due to sorting
    c = cumsum(Pe_row(tok,:));
    large_error = find(Pe_row(tok,:) > 0.10);
    ypos = c(large_error);
    for j=1:length(large_error)
        y = ypos(j);
        txt = sprintf('%2.0f%%', 100*Pe_row(tok, large_error(j)));
        col = [0,0,0];
        if any([1,2,3,4, 15,16 17] - large_error(j) == 0)
            col = [1,1,1];
        end
        
        text(x2,y*100 - 10, txt, 'rotation', 90, 'color', col); 
       
    end
    if ~isnan(Hrow(tok))
        txt = sprintf('%1.3f', Hrow(tok));
    else
        txt = 'NO PRESENT';
    end
    if isnan(c(end))
        c(end) = 0;
    end
    
    text(x2, c(end)*100 + 4, txt, 'rotation', 90);
 end


txt = sprintf('H_{avg} = %2.3f', Havg);
text(1.5, 110, txt, 'FontSize', 16);

if CM_COUNT == 1
    cv_order = 'vowf';
elseif CM_COUNT == 2
    cv_order = 'vowb';
elseif CM_COUNT == 3
    cv_order = 'conf';
elseif CM_COUNT == 4
    cv_order = 'conb';
end

fname = sprintf('stackedbar_%s_%s.eps', subject{1}, cv_order); %name with no SNR
print(gcf, fullfile('graphics', fname), '-depsc2'); %Print stacked barplot
end % for snr_i = 1:SNR_COUNT;