%%
clc; clear; close all;
set(0,'DefaultFigureWindowStyle','docked');

%% current set up
% homeXpos = window.innerWidth / 2; %// If you change here, must also change mouseDownFunc dimensions in jspsych-psychophysics.js
% homeYpos = window.innerHeight * 0.85; %// If you change here, must also change mouseDownFunc dimensions in jspsych-psychophysics.js
% homeWidth = window.innerWidth * 0.008; %// If you change here, must also change mouseDownFunc dimensions in jspsych-psychophysics.js
% homeHeight = homeWidth; %// If you change here, must also change mouseDownFunc dimensions in jspsych-psychophysics.js
% 
% % homeCoord =
% % {
% %     x0pos: homeXpos - homeWidth, y0pos: homeYpos - homeHeight,
% %     x1pos: homeXpos + homeWidth, y1pos: homeYpos + homeHeight
% %     };
% 
% targWidth = window.innerWidth * 0.03; %// was 0.08 then 0.4
% targHeight = targWidth;
% 
% %     // try doing location of targets so that the near jump is on a circle - so the distance travelled is the same. expect RT to be minimally affected by the jump
% A = 0.5; %// x position - centre of circle
% B = 0.85; %// y position - centre of circle - must match homeYpos
% r = 0.65; %// radius of circle
% 
% % Mouse moves ~15 cm in 300-400 ms = <= 50 cm.s average but
% equates to ~2100 px.s (629 pix distance home to target centre)
% 629/15 = 41 px per cm
% current jump is 49 px to just over 1 cm in arm movement terms which i
% think is good. 
% could actually shorten distance moved?


%% Import data from text file
% Script for importing data from the following text file:
%
%    filename: /Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_622p_smallCirc.csv
%
% Auto-generated by MATLAB on 18-Mar-2021 11:26:19

%% Setup the Import Options
% opts = delimitedTextImportOptions("NumVariables", 43);
% 
% % Specify range and delimiter
% opts.DataLines = [2, Inf];
% opts.Delimiter = ",";
% 
% % Specify column names and types
% opts.VariableNames = ["rt", "response_type", "key_press", "avg_frame_time", "center_x", "center_y", "CueType", "trial_type", "trial_index", "time_elapsed", "internal_node_id", "subject", "browser_name", "browser_version", "os_name", "os_version", "screen_resolution", "window_resolution", "click_x", "click_y", "CueDirection", "CueHeight", "TrialType", "Staircase", "BlockName", "BlockNo", "Xpos", "Ypos", "IsHome", "ClickX", "ClickY", "TooSoon", "Jitter", "ReactTime", "MoveTimeT1", "MoveTimeT2", "TargetHitT1", "TargetHitT2", "MouseX", "MouseY", "MouseTime", "Outcome", "StopSignalDelay"];
% opts.VariableTypes = ["categorical", "categorical", "categorical", "double", "double", "double", "categorical", "categorical", "double", "double", "string", "double", "categorical", "double", "categorical", "categorical", "categorical", "categorical", "double", "double", "categorical", "categorical", "categorical", "categorical", "categorical", "double", "double", "double", "categorical", "double", "double", "categorical", "double", "double", "double", "double", "categorical", "double", "double", "double", "double", "categorical", "double"];
% opts = setvaropts(opts, 11, "WhitespaceRule", "preserve");
% opts = setvaropts(opts, [12, 38, 39, 40, 41], "TrimNonNumeric", true);
% opts = setvaropts(opts, [12, 38, 39, 40, 41], "ThousandsSeparator", ",");
% opts = setvaropts(opts, [1, 2, 3, 7, 8, 11, 13, 15, 16, 17, 18, 21, 22, 23, 24, 25, 29, 32, 37, 42], "EmptyFieldRule", "auto");
% opts.ExtraColumnsRule = "ignore";
% opts.EmptyLineRule = "read";

% Import the data
%test6
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_54vp_4targ4deg.csv";
% %test 7
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_hagd_4targ4deg.csv";


% For subs 8 and 9 10 and 11
% Setup the Import Options
opts = delimitedTextImportOptions("NumVariables", 50);

% Specify range and delimiter
opts.DataLines = [2, Inf];
opts.Delimiter = ",";

% Specify column names and types
opts.VariableNames = ["rt", "response_type", "key_press", "avg_frame_time", "center_x", "center_y", "CueType", "trial_type", "trial_index", "time_elapsed", "internal_node_id", "subject", "browser_name", "browser_version", "os_name", "os_version", "screen_resolution", "window_resolution", "Targ1Ycent", "Targ2YcentNear", "Targ2YcentFar", "Targ1XLcent", "Targ2XLcent", "Targ1XRcent", "Targ2XRcent", "click_x", "click_y", "CueDirection", "CueHeight", "TrialType", "Staircase", "BlockName", "BlockNo", "Xpos", "Ypos", "IsHome", "ClickX", "ClickY", "TooSoon", "Jitter", "ReactTime", "MoveTimeT1", "MoveTimeT2", "TargetHitT1", "TargetHitT2", "MouseX", "MouseY", "MouseTime", "Outcome", "StopSignalDelay"];
opts.VariableTypes = ["categorical", "categorical", "categorical", "double", "double", "double", "categorical", "categorical", "double", "double", "string", "double", "categorical", "double", "categorical", "categorical", "categorical", "categorical", "double", "double", "double", "double", "double", "double", "double", "double", "double", "categorical", "categorical", "categorical", "categorical", "categorical", "double", "double", "double", "categorical", "double", "double", "categorical", "double", "double", "double", "double", "categorical", "double", "double", "double", "double", "categorical", "double"];
opts = setvaropts(opts, 11, "WhitespaceRule", "preserve");
opts = setvaropts(opts, [12, 45, 46, 47, 48], "TrimNonNumeric", true);
opts = setvaropts(opts, [12, 45, 46, 47, 48], "ThousandsSeparator", ",");
opts = setvaropts(opts, [1, 2, 3, 7, 8, 11, 13, 15, 16, 17, 18, 28, 29, 30, 31, 32, 36, 39, 44, 49], "EmptyFieldRule", "auto");
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
%test 8 - coldiff - white background, green square
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldiff5gjj.csv";

% test 9 - - coldiff - white background, green square - single central target...
%  with left/right small jumps laterally. Still labelled L/R Targets and
%  Near/Far jumps out of laziness, but can essentially collapse across all.
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldiffy9uz.csv";

% test 10 - - coldiff - white background, green square - single central target...
% same as 9 but off centre starting target away from fixation so need to saccade
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldiff8xhd.csv";

% test 11 - - coldiff - white background, green square - single central target...
% same as 9 but shorter distance .55 height - around 12-13cm
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldiffyk4w.csv";

% test 12 - - coldiff - white background, green square - single central target...
% even small target (0.02% width) and 10 deg jump **** First target stayed
% on!!!!! Fast response time - 650 ms
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldifffl1p.csv";

%%%%% test 13 - - coldiff - white background, green square - single central target...
%  small target (0.025% width) and 8 deg jump and central fixation (below
%  target so had to saccade to target at same time as movement)
%  Fast response time - 600 ms
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldiffx4uh.csv";
%%%%-------------13 with small target needing visual guidance seemed to be
%%%%the winner - check again


% test 14 - exact repeat of 13 except longer ITI and target 0.025
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldiffysdn.csv";

% test 15 - exact repeat of 13 except larger (0.028) target
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldiffh3je.csv";

% test 16 - 0.25 targets left and right 3 deg iwth 8deg jump
% Tried to ignore the jumps and just go straight. Min jump time 200 ms
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldiff59qf.csv";

% test 17 - 0.25 targets off-centre (250 deg)  left and right 3 deg iwth 5deg jump
% *** Target moved dynamically instead of jumping
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldiffpq38.csv";

% test 18 - 0.25 targets off-centre (180 deg)  with onle 1 * 10 deg jump
% Point is that the initial movement now doesnt have to be translated...
% but the target jump does (before was other way around)
% fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldiffd3po.csv";

% test 19 - 0.25 targets off-centre (180 deg)  with 2 jumps (up/down) * 10 deg jump
fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_StopChange_Data_smallCirc_coldiff45sl.csv";


%
dataTable = readtable(fileDat, opts);

%% Clear temporary variables
clear opts

%% Bit to get a matrix of mouseX and mouseY coordinates and times
csv = readtable(fileDat);
names = {'MouseX', 'MouseY', 'MouseTime'};
array_outcome = csv{:,'Outcome'};
for i = 1: length(names)
    currentCol = csv.Properties.VariableNames{names(i)};
    array = csv{:,{currentCol}};
    array_cell = array(cellfun(@(x) ~isempty(x),array_outcome));
    array_cell = cellfun(@(x) str2double(strsplit(x,',')),array_cell,'uni',0);
    mouseXYT(:,:,i) = padcat(array_cell{:}); % This function pads the array with NaNs as it concatenates
end

clear csv array_outcome;

%% Index trials
% NaN RT and MT trials == 0
dataTable.ReactTime(dataTable.ReactTime == 0) = NaN;
dataTable.MoveTimeT1(dataTable.MoveTimeT1 == 0) = NaN;
dataTable.MoveTimeT2(dataTable.MoveTimeT2 == 0) = NaN;

% First get rid of rows that don't pertain to the Go/Stop cues
trl_GoStop = dataTable.BlockName == 'MainStopExp' & dataTable.CueType == 'Go/Stop';
dataTable = dataTable(trl_GoStop,:);

% -----------------------------------------------------------------------
% Could reduce the table further for size purposes - take out
% browser_version, ClickX, Jitter,  etc
% Rename trial number?
% -----------------------------------------------------------------------

% Go trials
trl_GoAll = dataTable.BlockName == 'MainStopExp' & dataTable.TrialType == 'Go' & dataTable.TargetHitT1 == 'Left' | ...
    dataTable.BlockName == 'MainStopExp' & dataTable.TrialType == 'Go' & dataTable.TargetHitT1 == 'Right';
trl_GoCorr =  dataTable.BlockName == 'MainStopExp' & dataTable.Outcome == 'Correct_Go' & dataTable.TooSoon == 'false';
trl_GoErr =  dataTable.BlockName == 'MainStopExp' & dataTable.TrialType == 'Go' & dataTable.TargetHitT1 == 'Undefined'; %% Check this works - didn't have any to check
% %--------------------------- Outcome was a mess in first test person, so
% % just look at all trials for now
% trl_GoCorr =  trl_GoAll;
% trl_GoErr =  []; %% Check this works - didn't have any to check


% Stop trials with the Nearpad staircase
trl_StopAll_Str = dataTable.BlockName == 'MainStopExp' & ~isnan(dataTable.StopSignalDelay);
trl_StopCorr_Str = dataTable.BlockName == 'MainStopExp' & dataTable.Outcome == 'Successful_StopChange';
trl_StopFail_Str = dataTable.BlockName == 'MainStopExp' & dataTable.Outcome == 'Failed_Stop';


%% Get basic data
% All RTs and MT1s
RT_GoAll = dataTable.ReactTime(trl_GoAll);
MT1_GoAll = dataTable.MoveTimeT1(trl_GoAll);

% Remove outliers from RTs -
prctile_RT          = prctile(RT_GoAll,[25 75]);
trl_RT_outlier = (dataTable.ReactTime < (prctile_RT(1) - 1.5 * iqr(RT_GoAll)) | ...
    dataTable.ReactTime >(prctile_RT(2)+ 1.5 * iqr(RT_GoAll)) | ...
    dataTable.ReactTime < 100);
dataTable.ReactTime(dataTable.ReactTime < (prctile_RT(1) - 1.5 * iqr(RT_GoAll)) | ...
    dataTable.ReactTime >(prctile_RT(2)+ 1.5 * iqr(RT_GoAll)) | ...
    dataTable.ReactTime < 100) = NaN;
% Remove outliers from MTs - gets complicated because MTs vary if Go and
% Jump
prctile_MT1          = prctile(MT1_GoAll,[25 75]);
trl_MT1_outlier = (dataTable.MoveTimeT1 < (prctile_MT1(1) - 1.5 * iqr(MT1_GoAll)) | ...
    dataTable.MoveTimeT1>(prctile_MT1(2) + 1.5 * iqr(MT1_GoAll)) | ...
    dataTable.MoveTimeT1 < 100);
dataTable.MoveTimeT1(dataTable.MoveTimeT1 < (prctile_MT1(1) - 1.5 * iqr(MT1_GoAll)) | ...
    dataTable.MoveTimeT1>(prctile_MT1(2) + 1.5 * iqr(MT1_GoAll)) | ...
    dataTable.MoveTimeT1 < 100) = NaN;

% Go RT and MT1
RT_GoCorr = dataTable.ReactTime(trl_GoCorr);
RT_GoErr = dataTable.ReactTime(trl_GoErr);
MT1_GoCorr = dataTable.MoveTimeT1(trl_GoCorr);
MT1_GoErr = dataTable.MoveTimeT1(trl_GoErr);
% Correct Stop Change RT and MT2
RT_StopCorr_Jump = dataTable.ReactTime(trl_StopCorr_Str);
MT2_StopCorr_Jump = dataTable.MoveTimeT2(trl_StopCorr_Str);
% Failed Stop Change RT and MT1
RT_StopFail_Jump = dataTable.ReactTime(trl_StopFail_Str);
MT1_StopFail_Jump = dataTable.MoveTimeT1(trl_StopFail_Str);

% Total response times
TotRespT_GoCorr = RT_GoAll + MT1_GoAll;
TotRespT_StopCorr_Jump = RT_StopCorr_Jump + MT2_StopCorr_Jump;
TotRespT_StopFail_Jump = RT_StopFail_Jump + MT1_StopFail_Jump;

% Mean Go RT and MT1
RT_GoCorr_mn = nanmean(RT_GoCorr);
MT1_GoCorr_mn = nanmean(MT1_GoCorr);
% Mean Correct Stop Change RT and MT2
RT_StopCorr_Jump_mn = nanmean(RT_StopCorr_Jump);
MT2_StopCorr_Jump_mn = nanmean(MT2_StopCorr_Jump(MT2_StopCorr_Jump > 100));
% Mean Failed Stop Change RT and MT1
RT_StopFail_Jump_mn = nanmean(RT_StopFail_Jump);
MT1_StopFail_Jump_mn = nanmean(MT1_StopFail_Jump(MT1_StopFail_Jump > 100));

% All SSDs
SSD_Stop_Jump = dataTable.StopSignalDelay(trl_StopAll_Str);

% Mean SSD
SSD_Stop_Jump_mn = nanmean(SSD_Stop_Jump);

% Stop success
pStop_Jump = (sum(trl_StopCorr_Str) / sum(sum([trl_StopCorr_Str,trl_StopFail_Str]))) *100;

%% Calculate SSRT for RTs and MT1s
% Near
if ~isempty(RT_GoErr)
    dataTable.ReactTime(trl_GoErr) = nanmax(RT_GoCorr);
    dataTable.MoveTimeT1(trl_GoErr) = nanmax(MT1_GoCorr);
    RT_GoAll = dataTable.ReactTime(trl_GoAll);% Max Go RT
    MT1_GoAll = dataTable.MoveTimeT1(trl_GoAll);
    TotRespT_GoCorr = RT_GoAll + MT1_GoAll;
end

sort_TotRespT            = sort(TotRespT_GoCorr(~isnan(TotRespT_GoCorr)));
nth_TRT_index_Jump  = round((pStop_Jump/100).*length(sort_TotRespT));
nth_TRT_Jump        = sort_TotRespT(nth_TRT_index_Jump);
SSRT_Jump          = nth_TRT_Jump - SSD_Stop_Jump_mn;


%% Plot RTs and MT1s
figure()

subplot(3,2,1);
histogram(RT_GoCorr,'BinWidth',25, 'Normalization','probability');
hold on
histogram(RT_StopCorr_Jump,'BinWidth',25, 'Normalization','probability');
title('RTs: Go & Succ. Stop');
xlabel('Reaction Times (ms)');
ylabel('Count');
xlim([0,700]);
ylim([0,0.4]);
tx1 = (['Go: ' num2str(round(RT_GoCorr_mn)) 'ms']);
tx2 = (['SS: ' num2str(round(RT_StopCorr_Jump_mn)) 'ms']);
text(40, 0.38,tx1);
text(40, 0.32,tx2);

subplot(3,2,2)
histogram(RT_GoCorr,'BinWidth',25, 'Normalization','probability');
hold on
histogram(RT_StopFail_Jump,'BinWidth',25, 'Normalization','probability');
title('RTs: Go & Fail. Stop');
xlabel('Reaction Times (ms)');
ylabel('Count');
xlim([0,700]);
ylim([0,0.4]);
tx1 = (['Go: ' num2str(round(RT_GoCorr_mn)) 'ms']);
tx2 = (['FS-N: ' num2str(round(RT_StopFail_Jump_mn)) 'ms']);
text(40, 0.38,tx1);
text(40, 0.32,tx2);

subplot(3,2,3)
histogram(MT1_GoCorr,'BinWidth',25, 'Normalization','probability')
hold on
histogram(MT2_StopCorr_Jump,'BinWidth',25, 'Normalization','probability');
title('MTs: Go & Succ. Stopp');
xlabel('Movement Times (ms)');
ylabel('Count');
xlim([0,800]);
ylim([0,0.4]);
tx1 = (['Go MT1: ' num2str(round(MT1_GoCorr_mn)) 'ms']);
tx2 = (['SS MT2: ' num2str(round(MT2_StopCorr_Jump_mn)) 'ms']);
text(20, 0.38,tx1);
text(20, 0.32,tx2);

subplot(3,2,4)
histogram(MT1_GoCorr,'BinWidth',25, 'Normalization','probability')
hold on
histogram(MT1_StopFail_Jump,'BinWidth',25, 'Normalization','probability');
title('MTs: Go & Succ. Stopp');
xlabel('Movement Times (ms)');
ylabel('Count');
xlim([0,800]);
ylim([0,0.4]);
tx1 = (['Go MT1: ' num2str(round(MT1_GoCorr_mn)) 'ms']);
tx2 = (['FS-N MT1: ' num2str(round(MT1_StopFail_Jump_mn)) 'ms']);
text(20, 0.38,tx1);
text(20, 0.32,tx2);

subplot(3,2,5);
histogram(TotRespT_GoCorr,'BinWidth',20, 'Normalization','probability')
hold on
histogram(TotRespT_StopCorr_Jump,'BinWidth',20, 'Normalization','probability')
title('Tot Time: Go & Succ. Stop');
xlabel('Total Times (ms)');
ylabel('Count');
xlim([0,1200]);
ylim([0,0.3]);
tx1 = (['Go TotT: ' num2str(round(nanmean(TotRespT_GoCorr(TotRespT_GoCorr > 500)))) 'ms']);
tx2 = (['SS TotT: ' num2str(round(nanmean(TotRespT_StopCorr_Jump(TotRespT_StopCorr_Jump > 500)))) 'ms']);
text(40, 0.28,tx1);
text(40, 0.22,tx2);


subplot(3,2,6);
histogram(TotRespT_GoCorr,'BinWidth',20, 'Normalization','probability')
hold on
histogram(TotRespT_StopFail_Jump,'BinWidth',20, 'Normalization','probability')
title('Tot Time: Go & Fail. Stopp');
xlabel('Total Times (ms)');
ylabel('Count');
xlim([0,1000]);
ylim([0,0.3]);
tx1 = (['Go: ' num2str(round(nanmean(TotRespT_GoCorr(TotRespT_GoCorr > 500)))) 'ms']);
tx2 = (['FS: ' num2str(round(nanmean(TotRespT_StopFail_Jump(TotRespT_StopFail_Jump > 500)))) 'ms']);
text(40, 0.28,tx1);
text(40, 0.22,tx2);

print(gcf,strcat('Test19_RT_MT1_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

%% Plot stopping staircases
% Need to first calculate pStop at each SSD
% how many SSDs?
SSD_uniq_Jump = unique(SSD_Stop_Jump);
max_ntrls = max(length(SSD_uniq_Jump));

pStop_SSD = NaN(max_ntrls,2);
FailedStop_MT_SSD = NaN(max_ntrls,2);
FailedStop_ToT_SSD = NaN(max_ntrls,2);

% Stair case
for i = 1:length(SSD_uniq_Jump)
    currentSSD = SSD_uniq_Jump(i);
    %     count how many trials for that SSD in that stair case
    idx_all = dataTable.StopSignalDelay(trl_StopAll_Str) == currentSSD;
    nTrls_all = sum(idx_all);
    idx_success = dataTable.BlockName == 'MainStopExp' &  ...
        dataTable.StopSignalDelay == currentSSD & dataTable.Outcome == 'Successful_StopChange';
    nTrls_correct = sum(idx_success);
    pStop_SSD(i,1 ) = (nTrls_correct / nTrls_all) * 100;
    
    idx_fail = dataTable.BlockName == 'MainStopExp'  & ...
        dataTable.StopSignalDelay == currentSSD & dataTable.Outcome == 'Failed_Stop';
    FailedStop_MT_SSD(i,1 ) = nanmean(dataTable.MoveTimeT1(idx_fail));
    FailedStop_ToT_SSD(i,1 ) = nanmean(dataTable.ReactTime(idx_fail) + ...
        dataTable.MoveTimeT1(idx_fail));
end

% 

figure()
plot(dataTable.StopSignalDelay(~isnan(dataTable.StopSignalDelay)),  'b');
lsline;
title('Staircasing','FontSize',14);
xlabel('Trial','FontSize',14);
ylabel('Stop signal delay (ms)','FontSize',14);
% xlim([0,max(SSD_uniq_FarJump)]);
ylim([0,max(SSD_uniq_Jump)]);
print(gcf,strcat('Test19_StaircaseTracking_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

figure()
scatter(SSD_uniq_Jump, pStop_SSD(1:length(SSD_uniq_Jump),1), 50, 'filled', 'b');
hold on
plot([0, max(SSD_uniq_Jump)],[50,50],'--k');
lsline;
title('Stop function','FontSize',14);
xlabel('Stop signal delay (ms)','FontSize',14);
ylabel('Probability of stopping (%)','FontSize',14);
xlim([0,max(SSD_uniq_Jump)]);
ylim([0,100]);
legend('Near','50%','Hfit','Tfit','FontSize',14)
legend boxoff
print(gcf,strcat('Test19_StopFunction_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

figure()
scatter(SSD_uniq_Jump, FailedStop_MT_SSD(1:length(SSD_uniq_Jump),1), 50, 'filled', 'b');
hold on
plot([0, max(SSD_uniq_Jump)],[MT1_GoCorr_mn,MT1_GoCorr_mn],'--k');
lsline;
title('Failed Stop Move Time','FontSize',14);
xlabel('Stop signal delay (ms)','FontSize',14);
ylabel('Failed Stop Move Time (ms)','FontSize',14);
xlim([0,max(SSD_uniq_Jump)]);
ylim([0,450]);
legend('Near','Nfit','Ffit','FontSize',14, 'location', 'SouthEast')
legend boxoff

print(gcf,strcat('Test19_SSD_FSMT1_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

figure()
scatter(SSD_uniq_Jump, FailedStop_ToT_SSD(1:length(SSD_uniq_Jump),1), 50, 'filled', 'b');
hold on
plot([0, max(SSD_uniq_Jump)],[nanmean(TotRespT_GoCorr),nanmean(TotRespT_GoCorr)],'--k');
lsline;
title('Failed Stop Total Time','FontSize',14);
xlabel('Stop signal delay (ms)','FontSize',14);
ylabel('Failed Stop Total Time (ms)','FontSize',14);
xlim([0,max(SSD_uniq_Jump)]);
ylim([0,750]);
legend('Near','Nfit','Ffit','FontSize',14, 'location', 'SouthEast')
legend boxoff

print(gcf,strcat('Test19_SSD_FSToT_StopChange_smallTcirc.pdf'),'-dpdf','-r400');



%% Plot SSRT and mean SSD
figure()
subplot(2,3,1)
bar([RT_GoCorr_mn,0, 0], 'k');
hold on
bar([0,RT_StopCorr_Jump_mn, 0],'b');
bar([0,0, RT_StopFail_Jump_mn], 'r','LineStyle','--');
er = errorbar([1,2,3],[RT_GoCorr_mn,RT_StopCorr_Jump_mn, RT_StopFail_Jump_mn],...
    [nanstd(RT_GoCorr),nanstd(RT_StopCorr_Jump), nanstd(RT_StopFail_Jump)],'k');
er.LineStyle = 'none';
title('React. Time','FontSize',14);
xlabel('Trial','FontSize',14);
xticks([1 2 3])
xticklabels({'Go','SS','FS'})
ylabel('RT (ms)','FontSize',14);
ylim([200,round(RT_GoCorr_mn+100)]);

subplot(2,3,2)
bar([MT1_GoCorr_mn,0, 0], 'k');
hold on
bar([0,MT2_StopCorr_Jump_mn, 0],'b');
bar([0,0, MT1_StopFail_Jump_mn],'r' ,'LineStyle','--');
er = errorbar([1,2,3],[MT1_GoCorr_mn, MT2_StopCorr_Jump_mn,MT1_StopFail_Jump_mn],...
    [nanstd(MT1_GoCorr), nanstd(MT2_StopCorr_Jump), nanstd(MT1_StopFail_Jump)],'k');
er.LineStyle = 'none';
title('Move. Time','FontSize',14);
xlabel('Trial','FontSize',14);
xticks([1 2 3])
xticklabels({'Go','SS','FS'})
ylabel('MT1 (ms)','FontSize',14);
ylim([200,round(MT2_StopCorr_Jump_mn + 120)]);

subplot(2,3,3)
bar([nanmean(TotRespT_GoCorr),0, 0], 'k');
hold on
bar([0,nanmean(TotRespT_StopCorr_Jump), 0],'b');
bar([0,0, nanmean(TotRespT_StopFail_Jump)], 'r','LineStyle','--');
er = errorbar([1,2,3],[nanmean(TotRespT_GoCorr),nanmean(TotRespT_StopCorr_Jump),nanmean(TotRespT_StopFail_Jump)],...
    [nanstd(TotRespT_GoCorr),nanstd(TotRespT_StopCorr_Jump), nanstd(TotRespT_StopFail_Jump)],'k');
er.LineStyle = 'none';
title('Total Time','FontSize',14);
xlabel('Trial','FontSize',14);
xticks([1 2 3 ])
xticklabels({'Go','SS','FS'})
ylabel('Total Time (ms)','FontSize',14);
ylim([500,round(nanmean(TotRespT_StopCorr_Jump)+120)]);

subplot(2,3,4)
bar(pStop_Jump, 'b');
title('pStop','FontSize',14);
ylabel('pStop (%)','FontSize',14);
ylim([0,100]);

subplot(2,3,5)
bar(SSD_Stop_Jump_mn, 'b');
title('SSD','FontSize',14);
ylabel('SSD (ms)','FontSize',14);
ylim([0,round(SSD_Stop_Jump_mn+20)]);

subplot(2,3,6)
bar(SSRT_Jump, 'b');
title('SSRT','FontSize',14);
ylabel('SSRT (ms)','FontSize',14);
ylim([0,round(SSRT_Jump+20)]);

print(gcf,strcat('Test19_MeanBehav_StopChange_smallTcirc.pdf'),'-dpdf','-r400');


%% Analyse mouse movements
% want to index the time point/column number when the mouse entered the box
% so that we're not looking at all the junk after.
% need a way that captures all trials and the different maximums and times
% that they move for.
% For got trials, can use the min Y value, but this won't work for
% Far/reversal trials since it will cut it off
mouseX = mouseXYT(:,:,1);
mouseY = mouseXYT(:,:,2);
mouseT = mouseXYT(:,:,3);

TotRespT_T1_all = round(dataTable.ReactTime + dataTable.MoveTimeT1);
col_overTRT = mouseT > TotRespT_T1_all;

mouseX(col_overTRT)= NaN;
mouseY(col_overTRT)= NaN;
mouseT(col_overTRT)= NaN;
% Doing this because some of the onset timings seem out by far - e.g. 8 ms, 48 ms.
% Some also are unaliged with RT by +/-17 ms which is fine. But there are a
% bunch that are just not correlated at all
% see: scatter(mouseT(:,1), dataTable.ReactTime(:))
mouseT_alignRT = mouseT;
trl_mouseT_RT_out = mouseT(:,1) > dataTable.ReactTime + (2 * 17) | mouseT(:,1) < dataTable.ReactTime - (2 * 17);
mouseT_alignRT = mouseT_alignRT - (mouseT_alignRT(:,1)) + dataTable.ReactTime;
% Time normalise mouseT to 100%
min_mouseT = min(mouseT_alignRT');
max_mouseT = max(mouseT_alignRT') - min_mouseT;
mouseT_alignRT_norm = bsxfun(@minus, mouseT_alignRT, min_mouseT');
mouseT_alignRT_norm = bsxfun(@rdivide, mouseT_alignRT_norm, max_mouseT');
mouseT_alignRT_norm = mouseT_alignRT_norm .* 100;

% ------------------- Think this actually needs to be movetime in mouseT
% ------------------- OR print out target Y in the experiment and use that
[Yval,Yloc] = min(mouseY');

figure()
for i = 1:size(mouseX,1)
    if dataTable.Outcome(i) == 'Correct_Go'
        final_datpoint = Yloc(i);
        color = 'g';
    elseif dataTable.Outcome(i) == 'Successful_StopChange' 
        final_datpoint = Yloc(i);
        color = 'b';
    elseif dataTable.Outcome(i) == 'Failed_Stop'
        final_datpoint = Yloc(i);
        color = 'r';
    end
    
    mouseMove3d = plot3(mouseX(i,1:final_datpoint), mouseY(i,1:final_datpoint),...
        mouseT_alignRT(i,1:final_datpoint), color);
    hold on
end
xlabel('Horizontal (px)','FontSize',14)
ylabel('Vertical (px)','FontSize',14)
zlabel('Time from go (ms)','FontSize',14)
view(220,45)

print(gcf,strcat('Test19_Trajectory3d_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

view(0,270)
print(gcf,strcat('Test19_Trajectory2dXY_StopChange_smallTcirc.pdf'),'-dpdf','-r400');



% Averaged 3d plot
% ---------------------------------------------------------
% Separate out positions and correct for different X directions
startPos_mouseX_mn = nanmean(mouseX(:,1)); 

% Go
trl_GoCorr_left =  dataTable.BlockName == 'MainStopExp' & dataTable.Outcome == 'Correct_Go' ...
    & dataTable.TooSoon == 'false' & dataTable.CueDirection == 'Left';
trl_GoCorr_right =  dataTable.BlockName == 'MainStopExp' & dataTable.Outcome == 'Correct_Go' ...
    & dataTable.TooSoon == 'false' & dataTable.CueDirection == 'Right';

% Stop
trl_StopCorr_Str_left = dataTable.BlockName == 'MainStopExp'  ...
    & dataTable.Outcome == 'Successful_StopChange' & dataTable.CueDirection == 'Left';
trl_StopCorr_Str_right = dataTable.BlockName == 'MainStopExp' ...
    & dataTable.Outcome == 'Successful_StopChange' & dataTable.CueDirection == 'Right';
trl_StopFail_Str_left = dataTable.BlockName == 'MainStopExp' ...
    & dataTable.Outcome == 'Failed_Stop' & dataTable.CueDirection == 'Left';
trl_StopFail_Str_right = dataTable.BlockName == 'MainStopExp' ...
    & dataTable.Outcome == 'Failed_Stop' & dataTable.CueDirection == 'Right';


mouseX_GoCorr_left = nanmean(mouseX(trl_GoCorr_left,:));
mouseX_GoCorr_right = nanmean(mouseX(trl_GoCorr_right,:));

mouseX_StopCorr_Jump_left = nanmean(mouseX(trl_StopCorr_Str_left,:));
mouseX_StopCorr_Jump_right = nanmean(mouseX(trl_StopCorr_Str_right,:));


mouseX_StopFail_Jump_left = nanmean(mouseX(trl_StopFail_Str_left,:));
mouseX_StopFail_Jump_right = nanmean(mouseX(trl_StopFail_Str_right,:));

mouseY_GoCorr_left = nanmean(mouseY(trl_GoCorr_left,:));
mouseY_GoCorr_right = nanmean(mouseY(trl_GoCorr_right,:));

mouseY_StopCorr_Jump_left = nanmean(mouseY(trl_StopCorr_Str_left,:));
mouseY_StopCorr_Jump_right = nanmean(mouseY(trl_StopCorr_Str_right,:));

mouseY_StopFail_Jump_left = nanmean(mouseY(trl_StopFail_Str_left,:));
mouseY_StopFail_Jump_right = nanmean(mouseY(trl_StopFail_Str_right,:));


mouseT_GoCorr_left = nanmean(mouseT(trl_GoCorr_left,:));
mouseT_GoCorr_right = nanmean(mouseT(trl_GoCorr_right,:));

mouseT_StopCorr_Jump_left = nanmean(mouseT(trl_StopCorr_Str_left,:));
mouseT_StopCorr_Jump_right = nanmean(mouseT(trl_StopCorr_Str_right,:));

mouseT_StopFail_Jump_left = nanmean(mouseT(trl_StopFail_Str_left,:));
mouseT_StopFail_Jump_right = nanmean(mouseT(trl_StopFail_Str_right,:));

frameRate = nanmean(dataTable.avg_frame_time);

figure()
plot3(mouseX_GoCorr_left(1,1:round(MT1_GoCorr_mn./frameRate)), ...
    mouseY_GoCorr_left(1,1:round(MT1_GoCorr_mn./frameRate)),...
    mouseT_GoCorr_left(1,1:round(MT1_GoCorr_mn./frameRate)),'g','LineWidth',2);
hold on
plot3(mouseX_GoCorr_right(1,1:round(MT1_GoCorr_mn./frameRate)),...
    mouseY_GoCorr_right(1,1:round(MT1_GoCorr_mn./frameRate)),...
    mouseT_GoCorr_right(1,1:round(MT1_GoCorr_mn./frameRate)),'g','LineWidth',2);

plot3(mouseX_StopCorr_Jump_left(1,1:round(MT2_StopCorr_Jump_mn./frameRate)), ...
    mouseY_StopCorr_Jump_left(1,1:round(MT2_StopCorr_Jump_mn./frameRate)),...
    mouseT_StopCorr_Jump_left(1,1:round(MT2_StopCorr_Jump_mn./frameRate)),'b','LineWidth',2);
plot3(mouseX_StopCorr_Jump_right(1,1:round(MT2_StopCorr_Jump_mn./frameRate)),...
    mouseY_StopCorr_Jump_right(1,1:round(MT2_StopCorr_Jump_mn./frameRate)),...
    mouseT_StopCorr_Jump_right(1,1:round(MT2_StopCorr_Jump_mn./frameRate)),'b','LineWidth',2);

plot3(mouseX_StopFail_Jump_left(1,1:round(MT1_StopFail_Jump_mn./frameRate)), ...
    mouseY_StopFail_Jump_left(1,1:round(MT1_StopFail_Jump_mn./frameRate)),...
    mouseT_StopFail_Jump_left(1,1:round(MT1_StopFail_Jump_mn./frameRate)),'r','LineWidth',2);
plot3(mouseX_StopFail_Jump_right(1,1:round(MT1_StopFail_Jump_mn./frameRate)),...
    mouseY_StopFail_Jump_right(1,1:round(MT1_StopFail_Jump_mn./frameRate)),...
    mouseT_StopFail_Jump_right(1,1:round(MT1_StopFail_Jump_mn./frameRate)),'r','LineWidth',2);


xlabel('Horizontal (px)','FontSize',14)
ylabel('Vertical (px)','FontSize',14)
zlabel('Time from go (ms)','FontSize',14)

view(180,0)
print(gcf,strcat('Test19_Trajectory2dXZ_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

view(90,0)
print(gcf,strcat('Test19_Trajectory2dYZ_StopChange_smallTcirc.pdf'),'-dpdf','-r400');



%% Plot velocities for all conditions

% Calculate lateral (X) velocity in px.s
mouseX_GoCorr = mouseXYT(trl_GoCorr,:, 1);
mouseX_StopCorr_Jump = mouseXYT(trl_StopCorr_Str,:, 1);
mouseX_StopFail_Jump = mouseXYT(trl_StopFail_Str,:, 1);

mouseXdiff_GoCorr = diff(mouseX_GoCorr,1,2);
mouseXvel_GoCorr = abs(mouseXdiff_GoCorr./(frameRate/1000));
[xVelvalCorrGo, xVellocCorrGo] = max(mouseXvel_GoCorr');

mouseXdiff_StopCorr_Jump = diff(mouseX_StopCorr_Jump,1,2);
mouseXvel_StopCorr_Jump = abs(mouseXdiff_StopCorr_Jump./(frameRate/1000));
% mouseXvel_StopCorr_NearJump = (mouseXdiff_StopCorr_NearJump./(frameRate/1000));
[xVelvalCorr, xVellocCorr] = max(mouseXvel_StopCorr_Jump');

mouseXdiff_StopFail_Jump = diff(mouseX_StopFail_Jump,1,2);
mouseXvel_StopFail_Jump = abs(mouseXdiff_StopFail_Jump./(frameRate/1000));
[xVelvalFail, xVellocFail] = max(mouseXvel_StopFail_Jump');


% average X velocity and time of the peak velocity? expect later time of peak
% velocity for failed stops reflecting later change of direction
meanStopCue_MoveOn =  MT1_GoCorr_mn - SSRT_Jump;

figure();
plot((0:17:17*size(mouseXvel_GoCorr,2)-1),nanmean(mouseXvel_GoCorr),'-g')
hold on
plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0, 1000],'--k')
plot([0,0],[0, 1000],'-k')
plot([MT1_GoCorr_mn,MT1_GoCorr_mn],[0,1000],'.-k')
plot((0:17:17*size(mouseXvel_StopCorr_Jump,2)-1),nanmean(mouseXvel_StopCorr_Jump),'-b')
plot((0:17:17*size(mouseXvel_StopFail_Jump,2)-1),nanmean(mouseXvel_StopFail_Jump),'-r')
plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0,1000],'-k')
nanmean(TotRespT_GoCorr)
legend('Go','Stop','MoveOn','MoveEnd','SS','FS','location','NorthWest','FontSize',14);
xlabel('Time from movement onset (ms)','FontSize',14);
ylabel('X velocity (px.s)','FontSize',14);
xlim([-100, MT1_GoCorr_mn + 100]);
% ylim([0, 200]);
text(meanStopCue_MoveOn +10, 500, 'Stop','FontSize',14,'Rotation', -90);
text(MT1_GoCorr_mn +10, 500, 'Target Hit','FontSize',14,'Rotation', -90);
print(gcf,strcat('Test19_VelocityAbsX_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

% Calculate vertical (Y) velocity in px.s
mouseY_GoCorr = mouseXYT(trl_GoCorr,:, 2);
mouseY_StopCorr_Jump = mouseXYT(trl_StopCorr_Str,:, 2);
mouseY_StopFail_Jump = mouseXYT(trl_StopFail_Str,:, 2);

mouseYdiff_GoCorr = diff(mouseY_GoCorr,1,2);
% mouseYvel_GoCorr = -(mouseYdiff_GoCorr./(frameRate/1000));
mouseYvel_GoCorr = abs(mouseYdiff_GoCorr./(frameRate/1000)); % for the horizontal mvoement with verytical jump
[yVelvalCorrGo, yVellocCorrGo] = max(mouseYvel_GoCorr');

mouseYdiff_StopCorr_Jump = diff(mouseY_StopCorr_Jump,1,2);
% mouseYvel_StopCorr_Jump = -(mouseYdiff_StopCorr_Jump./(frameRate/1000));
mouseYvel_StopCorr_Jump = abs(mouseYdiff_StopCorr_Jump./(frameRate/1000));
[yVelvalCorr, yVellocCorr] = max(mouseYvel_StopCorr_Jump');

mouseYdiff_StopFail_Jump = diff(mouseY_StopFail_Jump,1,2);
% mouseYvel_StopFail_Jump = -(mouseYdiff_StopFail_Jump./(frameRate/1000));
mouseYvel_StopFail_Jump = abs(mouseYdiff_StopFail_Jump./(frameRate/1000));
[yVelvalFail, yVellocFail] = max(mouseYvel_StopFail_Jump');


figure();
plot((0:17:17*size(mouseYvel_GoCorr,2)-1),nanmean(mouseYvel_GoCorr),'-g')
hold on
plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[-2000, 2000],'--k')
plot([0,0],[-2000, 2000],'-k')
plot([MT1_GoCorr_mn,MT1_GoCorr_mn],[-2000,2000],'.-k')
plot((0:17:17*size(mouseYvel_StopCorr_Jump,2)-1),nanmean(mouseYvel_StopCorr_Jump),'-b')
plot((0:17:17*size(mouseYvel_StopFail_Jump,2)-1),nanmean(mouseYvel_StopFail_Jump),'-r')

legend('Go','Stop','MoveOn','MoveEnd','SS','FS','location','NorthWest','FontSize',14);
xlabel('Time from movement onset (ms)','FontSize',14);
ylabel('Y velocity (px.s)','FontSize',14);
xlim([-100, MT1_GoCorr_mn + 100]);
ylim([0,300]);
text(meanStopCue_MoveOn +10, 100, 'Stop','FontSize',14,'Rotation', -90);
text(MT1_GoCorr_mn +10, 200, 'Target Hit','FontSize',14,'Rotation', -90);
print(gcf,strcat('Test19_VelocityAbsY_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

figure();
plot((0:17:17*size(mouseYvel_GoCorr,2)-1),nanmean(mouseYvel_GoCorr)-nanmean(mouseYvel_StopCorr_Jump),'-b')
hold on
plot((0:17:17*size(mouseYvel_GoCorr,2)-1),nanmean(mouseYvel_GoCorr)-nanmean(mouseYvel_StopFail_Jump),'-r')
xlim([0, 300]);


% Peak Y velocity
figure()
subplot(2,2,1)
bar([nanmean(yVelvalCorrGo),0, 0], 'k');
hold on
bar([0,nanmean(yVelvalCorr), 0],'b');
bar([0,0, nanmean(yVelvalFail)], 'r', 'LineStyle', '--');
er = errorbar([1,2,3],[nanmean(yVelvalCorrGo),nanmean(yVelvalCorr),nanmean(yVelvalFail)],...
    [nanstd(yVelvalCorrGo),nanstd(yVelvalCorr), nanstd(yVelvalFail)],'k');
er.LineStyle = 'none';
title('Peak Y velocity','FontSize',14);
xlabel('Trial Type','FontSize',14);
xticks([1 2 3])
xticklabels({'Go','SS','FS'})
ylabel('Y velocity (px.s)','FontSize',14);
ylim([0,round(nanmean(yVelvalCorrGo)+1000)])

% Time of peak Y velocity
subplot(2,2,2)
bar([nanmean(yVellocCorrGo),0,0] * frameRate, 'k');
hold on
bar([0,nanmean(yVellocCorr), 0] * frameRate,'b');
bar([0,0, nanmean(yVellocFail)] * frameRate, 'r', 'LineStyle', '--');
er = errorbar([1,2,3],[nanmean(yVellocCorrGo) * frameRate,nanmean(yVellocCorr) * frameRate, ...
    nanmean(yVellocFail) * frameRate,],...
    [nanstd(yVellocCorrGo) * frameRate,nanstd(yVellocCorr) * frameRate, ...
    nanstd(yVellocFail) * frameRate],'k');
er.LineStyle = 'none';
title('Time to peak Y velocity','FontSize',14);
xlabel('Trial Type','FontSize',14);
xticks([1 2 3 4 5])
xticklabels({'Go','SS','FS'})
ylabel('Time (ms)','FontSize',14);
% ylim([0,round(nanmean(yVellocCorrGo * frameRate)+100)])

% Peak X velocity
subplot(2,2,3)
bar([nanmean(xVelvalCorrGo),0, 0], 'k');
hold on
bar([0,nanmean(xVelvalCorr), 0],'b');
bar([0,0, nanmean(xVelvalFail)], 'r', 'LineStyle', '--');
er = errorbar([1,2,3],[nanmean(xVelvalCorrGo),nanmean(xVelvalCorr),nanmean(xVelvalFail)],...
    [nanstd(xVelvalCorrGo),nanstd(xVelvalCorr),nanstd(xVelvalFail)],'k');
er.LineStyle = 'none';
title('Peak X velocity','FontSize',14);
xlabel('Trial Type','FontSize',14);
xticks([1 2 3 4 5])
xticklabels({'Go','SS','FS'})
ylabel('X velocity (px.s)','FontSize',14);
ylim([0,round(nanmean(xVelvalCorrGo)+1000)])

% Time of peak X velocity
subplot(2,2,4)
bar([nanmean(xVellocCorrGo),0, 0] * frameRate, 'k');
hold on
bar([0,nanmean(xVellocCorr), 0] * frameRate,'b');
bar([0,0, nanmean(xVellocFail)] * frameRate, 'r', 'LineStyle', '--');
er = errorbar([1,2,3],[nanmean(xVellocCorrGo) * frameRate,nanmean(xVellocCorr) * frameRate,...
    nanmean(xVellocFail) * frameRate],...
    [nanstd(xVellocCorrGo) * frameRate,nanstd(xVellocCorr) * frameRate,...
    nanstd(xVellocFail) * frameRate],'k');
er.LineStyle = 'none';
title('Time to peak X velocity','FontSize',14);
xlabel('Trial Type','FontSize',14);
xticks([1 2 3 4 5])
xticklabels({'Go','SS','FS'})
ylabel('Time (ms)','FontSize',14);
ylim([0,round(nanmean(xVellocCorr * frameRate)+ 300)])

print(gcf,strcat('Test19_VelocityBar_StopChange_smallTcirc.pdf'),'-dpdf','-r400');


% %% Plot velocities in first 100 ms (i.e. before the stop could have kicked in)
% idx_100 = round(100 / frameRate);
% 
% xVelvalCorrGo100_mn = nanmean(mouseXvel_GoCorr(:,idx_100));
% xVelvalCorrNear100_mn  = nanmean(mouseXvel_StopCorr_Jump(:,idx_100));
% xVelvalFailNear100_mn  = nanmean(mouseXvel_StopFail_Jump(:,idx_100)); 
% xVelvalCorrFar100_mn  = nanmean(mouseXvel_StopCorr_FarJump(:,idx_100)); 
% xVelvalFailFar100_mn  = nanmean(mouseXvel_StopFail_FarJump(:,idx_100)); 
% 
% yVelvalCorrGo100_mn = nanmean(mouseYvel_GoCorr(:,idx_100));
% yVelvalCorrNear100_mn  = nanmean(mouseYvel_StopCorr_Jump(:,idx_100));
% yVelvalFailNear100_mn  = nanmean(mouseYvel_StopFail_Jump(:,idx_100)); 
% yVelvalCorrFar100_mn  = nanmean(mouseYvel_StopCorr_FarJump(:,idx_100)); 
% yVelvalFailFar100_mn  = nanmean(mouseYvel_StopFail_FarJump(:,idx_100)); 
% 
% xVelvalCorrGo100_std = nanstd(mouseXvel_GoCorr(:,idx_100));
% xVelvalCorrNear100_std  = nanstd(mouseXvel_StopCorr_Jump(:,idx_100));
% xVelvalFailNear100_std  = nanstd(mouseXvel_StopFail_Jump(:,idx_100)); 
% xVelvalCorrFar100_std  = nanstd(mouseXvel_StopCorr_FarJump(:,idx_100)); 
% xVelvalFailFar100_std  = nanstd(mouseXvel_StopFail_FarJump(:,idx_100)); 
% 
% yVelvalCorrGo100_std = nanstd(mouseYvel_GoCorr(:,idx_100));
% yVelvalCorrNear100_std  = nanstd(mouseYvel_StopCorr_Jump(:,idx_100));
% yVelvalFailNear100_std  = nanstd(mouseYvel_StopFail_Jump(:,idx_100)); 
% yVelvalCorrFar100_std  = nanstd(mouseYvel_StopCorr_FarJump(:,idx_100)); 
% yVelvalFailFar100_std  = nanstd(mouseYvel_StopFail_FarJump(:,idx_100)); 
% 
% % Peak Y Velocity in 100 ms
% figure()
% subplot(1,2,1)
% bar([yVelvalCorrGo100_mn,0, 0,0,0], 'k');
% hold on
% bar([0,yVelvalCorrNear100_mn, 0,0,0],'b');
% bar([0,0,yVelvalCorrFar100_mn,0, 0],'b', 'LineStyle', '--');
% bar([0,0,0, yVelvalFailNear100_mn,0], 'r');
% bar([0,0,0,0 yVelvalFailFar100_mn], 'r', 'LineStyle', '--');
% er = errorbar([1,2,3,4,5],[yVelvalCorrGo100_mn,yVelvalCorrNear100_mn,...
%     yVelvalCorrFar100_mn,yVelvalFailNear100_mn, yVelvalFailFar100_mn],...
%     [yVelvalCorrGo100_std,yVelvalCorrNear100_std,...
%     yVelvalCorrFar100_std,yVelvalFailNear100_std, yVelvalFailFar100_std],'k');
% er.LineStyle = 'none';
% title('Y velocity @ 100 ms','FontSize',14);
% xlabel('Trial Type','FontSize',14);
% xticks([1 2 3 4 5])
% xticklabels({'Go','SS-N','SS-F','FS-N','FS-F'})
% ylabel('Y velocity (px.s)','FontSize',14);
% ylim([0,round(nanmean(yVelvalCorrGo100_mn)+1500)])
% 
% % Peak X Velocity in 100 ms
% subplot(1,2,2)
% bar([xVelvalCorrGo100_mn,0, 0,0,0], 'k');
% hold on
% bar([0,xVelvalCorrNear100_mn, 0,0,0],'b');
% bar([0,0,xVelvalCorrFar100_mn, 0,0],'b', 'LineStyle', '--');
% bar([0,0,0, xVelvalFailNear100_mn,0], 'r');
% bar([0,0,0,0 xVelvalFailFar100_mn], 'r', 'LineStyle', '--');
% er = errorbar([1,2,3,4,5],[xVelvalCorrGo100_mn, xVelvalCorrNear100_mn,...
%     xVelvalCorrFar100_mn,xVelvalFailNear100_mn, xVelvalFailFar100_mn],...
%     [xVelvalCorrGo100_std,xVelvalCorrNear100_std,xVelvalCorrFar100_std,...
%     xVelvalFailNear100_std, xVelvalFailFar100_std],'k');
% er.LineStyle = 'none';
% title('X velocity @ 100 ms','FontSize',14);
% xlabel('Trial Type','FontSize',14);
% xticks([1 2 3 4 5])
% xticklabels({'Go','SS-N','SS-F','FS-N','FS-F'})
% ylabel('X velocity (px.s)','FontSize',14);
% ylim([0,round(nanmean(xVelvalCorrGo100_mn)+300)])
% 
% 
% print(gcf,strcat('Test19_Velocity100msBar_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

% %% What explains slow failed stops?
% % Failed stops with TRT > or < mean Go TRT
% trl_StopFail_NearStr_Short = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump'...
%     & dataTable.Outcome == 'Failed_Stop' & ...
%     (dataTable.ReactTime +  dataTable.MoveTimeT1) < nanmean(TotRespT_GoCorr);
% 
% trl_StopFail_NearStr_Long = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump'...
%     & dataTable.Outcome == 'Failed_Stop' & ...
%     (dataTable.ReactTime +  dataTable.MoveTimeT1) > nanmean(TotRespT_GoCorr);
% 
% trl_StopFail_FarStr_Short = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump'...
%     & dataTable.Outcome == 'Failed_Stop' & ...
%     (dataTable.ReactTime +  dataTable.MoveTimeT1) < nanmean(TotRespT_GoCorr);
% 
% trl_StopFail_FarStr_Long = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump'...
%     & dataTable.Outcome == 'Failed_Stop' & ...
%     (dataTable.ReactTime +  dataTable.MoveTimeT1) > nanmean(TotRespT_GoCorr);
% 
% % Calculate lateral (X) velocity in px.s
% mouseX_StopFail_NearJump_Short = mouseXYT(trl_StopFail_NearStr_Short,:, 1);
% mouseX_StopFail_NearJump_Long = mouseXYT(trl_StopFail_NearStr_Long,:, 1);
% mouseX_StopFail_FarJump_Short = mouseXYT(trl_StopFail_FarStr_Short,:, 1);
% mouseX_StopFail_FarJump_Long = mouseXYT(trl_StopFail_FarStr_Long,:, 1);
% 
% mouseXdiff_StopFail_NearJump_Short = diff(mouseX_StopFail_NearJump_Short,1,2);
% mouseXvel_StopFail_NearJump_Short = abs(mouseXdiff_StopFail_NearJump_Short./(frameRate/1000));
% [xVelvalFailNear_Short, xVellocFailNear_Short] = max(mouseXvel_StopFail_NearJump_Short');
% 
% mouseXdiff_StopFail_NearJump_Long = diff(mouseX_StopFail_NearJump_Long,1,2);
% mouseXvel_StopFail_NearJump_Long = abs(mouseXdiff_StopFail_NearJump_Long./(frameRate/1000));
% [xVelvalFailNear_Long, xVellocFailNear_Long] = max(mouseXvel_StopFail_NearJump_Long');
% 
% mouseXdiff_StopFail_FarJump_Short = diff(mouseX_StopFail_FarJump_Short,1,2);
% mouseXvel_StopFail_FarJump_Short = abs(mouseXdiff_StopFail_FarJump_Short./(frameRate/1000));
% [xVelvalFailFar_Short, xVellocFailFar_Short] = max(mouseXvel_StopFail_FarJump_Short');
% 
% mouseXdiff_StopFail_FarJump_Long = diff(mouseX_StopFail_FarJump_Long,1,2);
% mouseXvel_StopFail_FarJump_Long = abs(mouseXdiff_StopFail_FarJump_Long./(frameRate/1000));
% [xVelvalFailFar_Long, xVellocFailFar_Long] = max(mouseXvel_StopFail_FarJump_Long');
% 
% figure();
% plot((0:17:17*size(mouseXvel_GoCorr,2)-1),nanmean(mouseXvel_GoCorr),'-g')
% hold on
% plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0, 2000],'--k')
% plot([0,0],[0, 2000],'-k')
% plot([MT1_GoCorr_mn,MT1_GoCorr_mn],[0,2000],'.-k')
% plot((0:17:17*size(mouseXvel_StopFail_NearJump_Short,2)-1),nanmean(mouseXvel_StopFail_NearJump_Short),'-b')
% plot((0:17:17*size(mouseXvel_StopFail_NearJump_Long,2)-1),nanmean(mouseXvel_StopFail_NearJump_Long),'--b')
% plot((0:17:17*size(mouseXvel_StopFail_FarJump_Short,2)-1),nanmean(mouseXvel_StopFail_FarJump_Short),'-r')
% plot((0:17:17*size(mouseXvel_StopFail_FarJump_Long,2)-1),nanmean(mouseXvel_StopFail_FarJump_Long),'--r')
% plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0,10000],'-k')
% nanmean(TotRespT_GoCorr)
% legend('Go','Stop','MoveOn','MoveEnd','FS-N-S','FS-N-L','FS-F-S','FS-F-L','location','NorthWest','FontSize',14);
% xlabel('Time from movement onset (ms)','FontSize',14);
% ylabel('X velocity (px.s)','FontSize',14);
% xlim([-100, MT1_GoCorr_mn + 100]);
% ylim([0, 200]);
% text(meanStopCue_MoveOn +10, 500, 'Stop','FontSize',14,'Rotation', -90);
% text(MT1_GoCorr_mn +10, 500, 'Target Hit','FontSize',14,'Rotation', -90);
% print(gcf,strcat('Test19_VelocityFailSplitX_StopChange_smallTcirc.pdf'),'-dpdf','-r400');
% 
% mouseY_StopFail_NearJump_Short = mouseXYT(trl_StopFail_NearStr_Short,:, 2);
% mouseY_StopFail_NearJump_Long = mouseXYT(trl_StopFail_NearStr_Long,:, 2);
% mouseY_StopFail_FarJump_Short = mouseXYT(trl_StopFail_FarStr_Short,:, 2);
% mouseY_StopFail_FarJump_Long = mouseXYT(trl_StopFail_FarStr_Long,:, 2);
% 
% mouseYdiff_StopFail_NearJump_Short = diff(mouseY_StopFail_NearJump_Short,1,2);
% mouseYvel_StopFail_NearJump_Short = abs(mouseYdiff_StopFail_NearJump_Short./(frameRate/1000));
% [yVelvalFailNear_Short, yVellocFailNear_Short] = max(mouseYvel_StopFail_NearJump_Short');
% 
% mouseYdiff_StopFail_NearJump_Long = diff(mouseY_StopFail_NearJump_Long,1,2);
% mouseYvel_StopFail_NearJump_Long = abs(mouseYdiff_StopFail_NearJump_Long./(frameRate/1000));
% [yVelvalFailNear_Long, yVellocFailNear_Long] = max(mouseYvel_StopFail_NearJump_Long');
% 
% mouseYdiff_StopFail_FarJump_Short = diff(mouseY_StopFail_FarJump_Short,1,2);
% mouseYvel_StopFail_FarJump_Short = abs(mouseYdiff_StopFail_FarJump_Short./(frameRate/1000));
% [yVelvalFailFar_Short, yVellocFailFar_Short] = max(mouseYvel_StopFail_FarJump_Short');
% 
% mouseYdiff_StopFail_FarJump_Long = diff(mouseY_StopFail_FarJump_Long,1,2);
% mouseYvel_StopFail_FarJump_Long = abs(mouseYdiff_StopFail_FarJump_Long./(frameRate/1000));
% [yVelvalFailFar_Long, yVellocFailFar_Long] = max(mouseYvel_StopFail_FarJump_Long');
% 
% figure();
% plot((0:17:17*size(mouseYvel_GoCorr,2)-1),nanmean(mouseYvel_GoCorr),'-g')
% hold on
% plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0, 2000],'--k')
% plot([0,0],[0, 2000],'-k')
% plot([MT1_GoCorr_mn,MT1_GoCorr_mn],[0,2000],'.-k')
% plot((0:17:17*size(mouseYvel_StopFail_NearJump_Short,2)-1),nanmean(mouseYvel_StopFail_NearJump_Short),'-b')
% plot((0:17:17*size(mouseYvel_StopFail_NearJump_Long,2)-1),nanmean(mouseYvel_StopFail_NearJump_Long),'--b')
% plot((0:17:17*size(mouseYvel_StopFail_FarJump_Short,2)-1),nanmean(mouseYvel_StopFail_FarJump_Short),'-r')
% plot((0:17:17*size(mouseYvel_StopFail_FarJump_Long,2)-1),nanmean(mouseYvel_StopFail_FarJump_Long),'--r')
% plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0,10000],'-k')
% nanmean(TotRespT_GoCorr)
% legend('Go','Stop','MoveOn','MoveEnd','FS-N-S','FS-N-L','FS-F-S','FS-F-L','location','NorthWest','FontSize',14);
% xlabel('Time from movement onset (ms)','FontSize',14);
% ylabel('Y velocity (px.s)','FontSize',14);
% xlim([-100, MT1_GoCorr_mn + 100]);
% ylim([0, 2500]);
% text(meanStopCue_MoveOn +10, 500, 'Stop','FontSize',14,'Rotation', -90);
% text(MT1_GoCorr_mn +10, 500, 'Target Hit','FontSize',14,'Rotation', -90);
% print(gcf,strcat('Test19_VelocityFailSplitY_StopChange_smallTcirc.pdf'),'-dpdf','-r400');
% 

% %% Fast and slow correct trials
% TotRespT_StopCorr_NearJump_med = nanmedian(TotRespT_StopCorr_Jump);
% 
% % Failed stops with TRT > or < mean Go TRT
% trl_StopCorr_NearStr_Short = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump'...
%     & dataTable.Outcome == 'Successful_StopChange' & ...
%     (dataTable.ReactTime +  dataTable.MoveTimeT2) < TotRespT_StopCorr_NearJump_med;
% 
% trl_StopCorr_NearStr_Long = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump'...
%     & dataTable.Outcome == 'Successful_StopChange' & ...
%     (dataTable.ReactTime +  dataTable.MoveTimeT2) > TotRespT_StopCorr_NearJump_med;
% 
% % X Velocity Successful stop
% mouseX_StopCorr_NearJump_Short = mouseXYT(trl_StopCorr_NearStr_Short,:, 1);
% mouseX_StopCorr_NearJump_Long = mouseXYT(trl_StopCorr_NearStr_Long,:, 1);
% 
% mouseXdiff_StopCorr_NearJump_Short = diff(mouseX_StopCorr_NearJump_Short,1,2);
% mouseXvel_StopCorr_NearJump_Short = abs(mouseXdiff_StopCorr_NearJump_Short./(frameRate/1000));
% [xVelvalCorrNear_Short, xVellocCorrNear_Short] = max(mouseXvel_StopCorr_NearJump_Short');
% 
% mouseXdiff_StopCorr_NearJump_Long = diff(mouseX_StopCorr_NearJump_Long,1,2);
% mouseXvel_StopCorr_NearJump_Long = abs(mouseXdiff_StopCorr_NearJump_Long./(frameRate/1000));
% [xVelvalCorrNear_Long, xVellocCorrNear_Long] = max(mouseXvel_StopCorr_NearJump_Long');
% 
% figure();
% plot((0:17:17*size(mouseXvel_GoCorr,2)-1),nanmean(mouseXvel_GoCorr),'-g')
% hold on
% plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0, 2000],'--k')
% plot([0,0],[0, 2000],'-k')
% plot([MT1_GoCorr_mn,MT1_GoCorr_mn],[0,2000],'.-k')
% plot((0:17:17*size(mouseXvel_StopCorr_NearJump_Short,2)-1),nanmean(mouseXvel_StopCorr_NearJump_Short),'-b')
% plot((0:17:17*size(mouseXvel_StopCorr_NearJump_Long,2)-1),nanmean(mouseXvel_StopCorr_NearJump_Long),'--b')
% plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0,10000],'-k')
% nanmean(TotRespT_GoCorr)
% legend('Go','Stop','MoveOn','MoveEnd','SS-N-S','SS-N-L','location','NorthWest','FontSize',14);
% xlabel('Time from movement onset (ms)','FontSize',14);
% ylabel('X velocity (px.s)','FontSize',14);
% xlim([-100, MT1_GoCorr_mn + 100]);
% ylim([0, 200]);
% text(meanStopCue_MoveOn +10, 500, 'Stop','FontSize',14,'Rotation', -90);
% text(MT1_GoCorr_mn +10, 500, 'Target Hit','FontSize',14,'Rotation', -90);
% print(gcf,strcat('Test19_VelocityCorrSplitX_StopChange_smallTcirc.pdf'),'-dpdf','-r400');
% 
% 
% % Y Velocity Successful stop
% mouseY_StopCorr_NearJump_Short = mouseXYT(trl_StopCorr_NearStr_Short,:, 2);
% mouseY_StopCorr_NearJump_Long = mouseXYT(trl_StopCorr_NearStr_Long,:, 2);
% 
% mouseYdiff_StopCorr_NearJump_Short = diff(mouseY_StopCorr_NearJump_Short,1,2);
% mouseYvel_StopCorr_NearJump_Short = abs(mouseYdiff_StopCorr_NearJump_Short./(frameRate/1000));
% [yVelvalCorrNear_Short, yVellocCorrNear_Short] = max(mouseYvel_StopCorr_NearJump_Short');
% 
% mouseYdiff_StopCorr_NearJump_Long = diff(mouseY_StopCorr_NearJump_Long,1,2);
% mouseYvel_StopCorr_NearJump_Long = abs(mouseYdiff_StopCorr_NearJump_Long./(frameRate/1000));
% [yVelvalCorrNear_Long, yVellocCorrNear_Long] = max(mouseYvel_StopCorr_NearJump_Long');
% 
% figure();
% plot((0:17:17*size(mouseYvel_GoCorr,2)-1),nanmean(mouseYvel_GoCorr),'-g')
% hold on
% plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0, 2000],'--k')
% plot([0,0],[0, 2000],'-k')
% plot([MT1_GoCorr_mn,MT1_GoCorr_mn],[0,2000],'.-k')
% plot((0:17:17*size(mouseYvel_StopCorr_NearJump_Short,2)-1),nanmean(mouseYvel_StopCorr_NearJump_Short),'-b')
% plot((0:17:17*size(mouseYvel_StopCorr_NearJump_Long,2)-1),nanmean(mouseYvel_StopCorr_NearJump_Long),'--b')
% plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0,10000],'-k')
% nanmean(TotRespT_GoCorr)
% legend('Go','Stop','MoveOn','MoveEnd','SS-N-S','SS-N-L','location','NorthWest','FontSize',14);
% xlabel('Time from movement onset (ms)','FontSize',14);
% ylabel('Y velocity (px.s)','FontSize',14);
% xlim([-100, MT1_GoCorr_mn + 100]);
% ylim([0, 2500]);
% text(meanStopCue_MoveOn +10, 500, 'Stop','FontSize',14,'Rotation', -90);
% text(MT1_GoCorr_mn +10, 500, 'Target Hit','FontSize',14,'Rotation', -90);
% print(gcf,strcat('Test19_VelocityCorrSplitY_StopChange_smallTcirc.pdf'),'-dpdf','-r400');
% 

%% what if I plot with respect to SSD on a given trial? will I see the jumps more readily?

mouseT_SSDnorm = mouseXYT(:,:,3);

% All SSDs
mouseXvel_SSDnorm_Corr = mouseXvel_StopCorr_Jump;
mouseXvel_SSDnorm_Fail = mouseXvel_StopFail_Jump;

% Take mouse time data points and subtract the SSD from all of them
% Mouse Time is relative to the Go cue, so subtracting SSD normalises all
% times to the SSD, so that SSD is now 0 ms 
mouseT_SSDnorm = mouseT_SSDnorm - dataTable.StopSignalDelay;

ssd_Corr = dataTable.StopSignalDelay(trl_StopCorr_Str,:); % checking only (delete)
mouseT_corr = mouseXYT(trl_StopCorr_Str,:,3) - ssd_Corr; % checking only (delete)

figure()
for i = 1:size(mouseXvel_SSDnorm_Corr,1)
    scatter(mouseT_corr(i,1:end-1),mouseXvel_SSDnorm_Corr(i,:))
    hold on
end
xlim([0,350])

mouseT_SSDnorm_Corr = mouseT_SSDnorm(trl_StopCorr_Str,:);
mouseT_SSDnorm_Fail = mouseT_SSDnorm(trl_StopFail_Str,:);

mouseT_SSDnorm_Corr(mouseT_SSDnorm_Corr < - frameRate) = NaN;
[valMinCorr,locMinCorr] = min(mouseT_SSDnorm_Corr');
[valMaxCorr,locMaxCorr] = max(mouseT_SSDnorm_Corr');

mouseT_SSDnorm_Fail(mouseT_SSDnorm_Fail < - frameRate) = NaN;
[valMinFail,locMinFail] = min(mouseT_SSDnorm_Fail');
[valMaxFail,locMaxFail] = max(mouseT_SSDnorm_Fail');
idx_exceedmax = locMaxFail > size(mouseXvel_SSDnorm_Fail,2);
locMaxFail(idx_exceedmax) = size(mouseXvel_SSDnorm_Fail,2);




dat = NaN(size(mouseT_SSDnorm_Corr,1),size(mouseT_SSDnorm_Corr,2));

for i = 1:size(mouseT_SSDnorm_Corr,1)

    dat = mouseT_SSDnorm_Corr(i,locMinCorr(i):locMaxCorr(i));
    mouseT_SSDnorm_Corr(i,1:length(dat)) = dat;
    mouseT_SSDnorm_Corr(i,length(dat):end) = NaN;
    
    dat = mouseXvel_SSDnorm_Corr(i,locMinCorr(i):locMaxCorr(i)-1);
    mouseXvel_SSDnorm_Corr(i,1:length(dat)) = dat;
    mouseXvel_SSDnorm_Corr(i,length(dat):end) = NaN;
    
end

mouseT_SSDnorm_Corr_mn = nanmean(mouseT_SSDnorm_Corr);
mouseXvel_SSDnorm_Corr_mn = nanmean(mouseXvel_SSDnorm_Corr);


for i = 1:size(mouseT_SSDnorm_Fail,1)

    dat = mouseT_SSDnorm_Fail(i,locMinFail(i):locMaxFail(i));
    mouseT_SSDnorm_Fail(i,1:length(dat)) = dat;
    mouseT_SSDnorm_Fail(i,length(dat):end) = NaN;
    
    dat = mouseXvel_SSDnorm_Fail(i,locMinFail(i):locMaxFail(i));
    mouseXvel_SSDnorm_Fail(i,1:length(dat)) = dat;
    mouseXvel_SSDnorm_Fail(i,length(dat):end) = NaN;
    
end

mouseT_SSDnorm_Fail_mn = nanmean(mouseT_SSDnorm_Fail);
mouseXvel_SSDnorm_Fail_mn = nanmean(mouseXvel_SSDnorm_Fail);

figure()
subplot(1,2,1)
plot(mouseT_SSDnorm_Corr_mn(1:length(mouseXvel_SSDnorm_Corr_mn)),mouseXvel_SSDnorm_Corr_mn,'b');
hold on
plot(mouseT_SSDnorm_Fail_mn(1:length(mouseXvel_SSDnorm_Fail_mn)),mouseXvel_SSDnorm_Fail_mn,'--r');
xlim([0, 450]);
xlabel('Time from Stop (ms)','FontSize',14);
ylabel('X velocity (px.s)','FontSize',14);
legend('SS','FS','location','NorthWest','FontSize',14);

%%------- time goes wrong here
mouseT_SSDnorm = mouseXYT(:,:,3);

% All SSDs
mouseT_SSDnorm = mouseT_SSDnorm - dataTable.StopSignalDelay;

mouseT_SSDnorm_Corr = mouseT_SSDnorm(trl_StopCorr_Str,:);
mouseT_SSDnorm_Fail = mouseT_SSDnorm(trl_StopFail_Str,:);

mouseT_SSDnorm_Corr(mouseT_SSDnorm_Corr < - frameRate) = NaN;
[valMinCorr,locMinCorr] = min(mouseT_SSDnorm_Corr');
[valMaxCorr,locMaxCorr] = max(mouseT_SSDnorm_Corr');

mouseT_SSDnorm_Fail(mouseT_SSDnorm_Fail < - frameRate) = NaN;
[valMinFail,locMinFail] = min(mouseT_SSDnorm_Fail');
[valMaxFail,locMaxFail] = max(mouseT_SSDnorm_Fail');
idx_exceedmax = locMaxFail > size(mouseXvel_SSDnorm_Fail,2);
locMaxFail(idx_exceedmax) = size(mouseXvel_SSDnorm_Fail,2);

mouseYvel_SSDnorm_Corr = mouseYvel_StopCorr_Jump;
mouseYvel_SSDnorm_Fail = mouseYvel_StopFail_Jump;

dat = NaN(size(mouseT_SSDnorm_Corr,1),size(mouseT_SSDnorm_Corr,2));

for i = 1:size(mouseT_SSDnorm_Corr,1)

    dat = mouseT_SSDnorm_Corr(i,locMinCorr(i):locMaxCorr(i));
    mouseT_SSDnorm_Corr(i,1:length(dat)) = dat;
    mouseT_SSDnorm_Corr(i,length(dat):end) = NaN;
    
    dat = mouseYvel_SSDnorm_Corr(i,locMinCorr(i):locMaxCorr(i)-1);
    mouseYvel_SSDnorm_Corr(i,1:length(dat)) = dat;
    mouseYvel_SSDnorm_Corr(i,length(dat):end) = NaN;
    
end

mouseT_SSDnorm_Corr_mn = nanmean(mouseT_SSDnorm_Corr);
mouseYvel_SSDnorm_Corr_mn = nanmean(mouseYvel_SSDnorm_Corr);


for i = 1:size(mouseT_SSDnorm_Fail,1)

    dat = mouseT_SSDnorm_Fail(i,locMinFail(i):locMaxFail(i));
    mouseT_SSDnorm_Fail(i,1:length(dat)) = dat;
    mouseT_SSDnorm_Fail(i,length(dat):end) = NaN;
    
    dat = mouseYvel_SSDnorm_Fail(i,locMinFail(i):locMaxFail(i));
    mouseYvel_SSDnorm_Fail(i,1:length(dat)) = dat;
    mouseYvel_SSDnorm_Fail(i,length(dat):end) = NaN;
    
end

mouseT_SSDnorm_Fail_mn = nanmean(mouseT_SSDnorm_Fail);
mouseYvel_SSDnorm_Fail_mn = nanmean(mouseYvel_SSDnorm_Fail);

subplot(1,2,2)
plot(mouseT_SSDnorm_Corr_mn(1:length(mouseYvel_SSDnorm_Corr_mn)),mouseYvel_SSDnorm_Corr_mn,'b');
hold on
plot(mouseT_SSDnorm_Fail_mn(1:length(mouseYvel_SSDnorm_Fail_mn)),mouseYvel_SSDnorm_Fail_mn,'--r');
xlim([0, 450]);
xlabel('Time from Stop (ms)','FontSize',14);
ylabel('Y velocity (px.s)','FontSize',14);
legend('SS','FS','location','NorthEast','FontSize',14);

print(gcf,strcat('Test19_VelocityXY_StopCue_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

figure()
subplot(1,2,1)
for i = 1:size(mouseXvel_SSDnorm_Corr,1)
    plot(mouseT_SSDnorm_Corr(i,1:length(mouseXvel_SSDnorm_Corr)), mouseXvel_SSDnorm_Corr(i,:))
hold on
end
xlim([0,350])
hold off
xlabel('Time from Stop (ms)','FontSize',14);
ylabel('X velocity (px.s)','FontSize',14);
legend('SS','FS','location','NorthWest','FontSize',14);

subplot(1,2,2)
for i = 1:size(mouseYvel_SSDnorm_Corr,1)
    plot(mouseT_SSDnorm_Corr(i,1:length(mouseYvel_SSDnorm_Corr)), mouseYvel_SSDnorm_Corr(i,:))
hold on
end
xlim([0,350])
hold off
xlabel('Time from Stop (ms)','FontSize',14);
ylabel('Y velocity (px.s)','FontSize',14);
legend('SS','FS','location','NorthWest','FontSize',14);

% Calc acceleration to be sure about when Vel changes
mouseXacc_SSDnorm_Corr = diff(mouseXvel_SSDnorm_Corr,1,2)./(frameRate/1000);
mouseXacc_SSDnorm_Corr_mn = nanmean(mouseXacc_SSDnorm_Corr);

mouseXacc_SSDnorm_Fail = diff(mouseXvel_SSDnorm_Fail,1,2)./(frameRate/1000);
mouseXacc_SSDnorm_Fail_mn = nanmean(mouseXacc_SSDnorm_Fail);


figure()
subplot(1,2,1)
plot(mouseT_SSDnorm_Corr_mn(1:length(mouseXacc_SSDnorm_Corr_mn)),mouseXacc_SSDnorm_Corr_mn,'b');
hold on
plot(mouseT_SSDnorm_Fail_mn(1:length(mouseXacc_SSDnorm_Fail_mn)),mouseXacc_SSDnorm_Fail_mn,'--r');
xlim([0, 450]);
xlabel('Time from Stop (ms)','FontSize',14);
ylabel('X Acc (px.s-2)','FontSize',14);
legend('SS','FS','location','NorthWest','FontSize',14);


mouseYacc_SSDnorm_Corr = diff(mouseYvel_SSDnorm_Corr,1,2)./(frameRate/1000);
mouseYacc_SSDnorm_Corr_mn = nanmean(mouseYacc_SSDnorm_Corr);

mouseYacc_SSDnorm_Fail = diff(mouseYvel_SSDnorm_Fail,1,2)./(frameRate/1000);
mouseYacc_SSDnorm_Fail_mn = nanmean(mouseYacc_SSDnorm_Fail);

subplot(1,2,2)
plot(mouseT_SSDnorm_Corr_mn(1:length(mouseYacc_SSDnorm_Corr_mn)),mouseYacc_SSDnorm_Corr_mn,'b');
hold on
plot(mouseT_SSDnorm_Fail_mn(1:length(mouseYacc_SSDnorm_Fail_mn)),mouseYacc_SSDnorm_Fail_mn,'--r');
xlim([0, 450]);
xlabel('Time from Stop (ms)','FontSize',14);
ylabel('Y Acc (px.s-2)','FontSize',14);
legend('SS','FS','location','NorthWest','FontSize',14);


figure()
subplot(1,2,1)
for i = 1:size(mouseXacc_SSDnorm_Corr,1)
    plot(mouseT_SSDnorm_Corr(i,1:length(mouseXacc_SSDnorm_Corr)), mouseXacc_SSDnorm_Corr(i,:));
hold on
end
xlim([0,350])
hold off
xlabel('Time from Stop (ms)','FontSize',14);
ylabel('X Acc (px.s-2)','FontSize',14);
legend('SS','FS','location','NorthWest','FontSize',14);

subplot(1,2,2)
for i = 1:size(mouseYacc_SSDnorm_Corr,1)
    plot(mouseT_SSDnorm_Corr(i,1:length(mouseYacc_SSDnorm_Corr)), mouseYacc_SSDnorm_Corr(i,:));
hold on
end
xlim([0,350]);
hold off
xlabel('Time from Stop (ms)','FontSize',14);
ylabel('Y velocity (px.s-2)','FontSize',14);
legend('SS','FS','location','NorthWest','FontSize',14);

figure()
for i = 1:size(mouseYacc_SSDnorm_Corr,1)
    plot(mouseT_SSDnorm_Corr(i,1:length(a)), a(i,:));
hold on
end
xlim([0,350]);
hold off
xlabel('Time from Stop (ms)','FontSize',14);
ylabel('X/Y velocity (px.s-2)','FontSize',14);
legend('SS','FS','location','NorthWest','FontSize',14);

a = mouseYacc_SSDnorm_Corr./mouseXacc_SSDnorm_Corr
aveA = nanmean(abs(a))
figure()
plot(mouseT_SSDnorm_Corr_mn(1:length(mouseXacc_SSDnorm_Corr_mn)),aveA)