%% plotting Kinematic Error and AI to target location:
clearvars                                                           % redo restructuring for Figure 3
currentFolder = pwd;
addpath(genpath('Matlab_functions'))
path = currentFolder(1:end-8);

tic
CW = [-1,-1,-1,1,1,1,-1,1,1,-1,-1,1,-1,1,-1,1,1,1,-1,-1,-1,1,1,-1];      % -1 no/CCW-CW; 1 yes/CW-CCW 
%% loading in the data:
if exist(sprintf('%s%s%',path,'data\restructured_Fig_3.mat'),'file')==2 
    load(sprintf('%s%s%',path,'data\restructured_Fig_3.mat'))
else
    restructure_fig_3.m
end

%% plotting
%% Loading in the colour matrix:
% col(shade,RGBcode,colour)
[~,col] =DefColours(5,5);
plotcol = [19,7,2,2];

%% ylimits:
YLIM = [-75,50];
YLIMR = [-1.5,1.5];
position = [0 0 18 11];
figure('units','centimeter',...
       'innerposition',position)
set(gca, 'FontName', 'Arial')
%%
out = zeros(2,6); % data points falling out of the plot
ToTN = zeros(2,6); % data points in plot
%% binsize for cluster:
bin = 4;
pmb = floor(bin/2);
%% what force field group: 
ForceFieldGroup = [-1,1];
for block = 0:5
    for group = 1:2
        %% open subplot and store in p1: 
        % 1:6 CWCCW 
        % 7:12 CCWCW 
        % 13:18 AI 
        p1{(group-1)*6+block+1} = subplot(1,18,(group-1)*6+block+1);
        for tt = 0:3
            if block > 0
                %% first plot individual data:
                %% individual data:
                D = Err(CW==ForceFieldGroup(group),:,block+1,tt+1);
                indRaw = ones(size(D)).*[1:length(D)];
                out(group,block+1) = sum(D(:)<YLIM(1))+sum(D(:)>YLIM(2));
                ToTN(group,block+1) = sum(~isnan(D(:)));
                %% mean and SD
                M = nanmean(D);
                indFF1 = find(~isnan(M));
                SD = nanstd(D);
                n = sum(~isnan(D));
                %% plotting 
                % individual data:
                scatter(indRaw(:),D(:),2*ones(size(indRaw(:))),ones(size(indRaw(:))).*[0.6,0.6,0.6],'filled','o','MarkerFaceAlpha',0.25)
                hold on
                % mean +- SE
                patch([indFF1,flip(indFF1)],[M(indFF1)+SD(indFF1)./sqrt(n(indFF1)),flip(M(indFF1)-SD(indFF1)./sqrt(n(indFF1)))],col(1,:,plotcol(tt+1)),'FaceAlpha',0.5,'LineStyle','none')               %plot(nanmean(Err(CW==PossibleGroup(group),1:265,block+1,trialtype+1)),'o','MarkerSize',2,'color',col(1,:,plotcol(trialtype+1)),'MarkerFacecolor',col(1,:,plotcol(trialtype+1)))
                plot(indFF1,M(indFF1),'-','color',col(1,:,plotcol(tt+1)))
             elseif block == 0 && tt == 0
                %% baseline: plot everything together:
               %% individual data:
                D = Err(CW==ForceFieldGroup(group),:,block+1,tt+1);
                indRaw = zeros(size(D)).*[1:length(D)];
                
                %% mean and SD
                M = nanmean(D,'all');
                indFF1 = find(~isnan(M));
                SD = nanstd(nanmean(D,2));
                n = size(D,1);
                %% plotting 
                % individual data:
                scatter(indRaw(:),D(:),2*ones(size(indRaw(:))),ones(size(indRaw(:))).*[0.6,0.6,0.6],'filled','o','MarkerFaceAlpha',0.25)
                hold on
                % mean 
                 scatter(0,M,2,col(1,:,plotcol(tt+1)),'filled','o','MarkerFaceAlpha',1)

               
            end
        end
        

    end
end
fprintf('%.5f%s of datapoints fall out fo the plot\n',sum(out(1,:),'all')/sum(ToTN(1,:),'all')*100,'%')
fprintf('%.5f%s of datapoints fall out fo the plot\n',sum(out(2,:),'all')/sum(ToTN(2,:),'all')*100,'%')
toc
%% AI
TA = 0; % target angle: training anlge
k1 = 55; % window size in A; 
k2 = 5; %window size in B;

m_FF1 = NaN(6,350); % sliding window mean in force field 1
SWSDFF1 = NaN(6,350); % sliding window SD in force field 1
m_FF2_1 = NaN(6,350); % sliding window mean in force field 2, alligned to start
SE_FF2_1 = NaN(6,350);% sliding window SD in force field 2, alligned to start
m_FF2_2 = NaN(6,350); % sliding window mean in force field 2, alligned to end
SE_FF2_2 = NaN(6,350);% sliding window SD in force field 2, alligned to end

%% baseline correction
for block = 1:6
    if ~exist('BL_C','var')
        AI(:,:,block,3) = AI(:,:,block,3)-nanmean(AI(:,:,1,1),2);
        AI(:,:,block,2) = AI(:,:,block,2)-nanmean(AI(:,:,1,1),2);
        AI(:,:,block,1) = AI(:,:,block,1)-nanmean(AI(:,:,1,1),2);
        BL_C = 1;
    end
  
end
%% plotting baseline
block = 0;
p1{13+block} = subplot(1,18,13);
D = AI(:,:,1,1)';
ind_Values = zeros(size(D(:)));
scatter(ind_Values(:),D(:),2*ones(size(ind_Values(:))),ones(size(ind_Values(:))).*[0.25,0.25,0.25],'filled','o','MarkerFaceAlpha',0.25)
hold on
scatter(0,nanmean(D,'all'),2,col(1,:,plotcol(1)),'filled','o','MarkerFaceAlpha',1)

%%
out = zeros(1,6); % data points falling out of the plot
ToTN = zeros(1,6); % data points in plot

for block = 2:6
    p1{13+block-1} = subplot(1,18,13+block-1);
    %% plotting reference lines:
    plot([0,300],[1,1],'-','color',[0,0,0,0.5])
    hold on
    plot([0,300],[-1,-1],'-','color',[0,0,0,0.5])
    
    %% plotting individual data:

    %% first force field
    D1 = AI(:,:,block,2);
    [~,ind_Values] = find(~isnan(D1)); % index of clamp trials in first force field
    D = D1(~isnan(D1)); % AI of clamp trials in first force field
   
    scatter(ind_Values(:),D(:),2*ones(size(ind_Values(:))),ones(size(ind_Values(:))).*[0.25,0.25,0.25],'filled','o','MarkerFaceAlpha',0.25)
    hold on 
    %% datapoints falling out of the plotting limit
    out(block-1) = sum(D(:)<YLIMR(1))+sum(D(:)>YLIMR(2));
    ToTN(block-1) = sum(~isnan(D(:)));
    %% second force field
   
    D2 = AI(:,:,block,3);
    [~,ind_Values] = find(~isnan(D2));
    D = D2(~isnan(D2));   
    scatter(ind_Values(:),D(:),2*ones(size(ind_Values(:))),ones(size(ind_Values(:))).*[0.25,0.25,0.25],'filled','o','MarkerFaceAlpha',0.25)
    

    %% plotting lines:
    
    %% datapoints falling out of the plotting limit
    out(block-1) = out(block-1)+sum(D(:)<YLIMR(1))+sum(D(:)>YLIMR(2));
    ToTN(block-1) = ToTN(block-1)+sum(~isnan(D(:)));
    %% index of different parts: First Force Field
    [~,j] = find(~isnan(AI(:,:,block,2)));
    indFF1 = 1:max(j);
    %% Second Force Field alligned to the start
    [~,j] = find(~isnan(AI(:,:,block,3)));
    indFF2_1 = min(j)+[0:14];
     %% Second Force Field alligned to the end
    indFF2_2 = max(j)-[14:-1:0];
    %% FIRST FORCE FIELD:
    [m_FF1(block,:),SE_FF1(block,:)] = smoothing_AI(indFF1,k1,AI(:,:,block,2),1);
    %% SECOND FORCE FIELD alligned to start:
    [m_FF2_1(block,:),SE_FF2_1(block,:)] = smoothing_AI(indFF2_1,k2,AI(:,:,block,3),1);
    %% SECOND FORCE FIELD alligned to end:
    [m_FF2_2(block,:),SE_FF2_2(block,:)] = smoothing_AI(indFF2_2,k2,AI(:,:,block,3),1);
   
    %% For plotting:
    indA1 = find(~isnan(m_FF1(block,:)));
    indFF2_1 = find(~isnan(m_FF2_1(block,:)));
    indFF2_2 = find(~isnan(m_FF2_2(block,:)));
    %% First force field
    patch([indA1,flip(indA1)],[m_FF1(block,indA1)-SE_FF1(block,indA1),flip(m_FF1(block,indA1)+SE_FF1(block,indA1))],col(1,:,plotcol(2)),'FaceAlpha',0.5,'LineStyle','none')
    plot(indA1,m_FF1(block,indA1),'color',col(1,:,plotcol(2)))
    %% Second force field alligned to start:
    patch([indFF2_1,flip(indFF2_1)],[m_FF2_1(block,indFF2_1)-SE_FF2_1(block,indFF2_1),flip(m_FF2_1(block,indFF2_1)+SE_FF2_1(block,indFF2_1))],col(1,:,plotcol(3)),'FaceAlpha',0.5,'LineStyle','none')
    plot(indFF2_1,m_FF2_1(block,indFF2_1),'color',col(1,:,plotcol(3)))
    %% Second force field alligned to end:
    patch([indFF2_2,flip(indFF2_2)],[m_FF2_2(block,indFF2_2)-SE_FF2_2(block,indFF2_2),flip(m_FF2_2(block,indFF2_2)+SE_FF2_2(block,indFF2_2))],col(1,:,plotcol(3)),'FaceAlpha',0.5,'LineStyle','none')
    plot(indFF2_2,m_FF2_2(block,indFF2_2),'color',col(1,:,plotcol(3)))
   
end
fprintf('%.5f%s of datapoints fall out fo the plot\n',sum(out,'all')/sum(ToTN,'all')*100,'%')

%% for restructuring figure

nR =    3; % rows
nC =   16; % columns
ESw = 30/1920;
Tw = [150/1920, 20/1920, 20/1920+ESw];
Th = [100/1080, 20/1080, 100/1080];
w = (1-sum(Tw.*[1,nC-1,1]))/nC;
h = (1-sum(Th.*[1,nR-1,1]))/nR;

xSPP = Tw(1):(w+Tw(2)):1-w-Tw(3);
%xSPP([3,4]) = xSPP([3,4])+ESw
ySPP = 1-h-Th(3):-(h+Th(2)):Th(1);%linspace(1-h-n/2*Th,n/2*Th,nR);
%% moving the plots around
% for background color
col(:,:,20) = 1;
%            
%%
BG =[20    20    20    20    20    20    20    20   20    20    20    20    20    20    20    20    20    20];
Px =[ 1     2     5     8    11    14     1     2    5     8    11    14     1     2     5     8    11    14];
Py =[ 1     1     1     1     1     1     2     2    2     2     2     2     3     3     3     3     3     3];
Sx =[ 1     3     3     3     3     3     1     3    3     3     3     3     1     3     3     3     3     3];
Sy =[ 1     1     1     1     1     1     1     1    1     1     1     1     1     1     1     1     1     1];
YL ={YLIM YLIM YLIM YLIM YLIM YLIM YLIM YLIM YLIM YLIM YLIM YLIM YLIMR YLIMR YLIMR YLIMR YLIMR YLIMR};
XL ={[-1,1] [0,300] [0,300] [0,300] [0,300] [0,300] [-1,1] [0,300] [0,300] [0,300] [0,300] [0,300] [-1,1] [0,300] [0,300] [0,300] [0,300] [0,300] };
Ylabel = {sprintf('Kinematic Error (%c)',char(0176)) [] [] [] [] [] sprintf('Kinematic Error (%c)',char(0176)) [] [] [] [] [] sprintf('Adaptation Index') [] [] [] [] []}
XT ={[0] [0:100:300]  [0:100:300]  [0:100:300]  [0:100:300]  [0:100:300] [0] [0:100:300]  [0:100:300]  [0:100:300]  [0:100:300]  [0:100:300]  [0] [0:100:300]  [0:100:300]  [0:100:300]  [0:100:300]  [0:100:300] };
YT ={[-50,0,50] [-50,0,50] [-50,0,50] [-50,0,50] [-50,0,50] [-50,0,50] [-50,0,50] [-50,0,50] [-50,0,50] [-50,0,50] [-50,0,50] [-50,0,50] [-1,0,1] [-1,0,1] [-1,0,1] [-1,0,1] [-1,0,1] [-1,0,1]};

XTL ={[] [] [] [] [] [] [] [] [] [] [] [] {'BL'}  {'0'   '100'   '200'   '300'} [] [] [] [] };
YTL ={[-50,0,50] [] [] [] [] [] [[-50,0,50]] [] [] [] [] [] [-1,0,1] [] [] [] [] []};
for i = 1:18
    
    subplot(p1{i})
      ylim(YL{i})
      xlim(XL{i})
      yticks(YT{i})
      xticks(XT{i})
      ylabel(Ylabel{i})
      xticklabels(XTL{i})
      yticklabels(YTL{i})
     
      
     set(p1{i},'position',[xSPP(Px(i)),ySPP(Py(i)),w*Sx(i)+Tw(2)*(Sx(i)-1),h*Sy(i)+Th(2)*(Sy(i)-1)],...
         'FontSize',8,...
         'Color',[col(10,:,BG(i))],...
         'TickLength',[0.02, 0.02]/(Sx(i)+Sy(i)))
   
    
end

p1{13}.YLabel.Position =[-1.8596-0.4 1.4305e-06 -1];
set(gca, 'FontName', 'Arial','FontSize',8)
 %% xlabel    
hxlabel = annotation('textbox',[xSPP(Px(2))+0.015 0.4*Th(1) 0 0],...
    'String','Trial',...
    'EdgeColor','none',...
    'FontName', 'Arial',...
    'FontSize',8,...
    'FitBoxToText','on',...
    'horizontalalignment', 'center',...
    'verticalalignment', 'middle');

% %% ylabel
% AIlabel = annotation('textarrow',...
%     'Position', [0.115 1/6+0.05 0  0],...
%     'HorizontalAlignment','center',...
%     'VerticalAlignment','middle',...
%     'String','Adaptation Index',...
%     'HeadStyle', 'none',...
%     'LineStyle', 'none',...
%     'FontName', 'Arial',...
%     'FontSize',10,...
%     'TextRotation',90);
% 
% 
% %% y2label
% EAlabel2 = annotation('textarrow',...
%     'Position', [0.125    5/6-0.04 0  0],...
%     'HorizontalAlignment','center',...
%     'VerticalAlignment','middle',...
%     'String',sprintf('Kinematic Error (%c)',char(0176)),...
%     'HeadStyle', 'none',...
%     'LineStyle', 'none',...
%     'FontName', 'Arial',...
%     'FontSize',10,...
%     'TextRotation',90);
% % 
% EAlabel = annotation('textarrow',...
%     'Position', [0.125    3/6+0.01 0  0],...
%     'HorizontalAlignment','center',...
%     'VerticalAlignment','middle',...
%     'String',sprintf('Kinematic Error (%c)',char(0176)),...
%     'HeadStyle', 'none',...
%     'LineStyle', 'none',...
%     'FontName', 'Arial',...
%     'FontSize',10,...
%     'TextRotation',90);
%% A B
Alabel = annotation('textbox',[Tw(1)*0.1 ySPP(Py(1))+h 0 0],...
    'String','A',...
    'EdgeColor','none',...
    'FontName', 'Arial',...
    'FontSize',12,...
    'FitBoxToText','on',...
    'horizontalalignment', 'center',...
    'verticalalignment', 'middle');

Blabel = annotation('textbox',[Tw(1)*0.1 ySPP(Py(7))+h 0 0],...
    'String','B',...
    'EdgeColor','none',...
    'FontName', 'Arial',...
    'FontSize',12,...
    'FitBoxToText','on',...
    'horizontalalignment', 'center',...
    'verticalalignment', 'middle');
Clabel = annotation('textbox',[Tw(1)*0.1 ySPP(Py(13))+h 0 0],...
    'String','C',...
    'EdgeColor','none',...
    'FontName', 'Arial',...
    'FontSize',12,...
    'FitBoxToText','on',...
    'horizontalalignment', 'center',...
    'verticalalignment', 'middle');


%% CW CCW CCW CW
CWlabel = annotation('textbox',[xSPP(Px(1))+0.001 ySPP(Py(1)) 0 0],...
    'String','CW-CCW',...
    'FontName', 'Arial',...
    'FontSize',10,...
    'EdgeColor','none',...
    'BackGroundColor','white',...
    'FaceAlpha',0.7,...
    'FitBoxToText','on',...
    'horizontalalignment', 'left',...
    'verticalalignment', 'bottom');

CCWlabel = annotation('textbox',[xSPP(Px(1))+0.001 ySPP(Py(7)) 0 0],...
    'String','CCW-CW',...
    'EdgeColor','none',...
    'BackGroundColor','white',...
    'FaceAlpha',0.7,...
    'FontName', 'Arial',...
    'FontSize',10,...
    'FitBoxToText','on',...
    'horizontalalignment', 'left',...
    'verticalalignment', 'bottom');
%% pooled data 
Plabel = annotation('textbox',[xSPP(Px(1))+0.001 ySPP(Py(13)) 0 0],...
    'String','pooled data',...
    'EdgeColor','none',...
    'BackGroundColor','white',...
    'FaceAlpha',0.7,...
    'FontName', 'Arial',...
    'FontSize',10,...
    'FitBoxToText','on',...
    'horizontalalignment', 'left',...
    'verticalalignment', 'bottom');
%% blocks
for i = 1:5
    
    Blocklabel{i} = annotation('textbox',[xSPP(Px(i+1))+1.7*w 0.96 0 0],...
        'String',sprintf('block %d',i),...
        'EdgeColor','none',...
        'FontName', 'Arial',...
        'FontSize',10,...
        'FitBoxToText','on',...
        'horizontalalignment', 'center',...
        'verticalalignment', 'top');
end


%% saving figure
saveas(gcf,sprintf('%s%s.pdf',path,'Figures\Fig_3'))

