%% restructuring model predictions for figure 8:

clearvars
OVERWRITE = 0;                                                              % redo the BIC Calculation
currentFolder = pwd;
addpath(genpath('Matlab_functions')) 
path = currentFolder(1:end-8); 
data_folder = 'data\processed\';
fits_folder = 'data\fits\';
%%
NS = [1:10,12:24];
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            % -1 no/CCW-CW; 1 yes/CW-CCW
Apos = [360     5    10    15    35    60   300   325   345   350   355];  % possible target angles
%% Loading in the colour matrix:
% col(shade,RGBcode,colour)
[~,col] =DefColours(5,5);

%% restructuring group:
% motion plan based CWCCW 1,2,3,4
Group = NaN(24,1);
BICmb = NaN(24,1);
BICpb = NaN(24,1);
for s = NS
    file = sprintf('%s%sBIC%02d.MAT',path,'data\BIC\',s);
    load(file,'BIC_MB','BIC_PB')
    BICmb(s) = BIC_MB;
    BICpb(s) = BIC_PB;
end
Group(CW' == 1 &BICmb-BICpb<0) =1;    % 1 CW motion based
Group(CW' == -1 &BICmb-BICpb<0) =1;   % 2 CCW motion based 
Group(CW' == 1 &BICmb-BICpb>0) =2;    % 3 CW plan based
Group(CW' == -1 &BICmb-BICpb>0) =2;   % 4 CCW plan based

%% load in the restructured data 
load(sprintf('%s%s%',path,'data\restructured_Fig_8.mat'),'FF2_d_mb_pb','FF1_d_mb_pb','SR_d_mb_pb','Apos')
%% flipping angle and AI:
% flipping AI:
FF1_d_mb_pb(CW == -1,:,:,:,:) = -FF1_d_mb_pb(CW == -1,:,:,:,:);
SR_d_mb_pb(CW == -1,:,:,:,:) = -SR_d_mb_pb(CW == -1,:,:,:,:);
FF2_d_mb_pb(CW == -1,:,:,:,:) = -FF2_d_mb_pb(CW == -1,:,:,:,:);

% flipping angle - +
ind = [1 11 10 9 8 7 6 5 4 3 2];
FF1_d_mb_pb(CW == -1,:,:,:,:) = FF1_d_mb_pb(CW == -1,:,ind,:,:);
SR_d_mb_pb(CW == -1,:,:,:,:) = SR_d_mb_pb(CW == -1,:,ind,:,:);

figure
histogram(Group) % does it make sense to split

%% for plotting
AposPlot = Apos';
AposPlot(Apos >180) = Apos(Apos >180)-360; % for plotting: 300:360 --> -60:0
MM = [2,5]; %% marker size
Icol = [19,7,2,10];% colors to plot in 


%% labels titles etc
%            
%            MB:D:CW                  MB:MP:CW              MB:D:CCW             MB:MP:CCW               PB:D:CW                PB:MP:CW               PB:D:CCW               PB:MP:CCW 
YlabelL  =  {'Adaptation Index',                    [],                    'Adaptation Index',                    [],[], []                    [] []};
Ylim     =  {[-1.7,1.7]               [-1.7,1.7]            [-1.7,1.7]           [-1.7,1.7]              [-1.7,1.7]             [-1.7,1.7]             [-1.7,1.7]             [-1.7,1.7]} ;
Xlim     =  {[-70,70]                 [-70,70]              [-70,70]             [-70,70]                [-70,70]               [-70,70]               [-70,70]               [-70,70]} ;      
Xticks   =  {sort(AposPlot)            sort(AposPlot)         sort(AposPlot)        sort(AposPlot)           sort(AposPlot)          sort(AposPlot)          sort(AposPlot)          sort(AposPlot)};    
XtiLa    =  {{sprintf('-60') sprintf('-35') '' '' '' sprintf('0')  '' ''  '' sprintf('35') sprintf('60')}                     [] [] []};
Yticks   =  {[-1.5:0.5:1.5]           [-1.5:0.5:1.5]        [-1.5:0.5:1.5]       [-1.5:0.5:1.5]          [-1.5:0.5:1.5]         [-1.5:0.5:1.5]         [-1.5:0.5:1.5]         [-1.5:0.5:1.5]};
YtiLa    =  {[-1.5:0.5:1.5]                     []                     [-1.5:0.5:1.5]                     []};    
Xlabel   =  {sprintf('Target Direction (%c)',char(0176))    []                       []                                         []                      []                     []                                     []};
Titles   =  {sprintf('Motion-Referenced \n Data'),... 
            sprintf('Motion-Referenced \n Model'),...
            [],...
            [],...
            sprintf('Plan-Referenced \n Data'),...
            sprintf('Plan-Referenced \n Model'),...
            [],...
            []};
%% plotting
position = [0 0 18 11];
figure('units','centimeter',...
    'innerposition',position)
set(gca, 'FontName', 'Arial','FontSize',8)
out = zeros(2,4); % data points falling out of the plot
ToTN = zeros(2,4); % data points in plot

for g =1:2
    for data_mod = 1:2
        %% D: data vs model predictions 
        d = 1; %% data
        p1{(g-1)*2+data_mod}= subplot(1,4,(g-1)*2+data_mod);
        
        if data_mod == 2 % plotting model:
            if g <=1 % plotting motion referenced
                d = 2;
            else % plotting plan referenced
                d= 3;
            end
        end
        
        %% participant mean
        % plotting mean over trails and blocks per participant for FF1
        D = squeeze(nanmean(FF1_d_mb_pb(Group == g,:,:,4,d),[2,4]));
        plot(AposPlot,D ,'o','Color',col(1,:,Icol(2)),'Markersize',MM(1),'HandleVisibility','off')%,'MarkerFaceColor',col(1,:,7)
        hold on
        if d == 1
            %% checking what falls out of the plot:
            out(g,1) = sum(D(:)<Ylim{(g-1)*2+data_mod}(1))+sum(D(:)>Ylim{(g-1)*2+data_mod}(2));
            ToTN(g,1) = sum(~isnan(D(:)));
            fprintf('%.5f%s of datapoints of FF1 fall out fo the plot\n',sum(out(g,1),'all')/sum(ToTN(g,1),'all')*100,'%')
        end
        % plotting mean over last 22 trails and blocks per participant for SponRec
        D = squeeze(nanmean(SR_d_mb_pb(Group == g,:,:,[23:end],d),[2,4]));
        plot(AposPlot,D ,'o','Color',col(1,:,Icol(4)),'Markersize',MM(1),'HandleVisibility','off')
        if d == 1
            %% checking what falls out of the plot:
            out(g,3) = sum(D(:)<Ylim{(g-1)*2+data_mod}(1))+sum(D(:)>Ylim{(g-1)*2+data_mod}(2));
            ToTN(g,3) = sum(~isnan(D(:)));
            fprintf('%.5f%s of datapoints of final SR fall out fo the plot\n',sum(out(g,3),'all')/sum(ToTN(g,1),'all')*100,'%')
        end
        % plotting mean over first 3 trails and blocks per participant for SponRec
        D =squeeze(nanmean(SR_d_mb_pb(Group == g,:,:,[1:3],d),[2,4]));
        plot(AposPlot, D,'S','Color',col(1,:,Icol(4)),'Markersize',MM(1),'HandleVisibility','off')
        if d == 1
            %% checking what falls out of the plot:
            out(g,4) = sum(D(:)<Ylim{(g-1)*2+data_mod}(1))+sum(D(:)>Ylim{(g-1)*2+data_mod}(2));
            ToTN(g,4) = sum(~isnan(D(:)));
            fprintf('%.5f%s of datapoints of initial SR fall out fo the plot\n',sum(out(g,4),'all')/sum(ToTN(g,1),'all')*100,'%')
        end
        % plotting mean over second force field trials 3 trails and blocks per participant for SponRec
        D = squeeze(nanmean(FF2_d_mb_pb(Group == g,:,:,[3],d),[2,4]));
        plot(0,D ,'o','Color',col(1,:,Icol(3)),'Markersize',MM(1),'HandleVisibility','off')
        if d == 1
            %% checking what falls out of the plot:
            out(g,2) = sum(D(:)<Ylim{(g-1)*2+data_mod}(1))+sum(D(:)>Ylim{(g-1)*2+data_mod}(2));
            ToTN(g,2) = sum(~isnan(D(:)));
            fprintf('%.3f%s of datapoints of FF2 fall out fo the plot\n',sum(out(g,2),'all')/sum(ToTN(g,1),'all')*100,'%')
        end
        %% group mean
        % plotting mean over trails, blocks, and participants for FF1
        plot(AposPlot, squeeze(nanmean(FF1_d_mb_pb(Group == g,:,:,4,d),[1,2,4,5])),'o','Color',col(1,:,Icol(2)),'MarkerFaceColor',col(1,:,Icol(2)),'Markersize',MM(2))%,'MarkerFaceColor',col(1,:,7)
        % mean over second force field 
        plot(0, squeeze(nanmean(FF2_d_mb_pb(Group == g,:,:,[3],d),[1,2,4,5])),'o','Color',col(1,:,Icol(3)),'MarkerFaceColor',col(1,:,Icol(3)),'Markersize',MM(2))
        % plotting mean over last 22 trails, blocks, and participant for SponRec
        plot(AposPlot, squeeze(nanmean(SR_d_mb_pb(Group == g,:,:,[23:end],d),[1,2,4,5])),'o','Color',col(1,:,Icol(4)),'MarkerFaceColor',col(1,:,Icol(4)),'Markersize',MM(2))
        % plotting mean for the last trial of B, blocks, and participant for SponRec
        plot(AposPlot, squeeze(nanmean(SR_d_mb_pb(Group == g,:,:,[1:3],d),[1,2,4,5])),'S','Color',col(1,:,Icol(4)),'MarkerFaceColor',col(1,:,Icol(4)),'Markersize',MM(2))
        %% mean over second force field 
        plot(0, squeeze(nanmean(FF2_d_mb_pb(Group == g,:,:,[3],d),[1,2,4,5])),'o','Color',col(1,:,Icol(3)),'MarkerFaceColor',col(1,:,Icol(3)),'Markersize',MM(2))
        if d == 1
            text(-60,-1.5,sprintf('N = %d',sum(Group == g)),'FontSize',8)
        end
    end

end
 fprintf('%.3f%s of datapoints of MB fall out fo the plot\n',sum(out(1,:),'all')/sum(ToTN(1,:),'all')*100,'%')
 fprintf('%.3f%s of datapoints of PB fall out fo the plot\n',sum(out(2,:),'all')/sum(ToTN(2,:),'all')*100,'%')
 
 for i = 1:4
    
     subplot(1,4,i) 
    
    ylabel(YlabelL{i})
     xlabel(Xlabel{i})
     xlim(Xlim{i})
     ylim(Ylim{i})
     yticks(Yticks{i})
     yticklabels(YtiLa{i})
     xticks(Xticks{i})
     xticklabels(XtiLa{i})
     %title(Titles{i})
     ylim(Ylim{i})
    
 end

%% for restructuring figure
%figure('units','normalized','outerposition',[0 0 1 1])
nR =    2 % rows
nC =    2; % columns
ESw = 30/1920
Tw = [180/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;
%            
%     MB:D          MB:MP               PB:D        PB:MP           PB:D            PB:MP
BG = [20            20                  20          20];
Px = [ 1             2                   1           2];
Py = [ 2             2                   1           1];
Sx = [ 1             1                   1           1];
Sy = [ 1             1                   1           1];
for i = 1:4
     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)],...
         'FontName', 'Arial','FontSize',8,...
         'Color',[col(10,:,BG(i))],...
         'TickLength',[0.02, 0.02]/(Sx(i)+Sy(i)))
    
end
legend('First Force Field','Second Force Field final','Final Spontaneous Recovery','Initial Spontaneous Recovery ','location','SouthEast','FontName', 'Arial','FontSize',8)
legend('boxoff')

%% A B
Alabel = annotation('textbox',[ 0.0094 0.8889 0  0],...
    'String','A',...
    'EdgeColor','none',...
    'FontName', 'Arial','FontSize',12,...
    'FitBoxToText','on',...
    'horizontalalignment', 'center',...
    'verticalalignment', 'middle');

Blabel = annotation('textbox',[0.0094 0.4722 0 0],...
    'String','B',...
    'EdgeColor','none',...
    'FontName', 'Arial','FontSize',12,...
    'FitBoxToText','on',...
    'horizontalalignment', 'center',...
    'verticalalignment', 'middle');

%% Titles
CWlabel = annotation('textbox',[0.0938 0.88 0  0],...
    'String','Plan-Referenced',...
    'EdgeColor','none',...
    'FontName', 'Arial','FontSize',10,...
    'FitBoxToText','on',...
    'horizontalalignment', 'left',...
    'verticalalignment', 'middle');

CCWlabel = annotation('textbox',[0.0938 0.46 0  0],...
    'String','Motion-Referenced',...
    'EdgeColor','none',...
    'FontName', 'Arial','FontSize',10,...
    'FitBoxToText','on',...
    'horizontalalignment', 'left',...
    'verticalalignment', 'middle');

%% Titles

dlabel = annotation('textbox',[xSPP(1)+0.5*w ySPP(1)+h 0 0],...
    'String','Data',...
    'EdgeColor','none',...
    'FontName', 'Arial','FontSize',10,...
    'FitBoxToText','on',...
    'horizontalalignment', 'center',...
    'verticalalignment', 'bottom');

MRmlabel = annotation('textbox',[xSPP(2)+0.5*w ySPP(1)+h 0 0],...
    'String','Model',...
    'EdgeColor','none',...
    'FontName', 'Arial','FontSize',10,...
    'FitBoxToText','on',...
    'horizontalalignment', 'center',...
    'verticalalignment',  'bottom');

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

