close all;
clear;
clc;

% Check whether my custom functions are available
hasCbrewer  = ~isempty(which('cbrewer'));
hasNicegraph = ~isempty(which('nicegraph'));
hasSavegraph = ~isempty(which('savegraph'));


d		= dir('MARK*.SAC');
fnames	= {d.name};
nfiles	= numel(fnames);

figure(1);
clf
hold on
e = NaN(nfiles*2,1);
d = e;
rt = e;

if hasCbrewer
    % Use custom cbrewer colormap if available
col = cbrewer('qual','Paired',9);
else
    % Fallback to built-in colormap
    col = turbo(18);
end
for ii = 1:nfiles
	fname	= fnames{ii};
	SAC		= loadsac(fname);
	onoff	= mod(SAC,1500);

	fname	= fcheckext(fname,'HUM');
	[h,v]	= pa_loadraw(fname,2,1500);

	R = hypot(h',v')';
	[nsamples,ntrials] = size(R);
	fname	= fcheckext(fname,'LOG');
	S		= readlog(fname);
	Fs		= S.meta.Sig_Fsample;
	L		= S.table;
	A = L.R2;
	P = L.Phi2;
	sel = A==5 & P==300;
	if sum(sel)
		d(ii)		= (onoff(2,sel)-onoff(1,sel))/Fs*1000;
		rt(ii)		= onoff(1,sel)/Fs*1000-500;
		x		= R(:,sel);
		x		= x-x(250);
		x		= lowpass(x,80,500);
		e(ii)	= x(842/2);
		x		= x/e(ii)*5;

		x = x(250:end);
		x = x(1:250);
		t = (1:numel(x))';
		t = t/Fs*1000; % ms

		sel = t<rt(ii);
		x(sel) = smooth(x(sel),20);
		sel = t>(rt(ii)+d(ii));
		x(sel) = smooth(x(sel),20);

		plot(t,x,'LineWidth',1.5,'Color',col(ii,:));
		if ii ==5
			xline(rt(ii))
			xline(rt(ii)+d(ii))
			text(rt(ii),0,num2str(rt(ii)),'HorizontalAlignment','center','VerticalAlignment','top','FontSize',24);
			text(rt(ii)+d(ii)/2,2.5,num2str(d(ii)),'HorizontalAlignment','center','VerticalAlignment','middle','FontSize',24);
		end
	end


		sel = A==5 & P==120;
	if sum(sel)
		d(ii+nfiles)		= (onoff(2,sel)-onoff(1,sel))/Fs*1000;
		rt(ii+nfiles)		= onoff(1,sel)/Fs*1000-500;
		x		= R(:,sel);
		x		= x-x(300);
		x		= lowpass(x,80,500);
		e(ii+nfiles)	= x(842/2);
		x		= x/e(ii+nfiles)*5;

		x = x(250:end);
		x = x(1:250);
		t = (1:numel(x))';
		t = t/Fs*1000; % ms

		sel = t<rt(ii+nfiles);
		x(sel) = smooth(x(sel),20);
		sel = t>(rt(ii+nfiles)+d(ii+nfiles));
		x(sel) = smooth(x(sel),20);

		plot(t,x,'LineWidth',1.5,'Color',col(ii,:));

		if ii ==7
	xline(rt(ii+nfiles))
	xline(rt(ii+nfiles)+d(ii+nfiles))
			text(rt(ii+nfiles),0,num2str(rt(ii+nfiles)),'HorizontalAlignment','center','VerticalAlignment','top','FontSize',24);
			text(rt(ii+nfiles)+d(ii+nfiles)/2,2.5,num2str(d(ii+nfiles)),'HorizontalAlignment','center','VerticalAlignment','middle','FontSize',24);

end
	end


			
	xlabel('time re stimulus onset (ms)');
	ylabel('amplitude (°)');
	nicegraph;
	xlim([-50 350]);
	plot([-50 0],[0 0],'k-')
	plot([0 0],[0 5],'k-')
	plot([0 800],[5 5],'k-')
	set(gca,'XTick',0:100:500,'YTick',[0 5])
	text(50,5,'5° target','HorizontalAlignment','left','VerticalAlignment','bottom','FontSize',24)
	title('human saccades to visual target');

end
% nanmean(e)

[mn,idx] = min(rt)
[mx,idx] = max(rt)


%% Save figure
fname = fullfile('..','..','..','images','saccade_reactiontimes_ori.svg');
if hasSavegraph
    % Use custom helper
    savegraph(fname,'svg');
else
    % Built-in export (R2020a+; otherwise use print/saveas)
    exportgraphics(gcf, fname, 'Resolution', 300);
end

function SAC = loadsac(fname)

fid         = fopen(fname,'r','l');
[SAC,N]     = fread(fid,inf,'ulong');

fclose(fid);
SAC         = reshape(SAC,2,N/2);
end