%% restructure for figure 3. This file is called in Figure_3.m
%% plotting error angle and AI to target location:
clearvars
OVERWRITE = 1;                                                              % redo restructuring for Figure 3
currentFolder = pwd;
addpath(genpath('Matlab_functions'))
path = currentFolder(1:end-8);

%% loading in the processed AI data:
if ~exist('SU')
    for s = [1:10,12:24]
        clear subject
        file = sprintf('%s%ss%03d.mat',path,'data\processed\',s);
        load(file)
        SU{s} = subject;
    end
end
%% restructuring the data to simplify plotting:
Apos =  unique(SU{1}.TA); % all possible target locations

if exist(sprintf('%s%s%',path,'data\restructured_Fig_4_5.mat'),'file')~=2 || OVERWRITE
    mBL = NaN(24,1); % mean baseline
    %               pp     block   target     trial 
    TA =        NaN(24,    5,      11,        4); % target angle
    ind_trial = NaN(24,    5,      11,        4);
    FF1 =       NaN(24,    5,      11,        4);
    FF2 =       NaN(24,    5,      1,        3);
    SR =        NaN(24,    5,      11,       44); % Spontaneous recovery trials
    for s =[1:10,12:24]
        for b = 0:5
            for  a = 1:11
                if b == 0
                    indBL = find(SU{s}.block == b & SU{s}.TT == 5 & SU{s}.TA == Apos(a));
                    mBL(s,a) = mean(SU{s}.r(indBL));
                else
                    ind_FF1 = find(SU{s}.block == b & SU{s}.TT == 3 & SU{s}.TA == Apos(a)); % index of clamp trials in first force field
                    ind_FF2 = find(SU{s}.block == b & SU{s}.TT == 6 & SU{s}.TA == Apos(a)); % index of clamp trials in second force field

                    TA(s,b,a,:) = SU{s}.TA(ind_FF1);                                        % Target Angle in first force field
                    ind_trial(s,b,a,:) = ind_FF1 - find(SU{s}.block == b,1);                % index relative to the start of the block  
                    FF1(s,b,a,:) = SU{s}.r(ind_FF1)-mBL(s,a);                                % AI values of first force field
                    indSR  = find(SU{s}.TT == 4 & SU{s}.block == b & SU{s}.TA == Apos(a));  %index of the Spontaneous recovery trials
                    I = indSR -  find(SU{s}.TT == 4 & SU{s}.block == b,1)+1;                % index relative to first spontaneous recovery trial trial of that block 
                    SR (s,b,a,I)= SU{s}.r(indSR)-mBL(s,a);   
                    if Apos(a) == 0
                      FF2(s,b,1,:) = SU{s}.r(ind_FF2(end-2:end))' - mBL(s,a);
                    end
                    
                end
            end
        end
    end
    
    
    save(sprintf('%s%s%',path,'data\restructured_Fig_4_5_8.mat'),'TA','FF1','SR','FF2')
end