addpath './bin'

subject = {'Alina','Angela','Anton','Bob','Carly','Edward','Evan','Joanna', 'Latisha','Laura','Miguel','Norene','Shauna','Teddy','Tony'};
subject_n = {'Anton','Bob','Carly','Evan','Joanna', 'Miguel'};

VOWSTIM_LIST={'@','A','E','I','O','R','U','W','Y','a','c','e','i','o','u'};
CONSTIM_LIST={'C','D','G','J','S','T','Z','b','d','f','g','h','k','l','m','n','p','r','s','t','v','w','y','z'};
CONSTIM_LIST_ED={'C','D','G','J','S','T','Z','b','d','f','g','h','k','l','m','n','p','s','t','v','w','y','z'}; %Edwards list
CM_COUNT = 4;
CV_ORDER={'vowf', 'vowb', 'conf', 'conb'};

%loop over subjects
for subj_i = 1:length(subject)
    %Load 4 sets of CMs for subject
    [CM] = loadcm( [subject{subj_i} '_updated'] ); % '_updated'
    %Remove Edwards consonant r, since he can't say r
    if strcmp(subject{subj_i}, 'Edward')
        matCMcon= CM{3}
        matCMcon(:,18)=0;        %remove r (set to 0)
        matCMcon(18,:)=0;
        CM{3}=matCMcon;
        matCMcon= CM{4}
        matCMcon(:,18)=0;        %remove r (set to 0)
        matCMcon(18,:)=0;
        CM{4}=matCMcon;
    end
    
    %loop over CMs
    for cm_i = 1:CM_COUNT;
        fname = sprintf('./tex/pruned_%s_%s.tex', subject{subj_i}, CV_ORDER{cm_i});
        if cm_i < 3
            cm2tex(CM{cm_i}, fname, VOWSTIM_LIST, VOWSTIM_LIST, {''})
        else
           cm2tex(CM{cm_i}, fname, CONSTIM_LIST, CONSTIM_LIST, {''})
        end
        %Remove rows and cols given zero presentations
        rowsum = sum( CM{cm_i}, 2);
        KEEP = find( rowsum > 0 )'; %dont keep when the rowsum is zero
        
        %For the next few lines we will compute the total entropy
        CM_total = zeros( size( CM{cm_i} ) );
        CM_total = CM{cm_i};
        
        % Compute row entropy
        N = sum( CM_total, 2 );
        Nrep = repmat( N, 1, length( CM{cm_i} ) );   % create a normalization matrix for ./
        
        Prow = CM_total ./ Nrep;
        wbname = sprintf('%',subject{subj_i});
        wbpath=['CM/',wbname,'.xls'];
        xlswrite(wbpath,Prow,cm_i);
        Hrow = sum(log2(Prow.^-Prow), 2);  % contains entropy for each row
        
        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 );
        sumcorr=0;
        for i=1:length(N)
            sumcorr=sumcorr+CM_total(i,i);
        end
        
        pcmp=1-sumcorr/sum(N);
        
        if cm_i==1
            vowfcmp(subj_i,1)=pcmp;
        elseif cm_i==2
            vowbcmp(subj_i,1)=pcmp;
        elseif cm_i==3
            confcmp(subj_i,1)=pcmp;
        elseif cm_i==4
            conbcmp(subj_i,1)=pcmp;
        end
        
        Pe_row = zeros( size(Prow) );
        
        pe_order = zeros( length( CM{cm_i} ), 2 );
        for i=1:length( CM{cm_i} )
            pe = 1 - Prow(i, i); %prob for error
            pe_order(i, :) = [pe, i]; %list prob for error along with index
            %extract rel errors row by row
            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
        
        pe_order = pe_order( KEEP, : );

        %sort prob for error and their indices
        pe_order = sortrows(pe_order);  % comment out to disable sorting of responses
        s_order = pe_order(:,2); %extract sorted indices
        p = sum(Pe_row(s_order,:), 2);%rowsummed and ascending sorted Pes
        pavg = mean( p );
        e = sqrt(p.*(1-p)./N(s_order)); %confidence: sigma=sqrt(p*q/N)
        
        stackederrorbar_plot(cm_i, subject{subj_i}, CV_ORDER, Pe_row, p, s_order, Hrow, Havg, Hall, e, length(CM{cm_i}), KEEP, VOWSTIM_LIST, CONSTIM_LIST, CONSTIM_LIST_ED)
        
        % export tabel
        err_tbl = cell(length(pe_order),2);
        for i=1:length(pe_order)
            err_tbl(i,1)= strread(num2str(pe_order(i,1)),'%s');
            if cm_i < 3
                err_tbl(i,2)= VOWSTIM_LIST(pe_order(i,2));
            else
                err_tbl(i,2)= CONSTIM_LIST(pe_order(i,2));
            end
        end
        
        sname = sprintf('tbl_%s_%s', subject{subj_i}, CV_ORDER{cm_i});
        oname=['tbl/',sname,'.mat']; %On linux, save the data in a file CM/sname.mat
        save(oname,'err_tbl');
        
        %         oname=['tbl/',sname,'.xls'];
        %         xlswrite(oname,prin1,1,'A1:U16');
        

        
        errorvsentropy_plot(cm_i+CM_COUNT, subject{subj_i}, cm_i, CV_ORDER, N, pe_order, s_order, Hrow, e, VOWSTIM_LIST, CONSTIM_LIST, CONSTIM_LIST_ED)
        
        %Store Data in AVG vectors
        if (cm_i==1 && subj_i==1)
            avg_data = [subj_i cm_i Havg pavg];
        else
            avg_data = [avg_data; subj_i cm_i Havg pavg];
        end
        
        if subj_i == 1
            if cm_i == 1
                vowf_all= [Hrow];
            elseif cm_i == 2
                vowb_all= [Hrow];
            elseif cm_i == 3
                conf_all= [Hrow];
            elseif cm_i == 4
                conb_all= [Hrow];
            end
        else
            if cm_i == 1
                vowf_all= [vowf_all Hrow];
            elseif cm_i == 2
                vowb_all= [vowb_all Hrow];
            elseif cm_i == 3
                conf_all= [conf_all Hrow];
            elseif cm_i == 4
                conb_all= [conb_all Hrow];
            end
        end
        
        
        
        %         %create entropy bar graph
        %         e_order=[tmp (1:length(tmp))'];
        %
        %         a = find( isnan( e_order(:, 1) ) );
        %         e_order(a, 1) = zeros( length(a), 1 );   % remove nan's
        %
        %         %e_order = e_order( KEEP, : );
        %         %sort prob for error and their indices
        %         e_order = sortrows(e_order);  % comment out to disable sorting of responses
        %         i_e_order = e_order(:,2); %extract sorted indices
        %
        %         figure(cm_i + CM_COUNT);
        %         bar( tmp(i_e_order) );
        %
        %         %lable abscissa
        %         if cm_i < 3
        %             set(gca,'XTick',1:1:length(i_e_order),'XTickLabel',VOWSTIM_LIST(s_order),'Fontsize',16);
        %         else
        %             set(gca,'XTick',1:1:length(i_e_order),'XTickLabel',CONSTIM_LIST(s_order),'Fontsize',16);
        %         end
        %         xlim([0, length(i_e_order)] + 0.5);
        %         ylim([0, max(tmp) + 0.2])
        %
        %         %create figure title
        %         if cm_i == 1
        %             title(sprintf('NSCM %s: Entropy of Vowels in Initial Position ', subject{subj_i}),'Fontsize',18);
        %             CV_ORDER{cm_i} = 'vowf';
        %         elseif cm_i == 2
        %             title(sprintf('NSCM %s: Entropy of Vowels in Final Position ', subject{subj_i}),'Fontsize',18);
        %             CV_ORDER{cm_i} = 'vowb';
        %         elseif cm_i == 3
        %             title(sprintf('NSCM %s: Entropy of Consonants in Initial Position ', subject{subj_i}),'Fontsize',18);
        %             CV_ORDER{cm_i} = 'conf';
        %         elseif cm_i == 4
        %             title(sprintf('NSCM %s: Entropy of Consonants in Final Position ', subject{subj_i}),'Fontsize',18);
        %             CV_ORDER{cm_i} = 'conb';
        %         end
        %         txtxlabel = sprintf('Entropy-Ranked-Order %s as Stimuli', CV_ORDER{cm_i});
        %         xlabel(txtxlabel,'Fontsize',18);
        %         ylabel('Entropy [bits]','Fontsize',18);
        %
        %         fname = sprintf('entropy_%s_%s.eps', subject{subj_i}, CV_ORDER{cm_i}); %name with no SNR
        %         print(gcf, fullfile('graphics', fname), '-depsc2'); %Print stacked barplot
        %         if cm_i == 1
        %             tmpall=[tmp];
        %         else
        %             tmpall=[tmpall;tmp];
        %         end
    end % for cm_i = 1:CM_COUNT;
    
end % for subj_i= 1:length(subject)

% Error rates from master files 
load('DataNSCM/mastconf.mat')
load('DataNSCM/mastconb.mat')
load('DataNSCM/mastvowf.mat')
load('DataNSCM/mastvowb.mat')


%mastconf() contains the scores
%Each row is a child (1:15)
%Each Column (1:25) contains the number of correct responses
%Each Column (26:50) contains the number of trials

%sum of correct answers devided by sum of presentations
conf=1-(sum(mastconf(1:15,1:25),2)./sum(mastconf(1:15,26:50),2));
conb=1-(sum(mastconb(1:15,1:25),2)./sum(mastconb(1:15,26:50),2));
vowf=1-(sum(mastvowf(1:15,1:15),2)./sum(mastvowf(1:15,16:30),2));
vowb=1-(sum(mastvowb(1:15,1:15),2)./sum(mastvowb(1:15,16:30),2));
figure(9)
%confvalues=find (avg_data
%confpavg=
bar( [conf, confcmp], 'grouped' );
legend('from master file','from cm');
set(gca,'XTick',1:length(conf),'XTickLabel',subject,'Fontsize',16);
plot(conf, confcmp, 'MarkerSize',8,'Marker','x','LineStyle','none');hold on;
polyf=polyfit(conf,confcmp,1)
x=[0:0.05:0.25];
y=polyval(polyf,x);
plot(x,y);


