clear
clc

g=dir('multiplayer*.csv');
pre=dir('prerating*.csv');
post=dir('postrating*.csv');

%get each subject's data by subject id matrix(:, 2), then create new .csv
%with just the matrix from 1 subject

for i = 1:length({g.name})
    g_dat = readtable(g(i).name);
    pre_dat = readtable(pre(i).name); 
    post_dat = readtable(post(i).name);
    dataSort = sortrows(g_dat,2);
    subNames=unique(dataSort(:,2));
    numSubs=height(subNames);
    for j=1:numSubs
        newMat = dataSort(matches(dataSort.participantNum, subNames.participantNum(j)), :);
        cols=newMat.colors(1);
        cols=erase(cols, ["'", "[", "]", ","]);
        ncols=textscan(cols{1},'%s','Delimiter',' ');
        new_pre=pre_dat(matches(pre_dat.participantNum, subNames.participantNum(j)), :);
        new_post=post_dat(matches(post_dat.participantNum, subNames.participantNum(j)), :);
        new_pre(isnan(new_pre.preratingChoice), :)=[];
        new_post=new_post(~isnan(new_post.postratingChoice), :);
        new_post(isnan(new_post.postratingChoice), :)=[];
        prerats=NaN(height(newMat), 1);
        postrats=NaN(height(newMat), 1);
        if ~isempty(new_pre)
            for k=1:6
               prerats(k,1)=new_pre.preratingChoice(matches(new_pre.color, ncols{1}(k)));
               postrats(k,1)=new_post.postratingChoice(matches(new_post.color, ncols{1}(k)));
            end
        end
        newMat.("Pre Ratings") = prerats;
        newMat.("Post Ratings") = postrats;
        writetable(newMat, strcat('sub', num2str(j), '.csv'));
    end
end