function visualsearchexp(n,search,subjectid)
% VISUALSEARCHEXP(N,SEARCH,SUBJECTID)
%
% Run a visual search experiment with two conditions:
%
% - POP-OUT: Subjects are asked to report the presence or absence of a
% TARGET STIMULUS (in this case, a colored lowercase letter “o”) among
% various numbers of DISTRACTER stimuli (+). If the distracter stimuli are
% just of a different color—that is, if they differ by a single FEATURE—you
% usually find the “pop-out” effect: the reaction time to detect the target
% is independent of the number of distracters.
%
% - CONJUNCTION: Conversely, if more than one stimulus dimension has to be
% considered to distinguish targets and distracters (conjunction search),
% you typically find a linear relationship between reaction time and the
% number of distracters.
%
% See also ﻿Wallisch P. MATLAB for neuroscientists : an introduction to
% scientific computing in MATLAB [Online].
% http://www.sciencedirect.com/science/book/9780123838360#ancp1 [26 Apr.
% 2017].   Project 3.4.

%% Initialization
% To prevent errors with existing variables and figures, remove all
% existing variables and figures.
close all;
clearvars;

%% Randomization
% setsize = [4 8 12 16];
% search = [0 1];
% [setsize,search] = meshgrid(setsize,search);
% setsize = setsize(:);
% search = search(:);
% n = numel(setsize);
% idx = randperm(n);
% setsize = setsize(idx)
% search = search(idx)
% [setsize search]
%%
if nargin<1
	n			= 8; % set size (only 4, 8, 12, or 16
	search		= 0; % conjunctive search = true, pop-up = false
	subjectid	= 1;
end

%% Figure
% Start by creating a figure.
figure(1);
clf; % Make sure to make the text vanish before the beginning of the next trial.
cla;

% Be sure to make the figure big enough to see it clearly.
% Fancy/difficult - expand figure to cover screen
fig			= gcf;
set(fig,'units','normalized','outerposition',[0 0 1 1])
fig.PaperPositionMode = 'auto';

plot(1,1,'wo')
hold on
xlim([-0.05 1.05]);
ylim([-0.05 1.05]);
% nicegraph; % make graph nice
axis('square');
grid off;
% axis off;

% Remove Ticks and set Box 
set(gca,...
	'Box','on', ...
	'XMinorTick','off', ...
	'YMinorTick','off', ...
	'XTick',[],...
	'YTick',[]);
drawnow;
axis off;
text(0.5,0.5,'Ready - Set - Go','FontSize',30,'HorizontalAlignment','center');
pause(2);

%%
% Show two conditions (pop-out search versus conjunction search) with four
% levels each (set size = 4, 8, 12, 16). These (8) conditions can be blocked
% (first all pop-out searches, then all conjunction searches or something
% like that).

% Be aware that you effectively have an experimental design with three factors [Set size:
% 4 levels (4, 8, 12, 16), conjunction versus feature search: 2 levels, target present versus
% absent: 2 levels). It might make sense to block the first two factors and randomize the
% last one.


% The analysis should contain at least 20 correct trials per level and condition for a total of
% 160 trials. They should go quickly (about 1 second each).
ntrials		= 60;
ncorrtrials	= 0;
% Write a big loop that goes through trials. Do this at the very end, if individual trials work.
RT			= NaN(ntrials*2,1); % reaction time (s)
Tpresent	= NaN(ntrials*2,1); % Target present
N			= NaN(ntrials*2,1); % set size
Csearch		= NaN(ntrials*2,1); % Conjunctive trial or not
KP			= cell(ntrials*2,1); % key press: 0 = in, 1 is out
% for ii = 1:ntrials
cnt		= 0; % count
while ncorrtrials<ntrials
	target = logical(randi(2,1)-1);  %  target presence
	% run trial
	cnt		= cnt+1;
	showtrial(n,target,search);
	drawnow;
	t				= tic;
	k		= waitforbuttonpress;
% pause; % Waiting for single key press
	% get response and stimulus parameters
	RT(cnt)			= toc(t); % get reaction time

	kp				= str2double(get(gcf,'CurrentCharacter')); % key press: 0 = in, 1 is out
	KP{cnt}			= kp; 
	Tpresent(cnt)	= double(target);
	N(cnt)			= n;
	Csearch(cnt)	= double(search);
	
	% Check for accuracy
	correct		= kp==double(target); % PEOPLE SHOULD PRESS ONLY 0 OR 1

	intime		= RT(cnt)<2; % people should respond within 1 s
	if intime && correct
		ncorrtrials = ncorrtrials+1;
	end
	[cnt ncorrtrials ntrials]
	if cnt>(ntrials*2) % stop while loop if there are too many trials, i.e. if people are unable to make correct and timely responses
		break
	end
end

close all;
%% Remove NaNs/empty 
sel			= isnan(RT);
RT			= RT(~sel);
KP			= KP(~sel);
Tpresent	= Tpresent(~sel);
Csearch		= Csearch(~sel);
N			= N(~sel);

%% Save data

searchstr	= {'popup','conjunctive'};
d			= char(datetime('now','Format','dd-MM-yy'));
t			= char(datetime('now','Format','HH-mm-ss'));

fname		= ['visualsearch-subject-' num2str(subjectid,'%03d') '-date-' d '-time-' t '-setsize-' num2str(n) '-search-' searchstr{search+1} '.csv'];
fname = fullfile('..','..','data',fname);

targetpresent = Tpresent;
nstim = N;
conjunctive = Csearch;
keypress = KP;
reactiontime = RT;
T = table(targetpresent,nstim,conjunctive,keypress,reactiontime);
writetable(T,fname);

% save(fname,'RT','KP','N','Tpresent','Csearch');

%% saved in working trajectory
%%
% close all;plotpost(RT,'xlim',[0 2]);
%%

% keyboard
%% Additional functions

function showtrial(n,target,search)
% Start writing one trial and make sure it works properly.

%% Random position
% Be sure to place the targets and distracters randomly.
x		= rand(n,1); % uniform, values between [0 1], inclusive
y		= rand(n,1);


%% Figure
% Start by creating a figure.
figure(1);
cla; % Make sure to make the text vanish before the beginning of the next trial.

hold on
xlim([-0.05 1.05]);
ylim([-0.05 1.05]);
% nicegraph; % make graph nice
axis('square');
grid off;
% axis off;

% Remove Ticks and set Box 
set(gca,...
	'Box','on', ...
	'XMinorTick','off', ...
	'YMinorTick','off', ...
	'XTick',[],...
	'YTick',[]);

%% 
% It is imperative to randomly interleave trials with and without target.
% There should be an equal number of trials with and without targets.  
% Each trial will essentially consist of newly presented, randomly placed
% text. 


%% Plot distractors
% targetSym		= 'O'; % target symbol
% distracterSym	= 'X'; % distracter symbol

xDistX	= x(1:(n/2));
yDistX	= y(1:(n/2));

xDistO	= x((n/2+1):n);
yDistO	= y((n/2+1):n);

text(xDistX,yDistX,'X','Color','b');
text(xDistO,yDistO,'O','Color','b');

%% Target = present, pop-up
if target
	xTar = xDistO(1);
	yTar = yDistO(1);
	text(xTar,yTar,'O','Color','r');
end
if search
	text(xDistX(1:(n/4)),yDistX(1:(n/4)),'X','Color','r');
end


%% Set Text Size of all symbols (and axis and figure text)
t = findall(gcf,'Type','Text'); % find all text objects
set(t,'FontSize',25); % then set fontsize of those objects to 25

