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

%% 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_PvO_Jstop_x09a.csv
%
% Auto-generated by MATLAB on 06-Apr-2021 15:50:14

%% Setup the Import Options
opts = delimitedTextImportOptions("NumVariables", 48);

% 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", "Targ2Ycent", "Targ1XLcent", "Targ2XLcent", "Targ1XRcent", "Targ2XRcent", "click_x", "click_y", "CueDirection", "TrialType", "Staircase", "BlockName", "BlockNo", "Xpos", "Ypos", "IsHome", "ClickX", "ClickY", "TooSoon", "Jitter", "ReactTime", "MoveTime", "MoveTimeT2", "TargetHit", "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", "categorical", "categorical", "categorical", "categorical", "double", "double", "double", "categorical", "double", "double", "categorical", "double", "double", "double", "double", "categorical", "categorical", "double", "double", "double", "categorical", "double"];
opts = setvaropts(opts, 11, "WhitespaceRule", "preserve");
opts = setvaropts(opts, [12, 44, 45, 46], "TrimNonNumeric", true);
opts = setvaropts(opts, [12, 44, 45, 46], "ThousandsSeparator", ",");
opts = setvaropts(opts, [1, 2, 3, 7, 8, 11, 13, 15, 16, 17, 18, 27, 28, 29, 30, 34, 37, 42, 43, 47], "EmptyFieldRule", "auto");
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
%
fileDat = "/Users/riccihannah/Google Drive/Online_Stop_Signal/jspsych-psychophysics-master/Data/All_PvO_Jstop_x09a.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.MoveTime(dataTable.MoveTime == 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.TargetHit == 'Left' | ...
    dataTable.BlockName == 'MainStopExp' & dataTable.TrialType == 'Go' & dataTable.TargetHit == 'Right';
trl_GoCorr =  dataTable.BlockName == 'MainStopExp' & dataTable.Outcome == 'Correct_Go' & dataTable.TooSoon == 'false';
trl_GoErr =  dataTable.BlockName == 'MainStopExp' & dataTable.TrialType == 'Go' & dataTable.TargetHit == 'Undefined'; 


% Stop trials with the Nearpad staircase
trl_StopAll_HomeStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair' & ~isnan(dataTable.StopSignalDelay);
trl_StopCorr_HomeStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair' & dataTable.Outcome == 'Correct_Stop_Home';
trl_StopFail_HomeStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair' & dataTable.Outcome == 'Failed_Stop_Home';
% any where T2 < T1 (weird squiggle overcorrection) and therefore wrongly
% classified as fail
trl_StopCorrt_HomeStr_T2lessT1 = find(dataTable.MoveTimeT2(trl_StopFail_HomeStr) < dataTable.MoveTime(trl_StopFail_HomeStr));

% Stop trials with the Far staircase
trl_StopAll_TargetStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' & ~isnan(dataTable.StopSignalDelay);
trl_StopCorr_TargetStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' & dataTable.Outcome == 'Correct_Stop_Home' | ...
    dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' & dataTable.Outcome == 'Failed_Stop_Home';
trl_StopFail_TargetStr = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' & dataTable.Outcome == 'Failed_Stop_Target';

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

%% Get basic data
% All RTs and MT1s
RT_GoAll = dataTable.ReactTime(trl_GoAll);
MT_GoAll = dataTable.MoveTime(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_MT          = prctile(MT_GoAll,[25 75]);
trl_MT_outlier = (dataTable.MoveTime < (prctile_MT(1) - 1.5 * iqr(MT_GoAll)) | ...
    dataTable.MoveTime>(prctile_MT(2) + 1.5 * iqr(MT_GoAll)) | ...
    dataTable.MoveTime < 100);
dataTable.MoveTime(dataTable.MoveTime < (prctile_MT(1) - 1.5 * iqr(MT_GoAll)) | ...
    dataTable.MoveTime>(prctile_MT(2) + 1.5 * iqr(MT_GoAll)) | ...
    dataTable.MoveTime < 100) = NaN;

% Go RT and MT
RT_GoCorr = dataTable.ReactTime(trl_GoCorr);
RT_GoErr = dataTable.ReactTime(trl_GoErr);
MT_GoCorr = dataTable.MoveTime(trl_GoCorr);
MT_GoErr = dataTable.MoveTime(trl_GoErr);

% Correct Stop RT (Target staircase)
RT_StopCorr_TargetStair = dataTable.ReactTime(trl_StopCorr_TargetStr);
MT_StopCorr_TargetStair = dataTable.MoveTime(trl_StopCorr_TargetStr);

% Failed Stop RT and MT
RT_StopFail_HomeStair = dataTable.ReactTime(trl_StopFail_HomeStr);
MT_StopFail_HomeStair = dataTable.MoveTime(trl_StopFail_HomeStr);
RT_StopFail_TargetStair = dataTable.ReactTime(trl_StopFail_TargetStr);
MT_StopFail_TargetStair = dataTable.MoveTime(trl_StopFail_TargetStr);

% Total response times
TotRespT_GoCorr = RT_GoAll + MT_GoAll;
TotRespT_StopFail_HomeStair = RT_StopFail_HomeStair + MT_StopFail_HomeStair;
TotRespT_StopFail_TargetStair = RT_StopFail_TargetStair + MT_StopFail_TargetStair;

% Mean Go RT and MT
RT_GoCorr_mn = nanmean(RT_GoCorr);
MT_GoCorr_mn = nanmean(MT_GoCorr);

% Mean Correct Stop RT (Target staircase)
RT_StopCorr_TargetStair_mn = nanmean(RT_StopCorr_TargetStair);
MT_StopCorr_TargetStair_mn = nanmean(MT_StopCorr_TargetStair);

% Mean Failed Stop Change RT and MT
RT_StopFail_HomeStair_mn = nanmean(RT_StopFail_HomeStair);
MT_StopFail_HomeStair_mn = nanmean(MT_StopFail_HomeStair);
RT_StopFail_TargetStair_mn = nanmean(RT_StopFail_TargetStair);
MT_StopFail_TargetStair_mn = nanmean(MT_StopFail_TargetStair);

% All SSDs
SSD_Stop_HomeStair = dataTable.StopSignalDelay(trl_StopAll_HomeStr);
SSD_Stop_TargetStair = dataTable.StopSignalDelay(trl_StopAll_TargetStr);

% Mean SSD
SSD_Stop_HomeStair_mn = nanmean(SSD_Stop_HomeStair);
SSD_Stop_TargetStair_mn = nanmean(SSD_Stop_TargetStair);

% Stop success
pStop_HomeStair = (sum(trl_StopCorr_HomeStr) / sum(sum([trl_StopCorr_HomeStr,trl_StopFail_HomeStr]))) *100;
pStop_TargetStair = (sum(trl_StopCorr_TargetStr) / sum(sum([trl_StopCorr_TargetStr,trl_StopFail_TargetStr]))) *100;

%% Calculate SSRT for RTs and MTs
% Near
if ~isempty(RT_GoErr)
    dataTable.ReactTime(trl_GoErr) = nanmax(RT_GoCorr);
    dataTable.MoveTime(trl_GoErr) = nanmax(MT_GoCorr);
    RT_GoAll = dataTable.ReactTime(trl_GoAll);% Max Go RT
    MT_GoAll = dataTable.MoveTime(trl_GoAll);
    TotRespT_GoCorr = RT_GoAll + MT_GoAll;
end

% Home stair case - using RTs
sort_RT = sort(RT_GoCorr(~isnan(RT_GoCorr)));
nth_RT_index_HomeStair  = round((pStop_HomeStair/100).*length(RT_GoCorr));
nth_RT_HomeStair        = sort_RT(nth_RT_index_HomeStair);
SSRT_HomeStair          = nth_RT_HomeStair - SSD_Stop_HomeStair_mn


% Target stair case using Total response time 
sort_TotRespT            = sort(TotRespT_GoCorr(~isnan(TotRespT_GoCorr)));
nth_TRT_index_TargetStair = round((pStop_TargetStair/100).*length(sort_TotRespT));
nth_TRT_TargetStair        = sort_TotRespT(nth_TRT_index_TargetStair);
SSRT_TargetStair         = nth_TRT_TargetStair - SSD_Stop_TargetStair_mn


%% Plot RTs and MTs
figure()

subplot(2,2,1);
histogram(RT_GoCorr,'BinWidth',25, 'Normalization','probability');
hold on
histogram((0:25:200),'BinWidth',25, 'Normalization','probability');
histogram(RT_StopCorr_TargetStair,'BinWidth',25, 'Normalization','probability');
title('RTs: Go & Corr. Stop');
xlabel('Reaction Times (ms)');
ylabel('Count');
xlim([0,700]);
ylim([0,0.4]);
tx1 = (['Go: ' num2str(round(RT_GoCorr_mn)) 'ms']);
tx2 = ('SS-H: N/A ms');
tx3 = (['SS-T: ' num2str(round(RT_StopCorr_TargetStair_mn)) 'ms']);
text(40, 0.38,tx1);
text(40, 0.32,tx2);
text(40, 0.26,tx3);

subplot(2,2,2)
histogram(RT_GoCorr,'BinWidth',25, 'Normalization','probability');
hold on
histogram(RT_StopFail_HomeStair,'BinWidth',25, 'Normalization','probability');
histogram(RT_StopFail_TargetStair,'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-H: ' num2str(round(RT_StopFail_HomeStair_mn)) 'ms']);
tx3 = (['FS-T: ' num2str(round(RT_StopFail_TargetStair_mn)) 'ms']);
text(40, 0.38,tx1);
text(40, 0.32,tx2);
text(40, 0.26,tx3);

subplot(2,2,3)
histogram(MT_GoCorr,'BinWidth',25, 'Normalization','probability')
hold on
histogram(MT_StopFail_HomeStair,'BinWidth',25, 'Normalization','probability');
histogram(MT_StopFail_TargetStair,'BinWidth',25, 'Normalization','probability');
title('MTs: Go & Fail. Stopp');
xlabel('Movement Times (ms)');
ylabel('Count');
xlim([0,800]);
ylim([0,0.4]);
tx1 = (['Go MT: ' num2str(round(MT_GoCorr_mn)) 'ms']);
tx2 = ('SS-H: N/A ms');
tx3 = (['FS-F MT: ' num2str(round(MT_StopFail_TargetStair_mn)) 'ms']);
text(20, 0.38,tx1);
text(20, 0.32,tx2);
text(20, 0.26,tx3);

subplot(2,2,4);
histogram(TotRespT_GoCorr,'BinWidth',20, 'Normalization','probability')
hold on
histogram((0:25:200),'BinWidth',25, 'Normalization','probability');
histogram(TotRespT_StopFail_TargetStair,'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-H: ' num2str(round(nanmean(TotRespT_StopFail_HomeStair(TotRespT_StopFail_HomeStair > 500)))) 'ms']);
tx3 = (['FS-T: ' num2str(round(nanmean(TotRespT_StopFail_TargetStair(TotRespT_StopFail_TargetStair > 500)))) 'ms']);
text(40, 0.28,tx1);
text(40, 0.22,tx2);
text(40, 0.16,tx3);

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

%% Plot stopping staircases
% Need to first calculate pStop at each SSD
% how many SSDs?
SSD_uniq_HomeStair = unique(SSD_Stop_HomeStair);
SSD_uniq_TargetStair = unique(SSD_Stop_TargetStair);
max_ntrls = max(length(SSD_uniq_HomeStair), length(SSD_uniq_TargetStair));

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

% Home stair case
for i = 1:length(SSD_uniq_HomeStair)
    currentSSD = SSD_uniq_HomeStair(i);
    %     count how many trials for that SSD in that stair case
    idx_all = dataTable.StopSignalDelay(trl_StopAll_HomeStr) == currentSSD;
    nTrls_all = sum(idx_all);
    idx_success = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair' & ...
        dataTable.StopSignalDelay == currentSSD & dataTable.Outcome == 'Correct_Stop_Home';
    nTrls_correct = sum(idx_success);
    pStop_SSD(i,1 ) = (nTrls_correct / nTrls_all) * 100;
    
    idx_fail = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair' & ...
        dataTable.StopSignalDelay == currentSSD & dataTable.Outcome == 'Failed_Stop_Home';
    FailedStop_RT_ToT_SSD(i,1 ) = nanmean(dataTable.ReactTime(idx_fail));
end

% Far stair case
for i = 1:length(SSD_uniq_TargetStair)
    currentSSD = SSD_uniq_TargetStair(i);
    %     count how many trials for that SSD in that stair case
    idx_all = dataTable.StopSignalDelay(trl_StopAll_TargetStr) == currentSSD;
    nTrls_all = sum(idx_all);
    idx_success = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' & ...
        dataTable.StopSignalDelay == currentSSD & dataTable.Outcome == 'Correct_Stop_Home' | ...
        dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' & ...
        dataTable.StopSignalDelay == currentSSD & dataTable.Outcome == 'Failed_Stop_Home';
    nTrls_correct = sum(idx_success);
    pStop_SSD(i,2) = (nTrls_correct / nTrls_all) * 100;
    idx_fail = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' & ...
        dataTable.StopSignalDelay == currentSSD & dataTable.Outcome == 'Failed_Stop_Target';
    FailedStop_RT_ToT_SSD(i,2 ) = nanmean(dataTable.ReactTime(idx_fail) + dataTable.MoveTime(idx_fail));
end


idx_HomeStair = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair' & ~isnan(dataTable.StopSignalDelay);
idx_TargetStair = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' & ~isnan(dataTable.StopSignalDelay);

figure()
plot(dataTable.StopSignalDelay(idx_HomeStair),  'b');
hold on
plot(dataTable.StopSignalDelay(idx_TargetStair),  '--b');
lsline;
title('Staircasing','FontSize',14);
xlabel('Trial','FontSize',14);
ylabel('Stop signal delay (ms)','FontSize',14);
% xlim([0,max(SSD_uniq_TargetStair)]);
ylim([0,max([SSD_uniq_HomeStair;SSD_uniq_TargetStair])]);
legend('Home','Target','FontSize',14)
legend boxoff
print(gcf,strcat('Test1_StaircaseTracking_PvO_JumpStop.pdf'),'-dpdf','-r400');

figure()
scatter(SSD_uniq_HomeStair, pStop_SSD(1:length(SSD_uniq_HomeStair),1), 50, 'filled', 'b');
hold on
scatter(SSD_uniq_TargetStair, pStop_SSD(1:length(SSD_uniq_TargetStair),2), 50, 'b');
plot([0, max(SSD_uniq_TargetStair)],[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_TargetStair)]);
ylim([0,100]);
legend('Home','Target','50%','Hfit','Tfit','FontSize',14)
legend boxoff
print(gcf,strcat('Test1_StopFunction_PvO_JumpStop.pdf'),'-dpdf','-r400');

figure()
scatter(SSD_uniq_HomeStair, FailedStop_RT_ToT_SSD(1:length(SSD_uniq_HomeStair),1), 50, 'filled', 'b');
hold on
scatter(SSD_uniq_TargetStair, FailedStop_RT_ToT_SSD(1:length(SSD_uniq_TargetStair),2), 50, 'filled', 'r');
plot([0, max(SSD_uniq_TargetStair)],[nanmean(RT_GoCorr_mn), nanmean(RT_GoCorr_mn)],'--k');
plot([0, max(SSD_uniq_TargetStair)],[nanmean(TotRespT_GoCorr), nanmean(TotRespT_GoCorr)],'--k');
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_TargetStair)]);
ylim([0,nanmean(TotRespT_GoCorr)+100]);
legend('Home','Target','Hfit','Tfit','FontSize',14, 'location', 'SouthEast')
legend boxoff

print(gcf,strcat('Test1_SSD_FSMT_PvO_JumpStop.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,0, 0,0,0],'b');
bar([0,0, RT_StopCorr_TargetStair_mn,0,0], 'b','LineStyle','--');
bar([0,0,0,RT_StopFail_HomeStair_mn, 0],'r');
bar([0,0,0,0 RT_StopFail_TargetStair_mn], 'r','LineStyle','--');
er = errorbar([1,2,3,4,5],[RT_GoCorr_mn,0, RT_StopCorr_TargetStair_mn, RT_StopFail_HomeStair_mn,RT_StopFail_TargetStair_mn],...
    [nanstd(RT_GoCorr),0, nanstd(RT_StopCorr_TargetStair),nanstd(RT_StopFail_HomeStair), nanstd(RT_StopFail_TargetStair)],'k');
er.LineStyle = 'none';
title('React. Time','FontSize',14);
xlabel('Staircase','FontSize',14);
xticks([1 2 3 4 5])
xticklabels({'Go','SSH','SST','FSH','FST'})
ylabel('RT (ms)','FontSize',14);
ylim([200,round(RT_GoCorr_mn+100)]);

subplot(2,3,2)
bar([MT_GoCorr_mn,0, 0,0,0], 'k');
hold on
bar([0,0, 0,0,0],'b');
bar([0,0, 0,0,0],'b' ,'LineStyle','--');
bar([0,0,0,MT_StopFail_HomeStair_mn,0],'r');
bar([0,0,0,0, MT_StopFail_TargetStair_mn], 'r','LineStyle','--');
er = errorbar([1,2,3,4,5],[MT_GoCorr_mn, 0, 0,MT_StopFail_HomeStair_mn,MT_StopFail_TargetStair_mn],...
    [nanstd(MT_GoCorr), 0, 0, nanstd(MT_StopFail_HomeStair), nanstd(MT_StopFail_HomeStair)],'k');
er.LineStyle = 'none';
title('Move. Time','FontSize',14);
xlabel('Staircase','FontSize',14);
xticks([1 2 3 4 5])
xticklabels({'Go','SSH','SST','FSH','FST'})
ylabel('MT (ms)','FontSize',14);
ylim([200,round(MT_GoCorr_mn+100)]);


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

subplot(2,3,4)
bar([pStop_HomeStair,0], 'b');
hold on
bar([0,pStop_TargetStair], '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_HomeStair_mn,0], 'b');
hold on
bar([0,SSD_Stop_TargetStair_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_HomeStair_mn;SSD_Stop_TargetStair_mn])+20)]);

subplot(2,3,6)
bar([SSRT_HomeStair,0], 'b');
hold on
bar([0,SSRT_TargetStair], '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_TargetStair+20)]);

print(gcf,strcat('Test1_MeanBehav_PvO_JumpStop.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
frameRate = nanmean(dataTable.avg_frame_time);
mouseX = mouseXYT(:,:,1);
mouseY = mouseXYT(:,:,2);
mouseT = mouseXYT(:,:,3);

TotRespT_T1_all = round(dataTable.ReactTime + dataTable.MoveTime);
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 * frameRate) | ...
    mouseT(:,1) < dataTable.ReactTime - (2 * frameRate);
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) == 'Correct_Stop_Home' & dataTable.Staircase(i) == 'HomeStair'
        final_datpoint = Yloc(i);
        color = 'b';
    elseif dataTable.Outcome(i) == 'Failed_Stop_Home' & dataTable.Staircase(i) == 'HomeStair'
        final_datpoint = size(mouseX,2);
        color = 'r';
    elseif dataTable.Outcome(i) == 'Failed_Stop_Home' & dataTable.Staircase(i) == 'TargetStair'
        final_datpoint = Yloc(i);
        color = '--b';
    elseif dataTable.Outcome(i) == 'Failed_Stop_Target' & dataTable.Staircase(i) == 'TargetStair'
        final_datpoint = size(mouseX,2);
        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('Test1_Trajectory3d_PvO_JumpStop.pdf'),'-dpdf','-r400');

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

% Home
trl_StopCorr_HomeStr_left = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair'...
    & dataTable.Outcome == 'Correct_Stop_Home' & dataTable.CueDirection == 'Left';
trl_StopCorr_HomeStr_right = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair'...
    & dataTable.Outcome == 'Correct_Stop_Home' & dataTable.CueDirection == 'Right';
trl_StopFail_HomeStr_left = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair'...
    & dataTable.Outcome == 'Failed_Stop_Home' & dataTable.CueDirection == 'Left' | ...
    dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair'...
    & dataTable.Outcome == 'Failed_Stop_Target' & dataTable.CueDirection == 'Left';
trl_StopFail_HomeStr_right = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair'...
    & dataTable.Outcome == 'Failed_Stop' & dataTable.CueDirection == 'Right' | ...
    dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'HomeStair'...
    & dataTable.Outcome == 'Failed_Stop_Home' & dataTable.CueDirection == 'Right';
% Target
trl_StopCorr_TargetStr_left = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' &...
    dataTable.Outcome == 'Correct_Stop_Home' & dataTable.CueDirection == 'Left' |...
    dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' &...
    dataTable.Outcome == 'Failed_Stop_Home' & dataTable.CueDirection == 'Left';
trl_StopCorr_TargetStr_right = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' &...
    dataTable.Outcome == 'Correct_Stop_Home' & dataTable.CueDirection == 'Right' |...
    dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair' &...
    dataTable.Outcome == 'Failed_Stop_Home' & dataTable.CueDirection == 'Right';
trl_StopFail_TargetStr_left = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair'...
    & dataTable.Outcome == 'Failed_Stop_Target' & dataTable.CueDirection == 'Left';
trl_StopFail_TargetStr_right = dataTable.BlockName == 'MainStopExp' & dataTable.Staircase == 'TargetStair'...
    & dataTable.Outcome == 'Failed_Stop_Target' & dataTable.CueDirection == 'Right';


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

mouseX_StopCorr_HomeStair_left = nanmean(mouseX(trl_StopCorr_HomeStr_left,:));
mouseX_StopCorr_HomeStair_right = nanmean(mouseX(trl_StopCorr_HomeStr_right,:));

mouseX_StopCorr_TargetStair_left = nanmean(mouseX(trl_StopCorr_TargetStr_left,:));
mouseX_StopCorr_TargetStair_right = nanmean(mouseX(trl_StopCorr_TargetStr_right,:));

mouseX_StopFail_HomeStair_left = nanmean(mouseX(trl_StopFail_HomeStr_left,:));
mouseX_StopFail_HomeStair_right = nanmean(mouseX(trl_StopFail_HomeStr_right,:));

mouseX_StopFail_TargetStair_left = nanmean(mouseX(trl_StopFail_TargetStr_left,:));
mouseX_StopFail_TargetStair_right = nanmean(mouseX(trl_StopFail_TargetStr_right,:));

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

mouseY_StopCorr_HomeStair_left = nanmean(mouseY(trl_StopCorr_HomeStr_left,:));
mouseY_StopCorr_HomeStair_right = nanmean(mouseY(trl_StopCorr_HomeStr_right,:));

mouseY_StopCorr_TargetStair_left = nanmean(mouseY(trl_StopCorr_TargetStr_left,:));
mouseY_StopCorr_TargetStair_right = nanmean(mouseY(trl_StopCorr_TargetStr_right,:));

mouseY_StopFail_HomeStair_left = nanmean(mouseY(trl_StopFail_HomeStr_left,:));
mouseY_StopFail_HomeStair_right = nanmean(mouseY(trl_StopFail_HomeStr_right,:));

mouseY_StopFail_TargetStair_left = nanmean(mouseY(trl_StopFail_TargetStr_left,:));
mouseY_StopFail_TargetStair_right = nanmean(mouseY(trl_StopFail_TargetStr_right,:));


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

mouseT_StopCorr_HomeStair_left = nanmean(mouseT(trl_StopCorr_HomeStr_left,:));
mouseT_StopCorr_HomeStair_right = nanmean(mouseT(trl_StopCorr_HomeStr_right,:));

mouseT_StopCorr_TargetStair_left = nanmean(mouseT(trl_StopCorr_TargetStr_left,:));
mouseT_StopCorr_TargetStair_right = nanmean(mouseT(trl_StopCorr_TargetStr_right,:));

mouseT_StopFail_HomeStair_left = nanmean(mouseT(trl_StopFail_HomeStr_left,:));
mouseT_StopFail_HomeStair_right = nanmean(mouseT(trl_StopFail_HomeStr_right,:));

mouseT_StopFail_TargetStair_left = nanmean(mouseT(trl_StopFail_TargetStr_left,:));
mouseT_StopFail_TargetStair_right = nanmean(mouseT(trl_StopFail_TargetStr_right,:));

frameRate = nanmean(dataTable.avg_frame_time);

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

plot3(mouseX_StopCorr_HomeStair_left(1,1:round(MT_GoCorr_mn./frameRate)), ...
    mouseY_StopCorr_HomeStair_left(1,1:round(MT_GoCorr_mn./frameRate)),...
    mouseT_StopCorr_HomeStair_left(1,1:round(MT_GoCorr_mn./frameRate)),'b','LineWidth',2);
plot3(mouseX_StopCorr_HomeStair_right(1,1:round(MT_GoCorr_mn./frameRate)),...
    mouseY_StopCorr_HomeStair_right(1,1:round(MT_GoCorr_mn./frameRate)),...
    mouseT_StopCorr_HomeStair_right(1,1:round(MT_GoCorr_mn./frameRate)),'b','LineWidth',2);

plot3(mouseX_StopCorr_TargetStair_left(1,1:round(MT_GoCorr_mn./frameRate)+10), ... % + 10 - need to sort our precisely when
    mouseY_StopCorr_TargetStair_left(1,1:round(MT_GoCorr_mn./frameRate)+10),...
    mouseT_StopCorr_TargetStair_left(1,1:round(MT_GoCorr_mn./frameRate)+10),'--b','LineWidth',2);
plot3(mouseX_StopCorr_TargetStair_right(1,1:round(MT_GoCorr_mn./frameRate)+10),...
    mouseY_StopCorr_TargetStair_right(1,1:round(MT_GoCorr_mn./frameRate)+10),...
    mouseT_StopCorr_TargetStair_right(1,1:round(MT_GoCorr_mn./frameRate)+10),'--b','LineWidth',2);

plot3(mouseX_StopFail_HomeStair_left(1,1:round(MT_GoCorr_mn./frameRate)), ...
    mouseY_StopFail_HomeStair_left(1,1:round(MT_GoCorr_mn./frameRate)),...
    mouseT_StopFail_HomeStair_left(1,1:round(MT_GoCorr_mn./frameRate)),'r','LineWidth',2);
plot3(mouseX_StopFail_HomeStair_right(1,1:round(MT_GoCorr_mn./frameRate)),...
    mouseY_StopFail_HomeStair_right(1,1:round(MT_GoCorr_mn./frameRate)),...
    mouseT_StopFail_HomeStair_right(1,1:round(MT_GoCorr_mn./frameRate)),'r','LineWidth',2);

plot3(mouseX_StopFail_TargetStair_left(1,1:round(MT_StopFail_TargetStair_mn./frameRate)), ...
    mouseY_StopFail_TargetStair_left(1,1:round(MT_StopFail_TargetStair_mn./frameRate)),...
    mouseT_StopFail_TargetStair_left(1,1:round(MT_StopFail_TargetStair_mn./frameRate)),'--r','LineWidth',2);
plot3(mouseX_StopFail_TargetStair_right(1,1:round(MT_StopFail_TargetStair_mn./frameRate)),...
    mouseY_StopFail_TargetStair_right(1,1:round(MT_StopFail_TargetStair_mn./frameRate)),...
    mouseT_StopFail_TargetStair_right(1,1:round(MT_StopFail_TargetStair_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('Test1_Trajectory2dXZ_PvO_JumpStop.pdf'),'-dpdf','-r400');

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



%% Plot velocities for all conditions

% Calculate lateral (X) velocity in px.s
mouseX_GoCorr = mouseXYT(trl_GoCorr,:, 1);
mouseX_StopCorr_HomeStair = mouseXYT(trl_StopCorr_HomeStr,:, 1);
mouseX_StopFail_HomeStair = mouseXYT(trl_StopFail_HomeStr,:, 1);
mouseX_StopCorr_TargetStair = mouseXYT(trl_StopCorr_TargetStr,:, 1);
mouseX_StopFail_TargetStair = mouseXYT(trl_StopFail_TargetStr,:, 1);

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

mouseXdiff_StopCorr_HomeStair = diff(mouseX_StopCorr_HomeStair,1,2)
mouseXvel_StopCorr_HomeStair = abs(mouseXdiff_StopCorr_HomeStair./(frameRate/1000));
% mouseXvel_StopCorr_HomeStair = (mouseXdiff_StopCorr_HomeStair./(frameRate/1000));
[xVelvalCorrNear, xVellocCorrNear] = max(mouseXvel_StopCorr_HomeStair');

mouseXdiff_StopFail_HomeStair = diff(mouseX_StopFail_HomeStair,1,2)
mouseXvel_StopFail_HomeStair = abs(mouseXdiff_StopFail_HomeStair./(frameRate/1000));
[xVelvalFailNear, xVellocFailNear] = max(mouseXvel_StopFail_HomeStair');

mouseXdiff_StopCorr_TargetStair = diff(mouseX_StopCorr_TargetStair,1,2)
mouseXvel_StopCorr_TargetStair = abs(mouseXdiff_StopCorr_TargetStair./(frameRate/1000));
[xVelvalCorrFar, xVellocCorrFar] = max(mouseXvel_StopCorr_TargetStair');

mouseXdiff_StopFail_TargetStair = diff(mouseX_StopFail_TargetStair,1,2)
mouseXvel_StopFail_TargetStair = abs(mouseXdiff_StopFail_TargetStair./(frameRate/1000));
[xVelvalFailFar, xVellocFailFar] = max(mouseXvel_StopFail_TargetStair');

% 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 =  MT_GoCorr_mn - mean([SSRT_HomeStair,SSRT_TargetStair])

figure();
plot((0:frameRate:frameRate*size(mouseXvel_GoCorr,2)-1),nanmean(mouseXvel_GoCorr),'-g')
hold on
plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0, 500],'--k')
plot([0,0],[0, 500],'-k')
plot([MT_GoCorr_mn,MT_GoCorr_mn],[0,200],'.-k')
plot((0:frameRate:frameRate*size(mouseXvel_StopCorr_HomeStair,2)-1),nanmean(mouseXvel_StopCorr_HomeStair),'-b')
plot((0:frameRate:frameRate*size(mouseXvel_StopCorr_TargetStair,2)-1),nanmean(mouseXvel_StopCorr_TargetStair),'--b')
plot((0:frameRate:frameRate*size(mouseXvel_StopFail_HomeStair,2)-1),nanmean(mouseXvel_StopFail_HomeStair),'-r')
plot((0:frameRate:frameRate*size(mouseXvel_StopFail_TargetStair,2)-1),nanmean(mouseXvel_StopFail_TargetStair),'--r')
plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0,500],'-k')
nanmean(TotRespT_GoCorr)
legend('Go','Stop','MoveOn','MoveEnd','SSH','SST','FSH','FST','location','NorthWest','FontSize',14);
xlabel('Time from movement onset (ms)','FontSize',14);
ylabel('X velocity (px.s)','FontSize',14);
xlim([-100, MT_GoCorr_mn + 100]);
ylim([0, nanmax(nanmean(mouseXvel_GoCorr))+100]);
text(meanStopCue_MoveOn +10, 150, 'Stop','FontSize',14,'Rotation', -90);
text(MT_GoCorr_mn +10, 150, 'Target Hit','FontSize',14,'Rotation', -90);
print(gcf,strcat('Test1_VelocityAbsX_PvO_JumpStop.pdf'),'-dpdf','-r400');

% Calculate vertical (Y) velocity in px.s
mouseY_GoCorr = mouseXYT(trl_GoCorr,:, 2);
mouseY_StopCorr_HomeStair = mouseXYT(trl_StopCorr_HomeStr,:, 2);
mouseY_StopFail_HomeStair = mouseXYT(trl_StopFail_HomeStr,:, 2);
mouseY_StopCorr_TargetStair = mouseXYT(trl_StopCorr_TargetStr,:, 2);
mouseY_StopFail_TargetStair = mouseXYT(trl_StopFail_TargetStr,:, 2);

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

mouseYdiff_StopCorr_HomeStair = diff(mouseY_StopCorr_HomeStair,1,2)
mouseYvel_StopCorr_HomeStair = -(mouseYdiff_StopCorr_HomeStair./(frameRate/1000));
[yVelvalCorrNear, yVellocCorrNear] = max(mouseYvel_StopCorr_HomeStair');

mouseYdiff_StopFail_HomeStair = diff(mouseY_StopFail_HomeStair,1,2)
mouseYvel_StopFail_HomeStair = -(mouseYdiff_StopFail_HomeStair./(frameRate/1000));
[yVelvalFailNear, yVellocFailNear] = max(mouseYvel_StopFail_HomeStair');

mouseYdiff_StopCorr_TargetStair = diff(mouseY_StopCorr_TargetStair,1,2)
mouseYvel_StopCorr_TargetStair = -(mouseYdiff_StopCorr_TargetStair./(frameRate/1000));
[yVelvalCorrFar, yVellocCorrFar] = max(mouseYvel_StopCorr_TargetStair');

mouseYdiff_StopFail_TargetStair = diff(mouseY_StopFail_TargetStair,1,2)
mouseYvel_StopFail_TargetStair = -(mouseYdiff_StopFail_TargetStair./(frameRate/1000));
[yVelvalFailFar, yVellocFailFar] = max(mouseYvel_StopFail_TargetStair');

figure();
plot((0:frameRate:frameRate*size(mouseYvel_GoCorr,2)-1),nanmean(mouseYvel_GoCorr),'-g');
hold on
plot([meanStopCue_MoveOn,meanStopCue_MoveOn],[0, 1000],'--k')
plot([0,0],[-1000, 1000],'-k')
plot([MT_GoCorr_mn,MT_GoCorr_mn],[0,1000],'.-k')
plot((0:frameRate:frameRate*size(mouseYvel_StopCorr_HomeStair,2)-1),nanmean(mouseYvel_StopCorr_HomeStair),'-b');
plot((0:frameRate:frameRate*size(mouseYvel_StopCorr_TargetStair,2)-1),nanmean(mouseYvel_StopCorr_TargetStair),'--b');
plot((0:frameRate:frameRate*size(mouseYvel_StopFail_HomeStair,2)-1),nanmean(mouseYvel_StopFail_HomeStair),'-r');
plot((0:frameRate:frameRate*size(mouseYvel_StopFail_TargetStair,2)-1),nanmean(mouseYvel_StopFail_TargetStair),'--r');
legend('Go','Stop','MoveOn','MoveEnd','SSH','SST','FSH','FST','location','NorthWest','FontSize',14);xlabel('Time from movement onset (ms)','FontSize',14);
ylabel('Y velocity (px.s)','FontSize',14);
xlim([-100, MT_GoCorr_mn + 100]);
ylim([0, nanmax(nanmean(mouseYvel_GoCorr))+250]);
text(meanStopCue_MoveOn +10, 500, 'Stop','FontSize',14,'Rotation', -90);
text(MT_GoCorr_mn +10, 500, 'Target Hit','FontSize',14,'Rotation', -90);
print(gcf,strcat('Test1_VelocityAbsY_PvO_JumpStop.pdf'),'-dpdf','-r400');

%% ---------------------------------------


% Prob makes sense if moving at an angle to look at the resultant velocity
% That might better show up the change because it's not clear in the Y or
% X alone



%%-----------------------------------------

% 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','SSH','SST','FSH','FST'})
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','SSH','SST','FSH','FST'})
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','SSH','SST','FSH','FST'})
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','SSH','SST','FSH','FST'})
ylabel('Time (ms)','FontSize',14);
ylim([0,round(nanmean(xVellocCorrFar * frameRate)+ 300)])

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


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

% Incomplete---------------------------------
% Incomplete---------------------------------
% Incomplete---------------------------------


mouseT_SSDnorm = mouseXYT(:,:,3);

% All SSDs
mouseT_SSDnorm = mouseT_SSDnorm - dataTable.StopSignalDelay;

mouseXvel_SSDnorm_HomeCorr = mouseXvel_StopCorr_HomeStair;
mouseXvel_SSDnorm_HomeFail = mouseXvel_StopFail_HomeStair;
mouseXvel_SSDnorm_TargetCorr = mouseXvel_StopCorr_TargetStair;
mouseXvel_SSDnorm_TargetFail = mouseXvel_StopFail_TargetStair;

mouseT_SSDnorm_HomeCorr = mouseT_SSDnorm(trl_StopCorr_HomeStr,:)
mouseT_SSDnorm_HomeFail = mouseT_SSDnorm(trl_StopFail_HomeStr,:)
mouseT_SSDnorm_TargetCorr = mouseT_SSDnorm(trl_StopCorr_TargetStr,:)
mouseT_SSDnorm_TargetFail = mouseT_SSDnorm(trl_StopFail_TargetStr,:)

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

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

for i = 1:size(mouseT_SSDnorm_HomeCorr,1)

    dat = mouseT_SSDnorm_HomeCorr(i,locMin(i):locMax(i))
    mouseT_SSDnorm_HomeCorr(i,1:length(dat)) = dat
    mouseT_SSDnorm_HomeCorr(i,length(dat):end) = NaN
    
    dat = mouseXvel_SSDnorm_HomeCorr(i,locMin(i):locMax(i))
    mouseXvel_SSDnorm_HomeCorr(i,1:length(dat)) = dat
    mouseXvel_SSDnorm_HomeCorr(i,length(dat):end) = NaN
    
end

mouseT_SSDnorm_HomeCorr_mn = nanmean(mouseT_SSDnorm_HomeCorr);
mouseXvel_SSDnorm_HomeCorr_mn = nanmean(mouseXvel_SSDnorm_HomeCorr);


for i = 1:size(mouseT_SSDnorm_HomeFail,1)

    dat = mouseT_SSDnorm_HomeFail(i,locMin(i):locMax(i))
    mouseT_SSDnorm_HomeFail(i,1:length(dat)) = dat
    mouseT_SSDnorm_HomeFail(i,length(dat):end) = NaN
    
    dat = mouseXvel_SSDnorm_HomeFail(i,locMin(i):locMax(i))
    mouseXvel_SSDnorm_HomeFail(i,1:length(dat)) = dat
    mouseXvel_SSDnorm_HomeFail(i,length(dat):end) = NaN
    
end

mouseT_SSDnorm_HomeFail_mn = nanmean(mouseT_SSDnorm_HomeFail);
mouseXvel_SSDnorm_HomeFail_mn = nanmean(mouseXvel_SSDnorm_HomeFail);

for i = 1:size(mouseT_SSDnorm_TargetCorr,1)

    dat = mouseT_SSDnorm_TargetCorr(i,locMin(i):locMax(i))
    mouseT_SSDnorm_TargetCorr(i,1:length(dat)) = dat
    mouseT_SSDnorm_TargetCorr(i,length(dat):end) = NaN
    
    dat = mouseXvel_SSDnorm_TargetCorr(i,locMin(i):locMax(i))
    mouseXvel_SSDnorm_TargetCorr(i,1:length(dat)) = dat
    mouseXvel_SSDnorm_TargetCorr(i,length(dat):end) = NaN
    
end

mouseT_SSDnorm_TargetCorr_mn = nanmean(mouseT_SSDnorm_TargetCorr);
mouseXvel_SSDnorm_TargetCorr_mn = nanmean(mouseXvel_SSDnorm_TargetCorr);


for i = 1:size(mouseT_SSDnorm_TargetFail,1)

    dat = mouseT_SSDnorm_TargetFail(i,locMin(i):locMax(i))
    mouseT_SSDnorm_TargetFail(i,1:length(dat)) = dat
    mouseT_SSDnorm_TargetFail(i,length(dat):end) = NaN
    
    dat = mouseXvel_SSDnorm_TargetFail(i,locMin(i):locMax(i))
    mouseXvel_SSDnorm_TargetFail(i,1:length(dat)) = dat
    mouseXvel_SSDnorm_TargetFail(i,length(dat):end) = NaN
    
end

mouseT_SSDnorm_TargetFail_mn = nanmean(mouseT_SSDnorm_TargetFail);
mouseXvel_SSDnorm_TargetFail_mn = nanmean(mouseXvel_SSDnorm_TargetFail);

figure()
plot(mouseT_SSDnorm_HomeCorr_mn(1:length(mouseXvel_SSDnorm_HomeCorr_mn)),mouseXvel_SSDnorm_HomeCorr_mn,'b')
hold on
plot(mouseT_SSDnorm_HomeFail_mn(1:length(mouseXvel_SSDnorm_HomeFail_mn)),mouseXvel_SSDnorm_HomeFail_mn,'--b')
plot(mouseT_SSDnorm_TargetCorr_mn(1:length(mouseXvel_SSDnorm_TargetCorr_mn)),mouseXvel_SSDnorm_TargetCorr_mn,'r')
plot(mouseT_SSDnorm_TargetFail_mn(1:length(mouseXvel_SSDnorm_TargetFail_mn)),mouseXvel_SSDnorm_TargetFail_mn,'--r')
xlim([0, 450])

a = mouseXvel_SSDnorm_HomeCorr_mn - mouseXvel_SSDnorm_HomeFail_mn;
b = mouseXvel_SSDnorm_HomeCorr_mn - mouseXvel_SSDnorm_TargetCorr_mn;
c = mouseXvel_SSDnorm_HomeCorr_mn - mouseXvel_SSDnorm_TargetFail_mn;

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