% code could be shortened by reducing repetive parts towards the end.

% Revisions made by Jonathan Buie April 31, 2014 New Goal is to reconfigure
% the Confusion Matricies to have a weight to each of the responses by the
% respective judges.  Each subject may have a different number of judges
% determining the results.  So this condition must be checked The team
% decided if one judge heard a correct response then the trial would be
% considered completely correct.

clear all
clc

CONS = {'C','D','G','J','S','T','Z','b','d','f','g','h','k','L','m','n','p','r','s','t','v','w','y','z'};
nCONS = length(CONS);
VOWS = {'@','A','E','I','O','R','U','W','Y','a','c','e','i','o','u'};
nVOWS = length(VOWS);
CON = 1;
VOW = 2;
% offest to con vow depending on position
INI = 2;
FIN = 4;

xlsVOW=cell(nVOWS+1,nVOWS+3);
xlsVOW{1,1} = 'T v \ R >';
xlsVOW(1,2:nVOWS+1) = VOWS;
xlsVOW(1,nVOWS+2:nVOWS+3) = {'Sum Pres', 'Sum Resp'};
xlsVOW(2:nVOWS+1,1) = VOWS';

xlsCON=cell(nCONS+1,nCONS+3);
xlsCON{1,1} = 'T v \ R >';
xlsCON(1,2:nCONS+1) = CONS;
xlsCON(1,nCONS+2:nCONS+3) = {'Sum Pres', 'Sum Resp'};
xlsCON(2:nCONS+1,1) = CONS';

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

%for sbj = SUBJECTS % {'Tony'} -- for only one subject
for sbj = {'Tony'}
    disp(['Working on CMs for ' char(sbj) '...']);
    count = zeros(6,nCONS);
    correct = zeros(6,nCONS);
    % Read in revised log files
    eval(['load(''./reviseddata/DataNSCM_' sbj{:}   '.mat'');'])
    eval(['trails = DataNSCM_' sbj{:} ';']);
    %initialize CMs
    CMs{1} = zeros(nCONS); % cons initial
    CMs{2} = zeros(nCONS); % cons final
    CMs{3} = zeros(nVOWS); % vows initial
    CMs{4} = zeros(nVOWS); % vows final
    corOffs{1} = zeros(1,nCONS); % cons initial
    corOffs{2} = zeros(1,nCONS); % cons final
    corOffs{3} = zeros(1,nVOWS); % vows initial
    corOffs{4} = zeros(1,nVOWS); % vows final
    %count total number of consonants and vowel irrelvant of their poistion
    % count matrix (6x24):
    % - 1st row cons irrelevant of position
    % - 2nd row vows irrelevant of position
    % - 3rd row cons initial
    % - 4th row vows initial
    % - 5th row cons final
    % - 6th row vows final
    for trail_idx = 2 : length(trails)
        % load trail data and save it in variables
        stimulus = trails{trail_idx,4};
        examiner = trails{trail_idx,5};
        transcriber1 = trails{trail_idx,6};
        transcriber2 = trails{trail_idx,7};
        
        % figure out in which CM trail belongs
        for i=1:length(stimulus)
            % consonant or vowel?
            pos = find(strcmp(stimulus(i), CONS));
            if i == 1 % could get rid of this for CMs just take i
                inifin = INI;
            else
                inifin = FIN;
            end
            if isempty(pos) % it is a vowel
                pos = find(strcmp(stimulus(i), VOWS));
                convow = VOW;
            else
                convow = CON;
            end
            % count irrelevant of poistion
            count(convow,pos) = count(convow,pos) + 1;
            % count depending on positon
            count(convow + inifin, pos) = count(convow + inifin,pos) + 1;
            
            if convow == CON
                % choose CM and save it in tmp CM variable
                if inifin == INI
                    CM = CMs{1};
                    corOff = corOffs{1};
                else
                    CM = CMs{2};
                    corOff = corOffs{2};
                end
                stimPos = find(strcmp(stimulus(i),CONS));
                corPos = strfind(examiner,stimulus(i));
                if ~isempty(corPos)
                    corOff(stimPos) = corOff(stimPos) + 1;
                end
                if length(examiner) >= i
                    respPos = find(strcmp(examiner(i),CONS));
                    CM(stimPos, respPos) = CM(stimPos, respPos) + 1;
                end
                % take into account all transcriber
                if  ~sum(isnan(transcriber1))
                    corPos = strfind(transcriber1, stimulus(i));
                    if ~isempty(corPos)
                        corOff(stimPos) = corOff(stimPos) + 1;
                    end
                    if length(transcriber1) >= i
                        respPos = find(strcmp(transcriber1(i),CONS));
                        CM(stimPos, respPos) = CM(stimPos, respPos) + 1;
                    end
                end
                if  ~sum(isnan(transcriber2))
                    corPos = strfind(transcriber2, stimulus(i));
                    if ~isempty(corPos)
                        corOff(stimPos) = corOff(stimPos) + 1;
                    end
                    if length(transcriber2) >= i
                        respPos = find(strcmp(transcriber2(i),CONS));
                        CM(stimPos, respPos) = CM(stimPos, respPos) + 1;
                    end
                end
                % save tmp CM variable
                if inifin == INI
                    CMs{1} = CM;
                    corOffs{1} = corOff;
                else
                    CMs{2} = CM;
                    corOffs{2} = corOff;
                end
            else
                % choose CM and save it in tmp CM variable
                if inifin == INI
                    CM = CMs{3}; %Vowels in Initial Position
                    corOff = corOffs{3};
                    
                else
                    CM = CMs{4}; %Vowels in Final Position
                    corOff = corOffs{4};
                end
                % take into account all transcribers
                stimPos = find(strcmp(stimulus(i),VOWS));
                % Examiner
                corPos = strfind(examiner,stimulus(i));
                if ~isempty(corPos)
                    corOff(stimPos) = corOff(stimPos) + 1;
                end
                if length(examiner) >= i
                    respPos = find(strcmp(examiner(i),VOWS));
                    CM(stimPos, respPos) = CM(stimPos, respPos) + 1; %value here incremented by 1
                end
                % Transcriber 1
                if  ~sum(isnan(transcriber1))
                    corPos = strfind(transcriber1, stimulus(i));
                    if ~isempty(corPos)
                        corOff(stimPos) = corOff(stimPos) + 1;
                    end
                    if length(transcriber1) >= i
                        respPos = find(strcmp(transcriber1(i),VOWS));
                        CM(stimPos, respPos) = CM(stimPos, respPos) + 1;
                    end
                end
                % Transcriber 2
                if  ~sum(isnan(transcriber2))
                    corPos = strfind(transcriber2, stimulus(i));
                    if ~isempty(corPos)
                        corOff(stimPos) = corOff(stimPos) + 1;
                    end
                    if length(transcriber2) >= i;
                        respPos = find(strcmp(transcriber2(i),VOWS));
                        CM(stimPos, respPos) = CM(stimPos, respPos) + 1;
                    end
                end
                % save tmp CM variable
                if inifin == INI
                    CMs{3} = CM;
                    corOffs{3} = corOff;
                else
                    CMs{4} = CM;
                    corOffs{4} = corOff;
                end
            end 
        end
    end
    % Write xls file
    xlsCM = xlsCON;
    xlsCM(2:nCONS+1,2:nCONS+1) = num2cell(CMs{1});
    corOff = corOffs{1};
    for i = [2:nCONS+1]
        diagText = xlsCM{i,i};
        xlsCM(i,i) = cellstr([num2str(diagText) ' (' num2str(corOff(i-1)) ')']);
    end
    nPres = count(CON + INI, :)';
    nResp = sum(CMs{1},2);
    xlsCM(2:nCONS+1,nCONS+2:nCONS+3) = num2cell([nPres nResp]);
    % add precentages
    xlsCM(nCONS+3:2*nCONS+3,1:nCONS+1) = xlsCON(1:nCONS+1,1:nCONS+1);
    CM = CMs{1};
    % replace digonal with corOff
    [m n] = size(CM);
    CM(1:m+1:end) = corOff;
    CM = CM ./ repmat(sum(CM,2),1,size(CM,2));
    CM(isnan(CM)) = 0;
    xlsCM(nCONS+4:2*nCONS+3,2:nCONS+1) = num2cell(CM);
    xlswrite(['xls/' sbj{1} '.xls'],xlsCM,'Cons Initial', 'A1')
  
    xlsCM = xlsCON;
    xlsCM(2:nCONS+1,2:nCONS+1) = num2cell(CMs{2});
    corOff = corOffs{2};
    for i = [2:nCONS+1]
        diagText = xlsCM{i,i};
        xlsCM(i,i) = cellstr([num2str(diagText) ' (' num2str(corOff(i-1)) ')']);
    end
    nPres = count(CON + FIN, :)';
    nResp = sum(CMs{2},2);
    xlsCM(2:nCONS+1,nCONS+2:nCONS+3) = num2cell([nPres nResp]);
    % add precentages
    xlsCM(nCONS+3:2*nCONS+3,1:nCONS+1) = xlsCON(1:nCONS+1,1:nCONS+1);
    CM = CMs{2};
    % replace digonal with corOff
    [m n] = size(CM);
    CM(1:m+1:end) = corOff;
    CM = CM ./ repmat(sum(CM,2),1,size(CM,2));
    CM(isnan(CM)) = 0;
    xlsCM(nCONS+4:2*nCONS+3,2:nCONS+1) = num2cell(CM);
    xlswrite(['xls/' sbj{1} '.xls'],xlsCM,'Cons Final', 'A1')
    
    xlsCM=xlsVOW;
    xlsCM(2:nVOWS+1,2:nVOWS+1) = num2cell(CMs{3});
    corOff = corOffs{3};
    for i = [2:nVOWS+1]
        diagText = xlsCM{i,i};
        xlsCM(i,i) = cellstr([num2str(diagText) ' (' num2str(corOff(i-1)) ')']);
    end
    nPres = count(VOW + INI, 1:nVOWS)';
    nResp = sum(CMs{3},2);
    xlsCM(2:nVOWS+1,nVOWS+2:nVOWS+3) = num2cell([nPres nResp]);
    % add precentages
    xlsCM(nVOWS+3:2*nVOWS+3,1:nVOWS+1) = xlsVOW(1:nVOWS+1,1:nVOWS+1);
    CM = CMs{3};
    % replace digonal with corOff
    [m n] = size(CM);
    CM(1:m+1:end) = corOff;
    CM = CM ./ repmat(sum(CM,2),1,size(CM,2));
    CM(isnan(CM)) = 0;
    xlsCM(nVOWS+4:2*nVOWS+3,2:nVOWS+1) = num2cell(CM);
    xlswrite(['xls/' sbj{1} '.xls'],xlsCM,'Vows Initial', 'A1')
    
    xlsCM=xlsVOW;
    xlsCM(2:nVOWS+1,2:nVOWS+1) = num2cell(CMs{4});
    corOff = corOffs{4};
    for i = [2:nVOWS+1]
        diagText = xlsCM{i,i};
        xlsCM(i,i) = cellstr([num2str(diagText) ' (' num2str(corOff(i-1)) ')']);
    end
    nPres = count(VOW + FIN, 1:nVOWS)';
    nResp = sum(CMs{4},2);
    xlsCM(2:nVOWS+1,nVOWS+2:nVOWS+3) = num2cell([nPres nResp]);
    % add precentages
    xlsCM(nVOWS+3:2*nVOWS+3,1:nVOWS+1) = xlsVOW(1:nVOWS+1,1:nVOWS+1);
    CM = CMs{4};
    % replace digonal with corOff
    [m n] = size(CM);
    CM(1:m+1:end) = corOff;
    CM = CM ./ repmat(sum(CM,2),1,size(CM,2));
    CM(isnan(CM)) = 0;
    xlsCM(nVOWS+4:2*nVOWS+3,2:nVOWS+1) = num2cell(CM);
    xlswrite(['xls/' sbj{1} '.xls'],xlsCM,'Vows Final', 'A1')
    
    % clean up Sheet1-3
    excelFileName = [sbj{1} '.xls'];
    excelFilePath = [pwd '\xls\'];
    sheetName = 'Sheet'; % EN: Sheet, DE: Tabelle, etc. (Lang. dependent)
    
    % Open Excel file
    objExcel = actxserver('Excel.Application');
    objExcel.Workbooks.Open(fullfile(excelFilePath, excelFileName)); % Full path is necessary!
    
    % Delete sheets
    try
        % Throws an error if the sheets do not exist.
        objExcel.ActiveWorkbook.Worksheets.Item([sheetName '1']).Delete;
        objExcel.ActiveWorkbook.Worksheets.Item([sheetName '2']).Delete;
        objExcel.ActiveWorkbook.Worksheets.Item([sheetName '3']).Delete;
    catch
        ; 
    end
    
    % Save, close and clean up.
    objExcel.ActiveWorkbook.Save;
    objExcel.ActiveWorkbook.Close;
    objExcel.Quit;
    objExcel.delete;
    
    % Save CMs in mat file
    save(['mat/' sbj{1} '.mat'],'CMs','corOffs')
end
disp('Done')
