%%
clc; clear 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";


%
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_NearStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump' & ~isnan(dataTable.StopSignalDelay);
trl_StopCorr_NearStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump' & dataTable.Outcome == 'Successful_StopChange';
trl_StopFail_NearStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump' & dataTable.Outcome == 'Failed_Stop';
% any where T2 < T1 (weird squiggle overcorrection) and therefore wrongly
% classified as fail
trl_StopCorrt_NearStr_T2lessT1 = find(dataTable.MoveTimeT2(trl_StopFail_NearStr) < dataTable.MoveTimeT1(trl_StopFail_NearStr))

% Stop trials with the Far staircase
trl_StopAll_FarStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump' & ~isnan(dataTable.StopSignalDelay);
trl_StopCorr_FarStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump' & dataTable.Outcome == 'Successful_StopChange';
trl_StopFail_FarStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump' & dataTable.Outcome == 'Failed_Stop';

% How many Far staircase trials did they initiate a movement
numTrls_moved_FarStr = sum(dataTable.Staircase == 'FarJump' & ~isnan(dataTable.ReactTime)); % looks like I initiated a movement every time!!

%% 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_NearJump = dataTable.ReactTime(trl_StopCorr_NearStr);
MT2_StopCorr_NearJump = dataTable.MoveTimeT2(trl_StopCorr_NearStr);
RT_StopCorr_FarJump = dataTable.ReactTime(trl_StopCorr_FarStr);
MT2_StopCorr_FarJump = dataTable.MoveTimeT2(trl_StopCorr_FarStr);
% Failed Stop Change RT and MT1
RT_StopFail_NearJump = dataTable.ReactTime(trl_StopFail_NearStr);
MT1_StopFail_NearJump = dataTable.MoveTimeT1(trl_StopFail_NearStr);
RT_StopFail_FarJump = dataTable.ReactTime(trl_StopFail_FarStr);
MT1_StopFail_FarJump = dataTable.MoveTimeT1(trl_StopFail_FarStr);

% Total response times
TotRespT_GoCorr = RT_GoAll + MT1_GoAll;
TotRespT_StopCorr_NearJump = RT_StopCorr_NearJump + MT2_StopCorr_NearJump;
TotRespT_StopCorr_FarJump = RT_StopCorr_FarJump + MT2_StopCorr_FarJump;
TotRespT_StopFail_NearJump = RT_StopFail_NearJump + MT1_StopFail_NearJump;
TotRespT_StopFail_FarJump = RT_StopFail_FarJump + MT1_StopFail_FarJump;

% 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_NearJump_mn = nanmean(RT_StopCorr_NearJump);
MT2_StopCorr_NearJump_mn = nanmean(MT2_StopCorr_NearJump(MT2_StopCorr_NearJump > 100));
RT_StopCorr_FarJump_mn = nanmean(RT_StopCorr_FarJump);
MT2_StopCorr_FarJump_mn = nanmean(MT2_StopCorr_FarJump(MT2_StopCorr_FarJump > 100));
% Mean Failed Stop Change RT and MT1
RT_StopFail_NearJump_mn = nanmean(RT_StopFail_NearJump);
MT1_StopFail_NearJump_mn = nanmean(MT1_StopFail_NearJump(MT1_StopFail_NearJump > 100));
RT_StopFail_FarJump_mn = nanmean(RT_StopFail_FarJump);
MT1_StopFail_FarJump_mn = nanmean(MT1_StopFail_FarJump(MT1_StopFail_FarJump > 100));

% All SSDs
SSD_Stop_NearJump = dataTable.StopSignalDelay(trl_StopAll_NearStr);
SSD_Stop_FarJump = dataTable.StopSignalDelay(trl_StopAll_FarStr);

% Mean SSD
SSD_Stop_NearJump_mn = nanmean(SSD_Stop_NearJump);
SSD_Stop_FarJump_mn = nanmean(SSD_Stop_FarJump);

% Stop success
pStop_NearJump = (sum(trl_StopCorr_NearStr) / sum(sum([trl_StopCorr_NearStr,trl_StopFail_NearStr]))) *100;
pStop_FarJump = (sum(trl_StopCorr_FarStr) / sum(sum([trl_StopCorr_FarStr,trl_StopFail_FarStr]))) *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_NearJump  = round((pStop_NearJump/100).*length(sort_TotRespT));
nth_TRT_NearJump        = sort_TotRespT(nth_TRT_index_NearJump);
SSRT_NearJump          = nth_TRT_NearJump - SSD_Stop_NearJump_mn

% MT1s
sort_TotRespT            = sort(TotRespT_GoCorr(~isnan(TotRespT_GoCorr)));
nth_TRT_index_FarJump = round((pStop_FarJump/100).*length(sort_TotRespT));
nth_TRT_FarJump        = sort_TotRespT(nth_TRT_index_FarJump);
SSRT_FarJump         = nth_TRT_FarJump - SSD_Stop_FarJump_mn


%% Plot RTs and MT1s
figure()

subplot(3,2,1);
histogram(RT_GoCorr,'BinWidth',25, 'Normalization','probability');
hold on
histogram(RT_StopCorr_NearJump,'BinWidth',25, 'Normalization','probability');
histogram(RT_StopCorr_FarJump,'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-N: ' num2str(round(RT_StopCorr_NearJump_mn)) 'ms']);
tx3 = (['SS-F: ' num2str(round(RT_StopCorr_FarJump_mn)) 'ms']);
text(40, 0.38,tx1);
text(40, 0.32,tx2);
text(40, 0.26,tx3);

subplot(3,2,2)
histogram(RT_GoCorr,'BinWidth',25, 'Normalization','probability');
hold on
histogram(RT_StopFail_NearJump,'BinWidth',25, 'Normalization','probability');
histogram(RT_StopFail_FarJump,'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_NearJump_mn)) 'ms']);
tx3 = (['FS-F: ' num2str(round(RT_StopFail_FarJump_mn)) 'ms']);
text(40, 0.38,tx1);
text(40, 0.32,tx2);
text(40, 0.26,tx3);

subplot(3,2,3)
histogram(MT1_GoCorr,'BinWidth',25, 'Normalization','probability')
hold on
histogram(MT2_StopCorr_NearJump,'BinWidth',25, 'Normalization','probability');
histogram(MT2_StopCorr_FarJump,'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-N MT2: ' num2str(round(MT2_StopCorr_NearJump_mn)) 'ms']);
tx3 = (['SS-F MT2: ' num2str(round(MT2_StopCorr_FarJump_mn)) 'ms']);
text(20, 0.38,tx1);
text(20, 0.32,tx2);
text(20, 0.26,tx3);

subplot(3,2,4)
histogram(MT1_GoCorr,'BinWidth',25, 'Normalization','probability')
hold on
histogram(MT1_StopFail_NearJump,'BinWidth',25, 'Normalization','probability');
histogram(MT1_StopFail_FarJump,'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_NearJump_mn)) 'ms']);
tx3 = (['FS-F MT1: ' num2str(round(MT1_StopFail_FarJump_mn)) 'ms']);
text(20, 0.38,tx1);
text(20, 0.32,tx2);
text(20, 0.26,tx3);

subplot(3,2,5);
histogram(TotRespT_GoCorr,'BinWidth',20, 'Normalization','probability')
hold on
histogram(TotRespT_StopCorr_NearJump,'BinWidth',20, 'Normalization','probability')
histogram(TotRespT_StopCorr_FarJump,'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 = (['FS TotT: ' num2str(round(nanmean(TotRespT_StopCorr_NearJump(TotRespT_StopCorr_NearJump > 500)))) 'ms']);
tx3 = (['FS TotT: ' num2str(round(nanmean(TotRespT_StopCorr_FarJump(TotRespT_StopCorr_FarJump > 500)))) 'ms']);
text(40, 0.28,tx1);
text(40, 0.22,tx2);
text(40, 0.16,tx3);

subplot(3,2,6);
histogram(TotRespT_GoCorr,'BinWidth',20, 'Normalization','probability')
hold on
histogram(TotRespT_StopFail_NearJump,'BinWidth',20, 'Normalization','probability')
histogram(TotRespT_StopFail_FarJump,'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-N: ' num2str(round(nanmean(TotRespT_StopFail_NearJump(TotRespT_StopFail_NearJump > 500)))) 'ms']);
tx3 = (['FS-N: ' num2str(round(nanmean(TotRespT_StopFail_FarJump(TotRespT_StopFail_FarJump > 500)))) 'ms']);
text(40, 0.28,tx1);
text(40, 0.22,tx2);
text(40, 0.16,tx3);

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

%% Plot stopping staircases
% Need to first calculate pStop at each SSD
% how many SSDs?
SSD_uniq_NearJump = unique(SSD_Stop_NearJump);
SSD_uniq_FarJump = unique(SSD_Stop_FarJump);
max_ntrls = max(length(SSD_uniq_NearJump), length(SSD_uniq_FarJump));

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

% Near stair case
for i = 1:length(SSD_uniq_NearJump)
    currentSSD = SSD_uniq_NearJump(i);
    %     count how many trials for that SSD in that stair case
    idx_all = dataTable.StopSignalDelay(trl_StopAll_NearStr) == currentSSD;
    nTrls_all = sum(idx_all);
    idx_success = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump' & ...
        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.Staircase == 'NearJump' & ...
        dataTable.StopSignalDelay == currentSSD & dataTable.Outcome == 'Failed_Stop';
    FailedStop_MT_SSD(i,1 ) = nanmean(dataTable.MoveTimeT1(idx_fail));
end

% Far stair case
for i = 1:length(SSD_uniq_FarJump)
    currentSSD = SSD_uniq_FarJump(i);
    %     count how many trials for that SSD in that stair case
    idx_all = dataTable.StopSignalDelay(trl_StopAll_FarStr) == currentSSD;
    nTrls_all = sum(idx_all);
    idx_success = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump' & ...
        dataTable.StopSignalDelay == currentSSD & dataTable.Outcome == 'Successful_StopChange';
    nTrls_correct = sum(idx_success);
    pStop_SSD(i,2) = (nTrls_correct / nTrls_all) * 100;
    idx_fail = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump' & ...
        dataTable.StopSignalDelay == currentSSD & dataTable.Outcome == 'Failed_Stop';
    FailedStop_MT_SSD(i,2 ) = nanmean(dataTable.MoveTimeT1(idx_fail));
end


idx_NearJump = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump' & ~isnan(dataTable.StopSignalDelay);
idx_FarJump = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump' & ~isnan(dataTable.StopSignalDelay);

figure()
plot(dataTable.StopSignalDelay(idx_NearJump),  'b');
hold on
plot(dataTable.StopSignalDelay(idx_FarJump),  '--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_NearJump;SSD_uniq_FarJump])]);
legend('Near','Far','FontSize',14)
legend boxoff
print(gcf,strcat('Test9_StaircaseTracking_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

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

figure()
scatter(SSD_uniq_NearJump, FailedStop_MT_SSD(1:length(SSD_uniq_NearJump),1), 50, 'filled', 'b');
hold on
scatter(SSD_uniq_FarJump, FailedStop_MT_SSD(1:length(SSD_uniq_FarJump),2), 50, 'filled', 'r');
plot([0, max(SSD_uniq_FarJump)],[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_FarJump)]);
ylim([0,450]);
legend('Near','Far','Nfit','Ffit','FontSize',14, 'location', 'SouthEast')
legend boxoff

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





%% Plot SSRT and mean SSD
figure()
subplot(2,3,1)
bar([RT_GoCorr_mn,0, 0,0,0], 'k');
hold on
bar([0,RT_StopCorr_NearJump_mn, 0,0,0],'b');
bar([0,0, RT_StopCorr_FarJump_mn,0,0], 'b','LineStyle','--');
bar([0,0,0,RT_StopFail_NearJump_mn, 0],'r');
bar([0,0,0,0 RT_StopFail_FarJump_mn], 'r','LineStyle','--');
er = errorbar([1,2,3,4,5],[RT_GoCorr_mn,RT_StopCorr_NearJump_mn, RT_StopCorr_FarJump_mn, RT_StopFail_NearJump_mn,RT_StopFail_FarJump_mn],...
    [nanstd(RT_GoCorr),nanstd(RT_StopCorr_NearJump), nanstd(RT_StopCorr_FarJump),nanstd(RT_StopFail_NearJump), nanstd(RT_StopFail_FarJump)],'k');
er.LineStyle = 'none';
title('React. Time','FontSize',14);
xlabel('Staircase','FontSize',14);
xticks([1 2 3 4 5])
xticklabels({'Go','SS-N','SS-F','FS-N','FS-F'})
ylabel('RT (ms)','FontSize',14);
ylim([200,round(RT_GoCorr_mn+100)]);

subplot(2,3,2)
bar([MT1_GoCorr_mn,0, 0,0,0], 'k');
hold on
bar([0,MT2_StopCorr_NearJump_mn, 0,0,0],'b');
bar([0,0, MT2_StopCorr_FarJump_mn,0,0],'b' ,'LineStyle','--');
bar([0,0,0,MT1_StopFail_NearJump_mn,0],'r');
bar([0,0,0,0, MT1_StopFail_FarJump_mn], 'r','LineStyle','--');
er = errorbar([1,2,3,4,5],[MT1_GoCorr_mn, MT2_StopCorr_NearJump_mn, MT2_StopCorr_FarJump_mn,MT1_StopFail_NearJump_mn,MT1_StopFail_FarJump_mn],...
    [nanstd(MT1_GoCorr), nanstd(MT2_StopCorr_NearJump), nanstd(MT2_StopCorr_NearJump), nanstd(MT1_StopFail_NearJump), nanstd(MT1_StopFail_FarJump)],'k');
er.LineStyle = 'none';
title('Move. Time','FontSize',14);
xlabel('Staircase','FontSize',14);
xticks([1 2 3 4 5])
xticklabels({'Go','SS-N','SS-F','FS-N','FS-F'})
ylabel('MT1 (ms)','FontSize',14);
ylim([200,round(max([MT2_StopCorr_NearJump_mn, MT2_StopCorr_FarJump_mn])+120)]);

subplot(2,3,3)
bar([nanmean(TotRespT_GoCorr),0, 0], 'k');
hold on
bar([0,nanmean(TotRespT_StopCorr_NearJump), 0,0,0],'b');
bar([0,0, nanmean(TotRespT_StopCorr_FarJump(TotRespT_StopCorr_FarJump > 500)),0,0], 'b','LineStyle','--');
bar([0,0,0, nanmean(TotRespT_StopFail_NearJump), 0],'r');
bar([0,0,0,0,  nanmean(TotRespT_StopFail_FarJump)], 'r','LineStyle','--');
er = errorbar([1,2,3, 4, 5],[nanmean(TotRespT_GoCorr),nanmean(TotRespT_StopCorr_NearJump),nanmean(TotRespT_StopCorr_FarJump(TotRespT_StopCorr_FarJump > 500)),nanmean(TotRespT_StopFail_NearJump),nanmean(TotRespT_StopFail_FarJump)],...
    [nanstd(TotRespT_GoCorr),nanstd(TotRespT_StopCorr_NearJump), nanstd(TotRespT_StopCorr_FarJump(TotRespT_StopCorr_FarJump > 500)),nanstd(TotRespT_StopFail_NearJump), nanstd(TotRespT_StopFail_FarJump)],'k');
er.LineStyle = 'none';
title('Total Time','FontSize',14);
xlabel('Staircase','FontSize',14);
xticks([1 2 3 4 5])
xticklabels({'Go','SS-N','SS-F','FS-N','FS-F'})
ylabel('Total Time (ms)','FontSize',14);
ylim([500,round(nanmean(TotRespT_StopCorr_FarJump(TotRespT_StopCorr_FarJump > 500))+120)]);
% subject 2 has no values for MT so it messes up total time

subplot(2,3,4)
bar([pStop_NearJump,0], 'b');
hold on
bar([0,pStop_FarJump], 'b','LineStyle','--');
title('pStop','FontSize',14);
xlabel('Staircase','FontSize',14);
xticks([1 2])
xticklabels({'Near','Far'})
ylabel('pStop (%)','FontSize',14);
ylim([0,100]);

subplot(2,3,5)
bar([SSD_Stop_NearJump_mn,0], 'b');
hold on
bar([0,SSD_Stop_FarJump_mn], 'b','LineStyle','--');
title('SSD','FontSize',14);
xlabel('Staircase','FontSize',14);
xticks([1 2])
xticklabels({'Near','Far'})
ylabel('SSD (ms)','FontSize',14);
ylim([0,round(max([SSD_Stop_NearJump_mn;SSD_Stop_FarJump_mn])+20)]);

subplot(2,3,6)
bar([SSRT_NearJump,0], 'b');
hold on
bar([0,SSRT_FarJump], 'b','LineStyle','--');
title('SSRT','FontSize',14);
xlabel('Staircase','FontSize',14);
xticks([1 2])
xticklabels({'Near','Far'})
ylabel('SSRT (ms)','FontSize',14);
ylim([0,round(SSRT_FarJump+20)]);

print(gcf,strcat('Test9_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' & dataTable.Staircase(i) == 'NearJump'
        final_datpoint = Yloc(i);
        color = 'b';
    elseif dataTable.Outcome(i) == 'Successful_StopChange' & dataTable.Staircase(i) == 'FarJump'
        final_datpoint = size(mouseX,2);
        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('Test9_Trajectory3d_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

view(0,270)
print(gcf,strcat('Test9_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';

% Near
trl_StopCorr_NearStr_left = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump'...
    & dataTable.Outcome == 'Successful_StopChange' & dataTable.CueDirection == 'Left';
trl_StopCorr_NearStr_right = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump'...
    & dataTable.Outcome == 'Successful_StopChange' & dataTable.CueDirection == 'Right';
trl_StopFail_NearStr_left = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump'...
    & dataTable.Outcome == 'Failed_Stop' & dataTable.CueDirection == 'Left';
trl_StopFail_NearStr_right = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'NearJump'...
    & dataTable.Outcome == 'Failed_Stop' & dataTable.CueDirection == 'Right';
% Far
trl_StopCorr_FarStr_left = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump' &...
    dataTable.Outcome == 'Successful_StopChange' & dataTable.CueDirection == 'Left';
trl_StopCorr_FarStr_right = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump' &...
    dataTable.Outcome == 'Successful_StopChange' & dataTable.CueDirection == 'Right';
trl_StopFail_FarStr_left = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump'...
    & dataTable.Outcome == 'Failed_Stop' & dataTable.CueDirection == 'Left';
trl_StopFail_FarStr_right = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'FarJump'...
    & 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_NearJump_left = nanmean(mouseX(trl_StopCorr_NearStr_left,:));
mouseX_StopCorr_NearJump_right = nanmean(mouseX(trl_StopCorr_NearStr_right,:));

mouseX_StopCorr_FarJump_left = nanmean(mouseX(trl_StopCorr_FarStr_left,:));
mouseX_StopCorr_FarJump_right = nanmean(mouseX(trl_StopCorr_FarStr_right,:));

mouseX_StopFail_NearJump_left = nanmean(mouseX(trl_StopFail_NearStr_left,:));
mouseX_StopFail_NearJump_right = nanmean(mouseX(trl_StopFail_NearStr_right,:));

mouseX_StopFail_FarJump_left = nanmean(mouseX(trl_StopFail_FarStr_left,:));
mouseX_StopFail_FarJump_right = nanmean(mouseX(trl_StopFail_FarStr_right,:));

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

mouseY_StopCorr_NearJump_left = nanmean(mouseY(trl_StopCorr_NearStr_left,:));
mouseY_StopCorr_NearJump_right = nanmean(mouseY(trl_StopCorr_NearStr_right,:));

mouseY_StopCorr_FarJump_left = nanmean(mouseY(trl_StopCorr_FarStr_left,:));
mouseY_StopCorr_FarJump_right = nanmean(mouseY(trl_StopCorr_FarStr_right,:));

mouseY_StopFail_NearJump_left = nanmean(mouseY(trl_StopFail_NearStr_left,:));
mouseY_StopFail_NearJump_right = nanmean(mouseY(trl_StopFail_NearStr_right,:));

mouseY_StopFail_FarJump_left = nanmean(mouseY(trl_StopFail_FarStr_left,:));
mouseY_StopFail_FarJump_right = nanmean(mouseY(trl_StopFail_FarStr_right,:));


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

mouseT_StopCorr_NearJump_left = nanmean(mouseT(trl_StopCorr_NearStr_left,:));
mouseT_StopCorr_NearJump_right = nanmean(mouseT(trl_StopCorr_NearStr_right,:));

mouseT_StopCorr_FarJump_left = nanmean(mouseT(trl_StopCorr_FarStr_left,:));
mouseT_StopCorr_FarJump_right = nanmean(mouseT(trl_StopCorr_FarStr_right,:));

mouseT_StopFail_NearJump_left = nanmean(mouseT(trl_StopFail_NearStr_left,:));
mouseT_StopFail_NearJump_right = nanmean(mouseT(trl_StopFail_NearStr_right,:));

mouseT_StopFail_FarJump_left = nanmean(mouseT(trl_StopFail_FarStr_left,:));
mouseT_StopFail_FarJump_right = nanmean(mouseT(trl_StopFail_FarStr_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_NearJump_left(1,1:round(MT2_StopCorr_NearJump_mn./frameRate)), ...
    mouseY_StopCorr_NearJump_left(1,1:round(MT2_StopCorr_NearJump_mn./frameRate)),...
    mouseT_StopCorr_NearJump_left(1,1:round(MT2_StopCorr_NearJump_mn./frameRate)),'b','LineWidth',2);
plot3(mouseX_StopCorr_NearJump_right(1,1:round(MT2_StopCorr_NearJump_mn./frameRate)),...
    mouseY_StopCorr_NearJump_right(1,1:round(MT2_StopCorr_NearJump_mn./frameRate)),...
    mouseT_StopCorr_NearJump_right(1,1:round(MT2_StopCorr_NearJump_mn./frameRate)),'b','LineWidth',2);

plot3(mouseX_StopCorr_FarJump_left(1,1:round(MT2_StopCorr_FarJump_mn./frameRate)+10), ... % + 10 - need to sort our precisely when
    mouseY_StopCorr_FarJump_left(1,1:round(MT2_StopCorr_FarJump_mn./frameRate)+10),...
    mouseT_StopCorr_FarJump_left(1,1:round(MT2_StopCorr_FarJump_mn./frameRate)+10),'--b','LineWidth',2);
plot3(mouseX_StopCorr_FarJump_right(1,1:round(MT2_StopCorr_FarJump_mn./frameRate)+10),...
    mouseY_StopCorr_FarJump_right(1,1:round(MT2_StopCorr_FarJump_mn./frameRate)+10),...
    mouseT_StopCorr_FarJump_right(1,1:round(MT2_StopCorr_FarJump_mn./frameRate)+10),'--b','LineWidth',2);

plot3(mouseX_StopFail_NearJump_left(1,1:round(MT1_StopFail_NearJump_mn./frameRate)), ...
    mouseY_StopFail_NearJump_left(1,1:round(MT1_StopFail_NearJump_mn./frameRate)),...
    mouseT_StopFail_NearJump_left(1,1:round(MT1_StopFail_NearJump_mn./frameRate)),'r','LineWidth',2);
plot3(mouseX_StopFail_NearJump_right(1,1:round(MT1_StopFail_NearJump_mn./frameRate)),...
    mouseY_StopFail_NearJump_right(1,1:round(MT1_StopFail_NearJump_mn./frameRate)),...
    mouseT_StopFail_NearJump_right(1,1:round(MT1_StopFail_NearJump_mn./frameRate)),'r','LineWidth',2);

plot3(mouseX_StopFail_FarJump_left(1,1:round(MT1_StopFail_FarJump_mn./frameRate)), ...
    mouseY_StopFail_FarJump_left(1,1:round(MT1_StopFail_FarJump_mn./frameRate)),...
    mouseT_StopFail_FarJump_left(1,1:round(MT1_StopFail_FarJump_mn./frameRate)),'--r','LineWidth',2);
plot3(mouseX_StopFail_FarJump_right(1,1:round(MT1_StopFail_FarJump_mn./frameRate)),...
    mouseY_StopFail_FarJump_right(1,1:round(MT1_StopFail_FarJump_mn./frameRate)),...
    mouseT_StopFail_FarJump_right(1,1:round(MT1_StopFail_FarJump_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('Test9_Trajectory2dXZ_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

view(90,0)
print(gcf,strcat('Test9_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_NearJump = mouseXYT(trl_StopCorr_NearStr,:, 1);
mouseX_StopFail_NearJump = mouseXYT(trl_StopFail_NearStr,:, 1);
mouseX_StopCorr_FarJump = mouseXYT(trl_StopCorr_FarStr,:, 1);
mouseX_StopFail_FarJump = mouseXYT(trl_StopFail_FarStr,:, 1);

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

mouseXdiff_StopCorr_NearJump = diff(mouseX_StopCorr_NearJump,1,2)
mouseXvel_StopCorr_NearJump = abs(mouseXdiff_StopCorr_NearJump./(frameRate/1000));
% mouseXvel_StopCorr_NearJump = (mouseXdiff_StopCorr_NearJump./(frameRate/1000));
[xVelvalCorrNear, xVellocCorrNear] = max(mouseXvel_StopCorr_NearJump');

mouseXdiff_StopFail_NearJump = diff(mouseX_StopFail_NearJump,1,2)
mouseXvel_StopFail_NearJump = abs(mouseXdiff_StopFail_NearJump./(frameRate/1000));
[xVelvalFailNear, xVellocFailNear] = max(mouseXvel_StopFail_NearJump');

mouseXdiff_StopCorr_FarJump = diff(mouseX_StopCorr_FarJump,1,2)
mouseXvel_StopCorr_FarJump = abs(mouseXdiff_StopCorr_FarJump./(frameRate/1000));
[xVelvalCorrFar, xVellocCorrFar] = max(mouseXvel_StopCorr_FarJump');

mouseXdiff_StopFail_FarJump = diff(mouseX_StopFail_FarJump,1,2)
mouseXvel_StopFail_FarJump = abs(mouseXdiff_StopFail_FarJump./(frameRate/1000));
[xVelvalFailFar, xVellocFailFar] = max(mouseXvel_StopFail_FarJump');

% 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 - mean([SSRT_NearJump,SSRT_FarJump])

figure();
plot((0:17:17*size(mouseXvel_GoCorr,2)-1),nanmean(mouseXvel_GoCorr),'-g')
hold on
plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0, 200],'--k')
plot([0,0],[0, 200],'-k')
plot([MT1_GoCorr_mn,MT1_GoCorr_mn],[0,200],'.-k')
plot((0:17:17*size(mouseXvel_StopCorr_NearJump,2)-1),nanmean(mouseXvel_StopCorr_NearJump),'-b')
plot((0:17:17*size(mouseXvel_StopCorr_FarJump,2)-1),nanmean(mouseXvel_StopCorr_FarJump),'--b')
plot((0:17:17*size(mouseXvel_StopFail_NearJump,2)-1),nanmean(mouseXvel_StopFail_NearJump),'-r')
plot((0:17:17*size(mouseXvel_StopFail_FarJump,2)-1),nanmean(mouseXvel_StopFail_FarJump),'--r')
plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0,200],'-k')
nanmean(TotRespT_GoCorr)
legend('Go','Stop','MoveOn','MoveEnd','SS-N','SS-F','FS-N','FS-F','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('Test9_VelocityAbsX_StopChange_smallTcirc.pdf'),'-dpdf','-r400');

% Calculate vertical (Y) velocity in px.s
mouseY_GoCorr = mouseXYT(trl_GoCorr,:, 2);
mouseY_StopCorr_NearJump = mouseXYT(trl_StopCorr_NearStr,:, 2);
mouseY_StopFail_NearJump = mouseXYT(trl_StopFail_NearStr,:, 2);
mouseY_StopCorr_FarJump = mouseXYT(trl_StopCorr_FarStr,:, 2);
mouseY_StopFail_FarJump = mouseXYT(trl_StopFail_FarStr,:, 2);

mouseYdiff_GoCorr = diff(mouseY_GoCorr,1,2)
mouseYvel_GoCorr = -(mouseYdiff_GoCorr./(frameRate/1000));
[yVelvalCorrGo, yVellocCorrGo] = max(mouseYvel_GoCorr');

mouseYdiff_StopCorr_NearJump = diff(mouseY_StopCorr_NearJump,1,2)
mouseYvel_StopCorr_NearJump = -(mouseYdiff_StopCorr_NearJump./(frameRate/1000));
[yVelvalCorrNear, yVellocCorrNear] = max(mouseYvel_StopCorr_NearJump');

mouseYdiff_StopFail_NearJump = diff(mouseY_StopFail_NearJump,1,2)
mouseYvel_StopFail_NearJump = -(mouseYdiff_StopFail_NearJump./(frameRate/1000));
[yVelvalFailNear, yVellocFailNear] = max(mouseYvel_StopFail_NearJump');

mouseYdiff_StopCorr_FarJump = diff(mouseY_StopCorr_FarJump,1,2)
mouseYvel_StopCorr_FarJump = -(mouseYdiff_StopCorr_FarJump./(frameRate/1000));
[yVelvalCorrFar, yVellocCorrFar] = max(mouseYvel_StopCorr_FarJump');

mouseYdiff_StopFail_FarJump = diff(mouseY_StopFail_FarJump,1,2)
mouseYvel_StopFail_FarJump = -(mouseYdiff_StopFail_FarJump./(frameRate/1000));
[yVelvalFailFar, yVellocFailFar] = max(mouseYvel_StopFail_FarJump');

figure();
plot((0:17:17*size(mouseYvel_GoCorr,2)-1),nanmean(mouseYvel_GoCorr),'-g')
hold on
plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[-1000, 1000],'--k')
plot([0,0],[-1000, 1000],'-k')
plot([MT1_GoCorr_mn,MT1_GoCorr_mn],[-1000,1000],'.-k')
plot((0:17:17*size(mouseYvel_StopCorr_NearJump,2)-1),nanmean(mouseYvel_StopCorr_NearJump),'-b')
plot((0:17:17*size(mouseYvel_StopCorr_FarJump,2)-1),nanmean(mouseYvel_StopCorr_FarJump),'--b')
plot((0:17:17*size(mouseYvel_StopFail_NearJump,2)-1),nanmean(mouseYvel_StopFail_NearJump),'-r')
plot((0:17:17*size(mouseYvel_StopFail_FarJump,2)-1),nanmean(mouseYvel_StopFail_FarJump),'--r')

legend('Go','Stop','MoveOn','MoveEnd','SS-N','SS-F','FS-N','FS-F','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([-2500, 2500]);
text(meanStopCue_MoveOn +10, 2200, 'Stop','FontSize',14,'Rotation', -90);
text(MT1_GoCorr_mn +10, 2200, 'Target Hit','FontSize',14,'Rotation', -90);
print(gcf,strcat('Test9_VelocityAbsY_StopChange_smallTcirc.pdf'),'-dpdf','-r400');


% Peak Y velocity
figure()
subplot(2,2,1)
bar([nanmean(yVelvalCorrGo),0, 0,0,0], 'k');
hold on
bar([0,nanmean(yVelvalCorrNear), 0,0,0],'b');
bar([0,0, nanmean(yVelvalCorrFar),0,0], 'b', 'LineStyle', '--');
bar([0,0,0,nanmean(yVelvalFailNear), 0],'r');
bar([0,0,0,0 nanmean(yVelvalFailFar)], 'r', 'LineStyle', '--');
er = errorbar([1,2,3,4,5],[nanmean(yVelvalCorrGo),nanmean(yVelvalCorrNear),nanmean(yVelvalCorrFar),nanmean(yVelvalFailNear),nanmean(yVelvalFailFar)],...
    [nanstd(yVelvalCorrGo),nanstd(yVelvalCorrNear), nanstd(yVelvalCorrFar),nanstd(yVelvalFailNear), nanstd(yVelvalFailFar)],'k');
er.LineStyle = 'none';
title('Peak Y velocity','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(yVelvalCorrGo)+1000)])

% Time of peak Y velocity
subplot(2,2,2)
bar([nanmean(yVellocCorrGo),0, 0,0,0] * frameRate, 'k');
hold on
bar([0,nanmean(yVellocCorrNear), 0,0,0] * frameRate,'b');
bar([0,0, nanmean(yVellocCorrFar),0,0] * frameRate, 'b', 'LineStyle', '--');
bar([0,0,0,nanmean(yVellocFailNear), 0] * frameRate,'r');
bar([0,0,0,0 nanmean(yVellocFailNear)] * frameRate, 'r', 'LineStyle', '--');
er = errorbar([1,2,3,4,5],[nanmean(yVellocCorrGo) * frameRate,nanmean(yVellocCorrNear) * frameRate, ...
    nanmean(yVellocCorrFar) * frameRate,nanmean(yVellocFailNear) * frameRate,nanmean(yVellocFailNear) * frameRate],...
    [nanstd(yVellocCorrGo) * frameRate,nanstd(yVellocCorrNear) * frameRate, ...
    nanstd(yVellocCorrFar) * frameRate,nanstd(yVellocFailNear) * frameRate, ...
    nanstd(yVellocFailNear) * 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-N','SS-F','FS-N','FS-F'})
ylabel('Time (ms)','FontSize',14);
ylim([0,round(nanmean(yVellocCorrGo * frameRate)+100)])

% Peak X velocity
subplot(2,2,3)
bar([nanmean(xVelvalCorrGo),0, 0,0,0], 'k');
hold on
bar([0,nanmean(xVelvalCorrNear), 0,0,0],'b');
bar([0,0, nanmean(xVelvalCorrFar),0,0], 'b', 'LineStyle', '--');
bar([0,0,0,nanmean(xVelvalFailNear), 0],'r');
bar([0,0,0,0 nanmean(xVelvalFailFar)], 'r', 'LineStyle', '--');
er = errorbar([1,2,3,4,5],[nanmean(xVelvalCorrGo),nanmean(xVelvalCorrNear),nanmean(xVelvalCorrFar),nanmean(xVelvalFailNear),nanmean(xVelvalFailFar)],...
    [nanstd(xVelvalCorrGo),nanstd(xVelvalCorrNear), nanstd(xVelvalCorrFar),nanstd(xVelvalFailNear), nanstd(xVelvalFailFar)],'k');
er.LineStyle = 'none';
title('Peak X velocity','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(xVelvalCorrGo)+1000)])

% Time of peak X velocity
subplot(2,2,4)
bar([nanmean(xVellocCorrGo),0, 0,0,0] * frameRate, 'k');
hold on
bar([0,nanmean(xVellocCorrNear), 0,0,0] * frameRate,'b');
bar([0,0, nanmean(xVellocCorrFar),0,0] * frameRate, 'b', 'LineStyle', '--');
bar([0,0,0,nanmean(xVellocFailNear), 0] * frameRate,'r');
bar([0,0,0,0 nanmean(xVellocFailNear)] * frameRate, 'r', 'LineStyle', '--');
er = errorbar([1,2,3,4,5],[nanmean(xVellocCorrGo) * frameRate,nanmean(xVellocCorrNear) * frameRate,...
    nanmean(xVellocCorrFar) * frameRate,nanmean(xVellocFailNear) * frameRate,...
    nanmean(xVellocFailNear) * frameRate],...
    [nanstd(xVellocCorrGo) * frameRate,nanstd(xVellocCorrNear) * frameRate,...
    nanstd(xVellocCorrFar) * frameRate,nanstd(xVellocFailNear) * frameRate,...
    nanstd(xVellocFailNear) * 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-N','SS-F','FS-N','FS-F'})
ylabel('Time (ms)','FontSize',14);
ylim([0,round(nanmean(xVellocCorrFar * frameRate)+ 300)])

print(gcf,strcat('Test9_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_NearJump(:,idx_100));
xVelvalFailNear100_mn  = nanmean(mouseXvel_StopFail_NearJump(:,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_NearJump(:,idx_100));
yVelvalFailNear100_mn  = nanmean(mouseYvel_StopFail_NearJump(:,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_NearJump(:,idx_100));
xVelvalFailNear100_std  = nanstd(mouseXvel_StopFail_NearJump(:,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_NearJump(:,idx_100));
yVelvalFailNear100_std  = nanstd(mouseYvel_StopFail_NearJump(:,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('Test9_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('Test9_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('Test9_VelocityFailSplitY_StopChange_smallTcirc.pdf'),'-dpdf','-r400');


%% Fast and slow correct trials
TotRespT_StopCorr_NearJump_med = nanmedian(TotRespT_StopCorr_NearJump);

% 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('Test9_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('Test9_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
mouseT_SSDnorm = mouseT_SSDnorm - dataTable.StopSignalDelay;

mouseXvel_SSDnorm_NearCorr = mouseXvel_StopCorr_NearJump;
mouseXvel_SSDnorm_NearFail = mouseXvel_StopFail_NearJump;
mouseXvel_SSDnorm_FarCorr = mouseXvel_StopCorr_FarJump;
mouseXvel_SSDnorm_FarFail = mouseXvel_StopFail_FarJump;

mouseT_SSDnorm_NearCorr = mouseT_SSDnorm(trl_StopCorr_NearStr,:)
mouseT_SSDnorm_NearFail = mouseT_SSDnorm(trl_StopFail_NearStr,:)
mouseT_SSDnorm_FarCorr = mouseT_SSDnorm(trl_StopCorr_FarStr,:)
mouseT_SSDnorm_FarFail = mouseT_SSDnorm(trl_StopFail_FarStr,:)

mouseT_SSDnorm_NearCorr(mouseT_SSDnorm_NearCorr < - frameRate) = NaN;
[valMin,locMin] = min(mouseT_SSDnorm_NearCorr')
[valMax,locMax] = max(mouseT_SSDnorm_NearCorr')

dat = NaN(size(mouseT_SSDnorm_NearCorr,1),size(mouseT_SSDnorm_NearCorr,2))

for i = 1:size(mouseT_SSDnorm_NearCorr,1)

    dat = mouseT_SSDnorm_NearCorr(i,locMin(i):locMax(i))
    mouseT_SSDnorm_NearCorr(i,1:length(dat)) = dat
    mouseT_SSDnorm_NearCorr(i,length(dat):end) = NaN
    
    dat = mouseXvel_SSDnorm_NearCorr(i,locMin(i):locMax(i))
    mouseXvel_SSDnorm_NearCorr(i,1:length(dat)) = dat
    mouseXvel_SSDnorm_NearCorr(i,length(dat):end) = NaN
    
end

mouseT_SSDnorm_NearCorr_mn = nanmean(mouseT_SSDnorm_NearCorr);
mouseXvel_SSDnorm_NearCorr_mn = nanmean(mouseXvel_SSDnorm_NearCorr);


for i = 1:size(mouseT_SSDnorm_NearFail,1)

    dat = mouseT_SSDnorm_NearFail(i,locMin(i):locMax(i))
    mouseT_SSDnorm_NearFail(i,1:length(dat)) = dat
    mouseT_SSDnorm_NearFail(i,length(dat):end) = NaN
    
    dat = mouseXvel_SSDnorm_NearFail(i,locMin(i):locMax(i))
    mouseXvel_SSDnorm_NearFail(i,1:length(dat)) = dat
    mouseXvel_SSDnorm_NearFail(i,length(dat):end) = NaN
    
end

mouseT_SSDnorm_NearFail_mn = nanmean(mouseT_SSDnorm_NearFail);
mouseXvel_SSDnorm_NearFail_mn = nanmean(mouseXvel_SSDnorm_NearFail);

for i = 1:size(mouseT_SSDnorm_FarCorr,1)

    dat = mouseT_SSDnorm_FarCorr(i,locMin(i):locMax(i))
    mouseT_SSDnorm_FarCorr(i,1:length(dat)) = dat
    mouseT_SSDnorm_FarCorr(i,length(dat):end) = NaN
    
    dat = mouseXvel_SSDnorm_FarCorr(i,locMin(i):locMax(i))
    mouseXvel_SSDnorm_FarCorr(i,1:length(dat)) = dat
    mouseXvel_SSDnorm_FarCorr(i,length(dat):end) = NaN
    
end

mouseT_SSDnorm_FarCorr_mn = nanmean(mouseT_SSDnorm_FarCorr);
mouseXvel_SSDnorm_FarCorr_mn = nanmean(mouseXvel_SSDnorm_FarCorr);


for i = 1:size(mouseT_SSDnorm_FarFail,1)

    dat = mouseT_SSDnorm_FarFail(i,locMin(i):locMax(i))
    mouseT_SSDnorm_FarFail(i,1:length(dat)) = dat
    mouseT_SSDnorm_FarFail(i,length(dat):end) = NaN
    
    dat = mouseXvel_SSDnorm_FarFail(i,locMin(i):locMax(i))
    mouseXvel_SSDnorm_FarFail(i,1:length(dat)) = dat
    mouseXvel_SSDnorm_FarFail(i,length(dat):end) = NaN
    
end

mouseT_SSDnorm_FarFail_mn = nanmean(mouseT_SSDnorm_FarFail);
mouseXvel_SSDnorm_FarFail_mn = nanmean(mouseXvel_SSDnorm_FarFail);

figure()
plot(mouseT_SSDnorm_NearCorr_mn(1:length(mouseXvel_SSDnorm_NearCorr_mn)),mouseXvel_SSDnorm_NearCorr_mn,'b')
hold on
plot(mouseT_SSDnorm_NearFail_mn(1:length(mouseXvel_SSDnorm_NearFail_mn)),mouseXvel_SSDnorm_NearFail_mn,'--b')
plot(mouseT_SSDnorm_FarCorr_mn(1:length(mouseXvel_SSDnorm_FarCorr_mn)),mouseXvel_SSDnorm_FarCorr_mn,'r')
plot(mouseT_SSDnorm_FarFail_mn(1:length(mouseXvel_SSDnorm_FarFail_mn)),mouseXvel_SSDnorm_FarFail_mn,'--r')
xlim([0, 450])

a = mouseXvel_SSDnorm_NearCorr_mn - mouseXvel_SSDnorm_NearFail_mn;
b = mouseXvel_SSDnorm_NearCorr_mn - mouseXvel_SSDnorm_FarCorr_mn;
c = mouseXvel_SSDnorm_NearCorr_mn - mouseXvel_SSDnorm_FarFail_mn;

figure()
plot(mouseT_SSDnorm_NearCorr_mn(1:length(mouseXvel_SSDnorm_NearFail_mn)),a)
hold on
plot(mouseT_SSDnorm_NearCorr_mn(1:length(mouseXvel_SSDnorm_NearFail_mn)),b)
plot(mouseT_SSDnorm_NearCorr_mn(1:length(mouseXvel_SSDnorm_NearFail_mn)),c)
xlim([0, 450])