clear all;
%GetSecstest;
framerate = round (screen(0,'framerate'));
disp( sprintf('Running at %d Hz.', framerate));

% if framerate ~= 75
% 	disp('Wrong refresh rate. Exiting.');
% 	return
% end

disableinput = 0;



%  ================================ Parameters ===============================


textcolor = [0 0 0];
bgcolor = [180 180 180];



%  ============================ READ IN SUBJECT INFO ============================
prompts = {'Subject Number', 'Last Name', 'First Name', 'Age', 'Sex (M/F)', 'Handedness (R/L)', 'BCS-subject full email'};
default_s_info = {'0', '', '', '', '', '', ''};
s_info = inputdlg(prompts, 'Subject Info', 1, default_s_info);

% Quit if cancel is pressed
if size(s_info) == 0
	return
end

[s_num, s_lname, s_fname, s_age, s_sex, s_hand, s_email] = deal(s_info{:});
s_num = sscanf(s_num, '%d');
s_age = sscanf(s_age, '%d');

if (s_num > 0)
	subjfile = fopen('subjects.txt', 'a');
	fprintf(subjfile, '%i  %s %s  %i  %s  %s  %s  ', ...
	s_num, s_fname, s_lname, s_age, s_sex, s_hand, s_email);
	fclose(subjfile);
end;

%=================================DISPLAY INSTRUCTIONS=========================

win = screen(0, 'OpenWindow');
screen(win, 'FillRect', bgcolor);
[windowptr, rect] = screen('GetFrontWindow');
center = [rect(3) rect(4)]/2;

whichScreen = 0;
[window,Scrnsize] = Screen(whichScreen,'OpenWindow',[180,180,180]);

centerx = Scrnsize(3)/2;
centery = Scrnsize(4)/2;

SCREEN(window,'TextSize',30);
SCREEN(window,'TextFont','Arial');
wblank = Screen(window,'OpenOffscreenWindow',[180,180,180]);        
SCREEN(wblank,'FrameRect',31);



hidecursor

s = sprintf('In this experiment you will see four streams of symbols');
SCREEN(window,'DrawText',s ,150,200,[0,0,0]);

s = sprintf('going by very fast, together with one or two digits.');
SCREEN(window,'DrawText',s ,150,240,[0,0,0]);

s = sprintf('Your task is to spot the digit or digits, and report');
SCREEN(window,'DrawText',s ,150,280,[0,0,0]);

s = sprintf('them  after each trial. There will be either one or two');
SCREEN(window,'DrawText',s ,150,320,[0,0,0]);

s = sprintf('digits presented randomly in the same or different');
SCREEN(window,'DrawText',s ,150,360,[0,0,0]);

s = sprintf('streams. Report digits even if you are not sure, but  ');
SCREEN(window,'DrawText',s ,150,400,[0,0,0]);

s = sprintf('do not guess randomly. This experiment is quite  ');
SCREEN(window,'DrawText',s ,150,440,[0,0,0]);

s = sprintf('difficult so do not worry about your performance. ');
SCREEN(window,'DrawText',s ,150,480,[0,0,0]);

s = sprintf('First we will start with practice trials. ');
SCREEN(window,'DrawText',s ,150,520,[0,0,0]);

s = sprintf('Press the spacebar to continue. ');
SCREEN(window,'DrawText',s ,150,560,[0,0,0]);

a = GetChar;
Screen('CopyWindow',wblank,window);

% =============== DETERMINE BETWEEN-SUBJECTS VARIABLES FOR THIS SUBJECT =================



% ========================== SET UP THE NECESSARY SCREENS ============================
win = screen(0, 'OpenWindow');
screen(win, 'FillRect', bgcolor);
[windowptr, rect] = screen('GetFrontWindow');
center = [rect(3) rect(4)]/2;

%xsize = 120;
%ysize = 120;
%xoffset = 130;
%yoffset = 

textbox = [ 0,0,60,60 ];
textboxcross = [ 0,0,60,60 ];

textbox_center = [0,0];


%  [ Left  Top   Right  Bottom] 

%topleft = [center-[150 105], center-[50 35] ];

%botleft = [center-[150 -95], center-[50 -165]];

%brad added code
%botleft = [center-[150 -80], center-[50 -150]];

%topright = [center-[-50 105], center-[-150 35]];

%botright = [center-[-50 -95], center-[-150 -165]];

%brad added code
%botright = [center-[-50 -80], center-[-150 -150]];

%
%	Quadrants:	1	2
%				3	4
%

waitwin = screen(win, 'OpenOffscreenWindow', bgcolor);
screen(waitwin, 'TextSize', 12);
screen(waitwin, 'TextFont', 'Geneva');
screen(waitwin, 'DrawText', 'Loading...', ...
center(1)-22, center(2)+3, textcolor);

fixwin = screen(win, 'OpenOffscreenWindow', bgcolor, textboxcross);
screen(fixwin, 'TextSize', 30);
screen(fixwin, 'TextFont', 'Courier');
screen(fixwin, 'TextStyle', 1);
screen(fixwin, 'DrawText', '+', textbox_center(1)+21.5, textbox_center(2)+38.5, textcolor); 



readywin = screen(win, 'OpenOffscreenWindow', bgcolor);
screen(readywin, 'TextSize', 12);
screen(readywin, 'TextFont', 'Geneva');
screen(readywin, 'TextStyle', 1);
screen(readywin, 'DrawText', 'Press space bar', ...
center(1)-70, center(2)+20, textcolor);

%brad added code
%changed these values from the following
%center(1)-50, center(2)+3, textcolor);

lengtho = 9 + 2 + 6;
textsize = 70;

for(quad = 1:18)
	for i = 1:lengtho
		
		
		%set up screens for each trial
		quadscreens(i,quad) =  screen(win, 'OpenOffscreenWindow', bgcolor, textbox);
		screen(quadscreens(i,quad), 'TextSize', textsize);
		screen(quadscreens(i,quad), 'TextFont', 'Arial');
	end
end

Distractors(1:20) =  ['A','B','C','D','E','F','G','H','J','K','L','N','P','Q','R','T','U','V','X','Y'];


Targs(1:8) = ['2','3','4','5','6','7','8','9'];	

for hm = 1:3
	
	if hm < 3
		practice = 1;
		conds = getConditions (s_num, practice);  %sets conditions and number of trials
		
	else
		practice = 0;
		conds =  getConditions (s_num, practice); 
		
	end
	numtrials = conds.numtrials;
	
	
	
	%Run and generate stimuli for each trial
	for q = 1: numtrials
		trial = q;
		j = conds.index(q); %changed j to be random instead of serial
		
		if(disableinput==0)
			
			if q == 1  &  practice == 1 & hm ==2
				msg = msgbox('Press Ok to begin the second block of practice trials, slightly faster.', 'modal');
				uiwait(msg);
				screen(win,'FillRect',bgcolor);
			end
		
		
			if q == 1  &  practice == 0
				msg = msgbox('End of practice trials.  The real trials will begin now.', 'modal');
				uiwait(msg);
				screen(win,'FillRect',bgcolor);
			end
			%	HideCursor;
			
			if q == 161 & practice == 0	
				msg = msgbox ('Feel free to take a short break and click OK to continue');
				uiwait(msg);
				screen (win, 'FillRect', bgcolor);
			end
		end
	
		%	HideCursor;		
		% Number the practice trials starting at 101
		if practice == 1
			t = 100 + trial;
			rp = 0;  % Indicate that it's a practice trial
		else
			t = trial;
			rp = 1;
		end
	
		lengtho = conds.t1ser + conds.soa + 6;
		
		blankframe = screen(win, 'OpenOffscreenWindow', bgcolor, textbox);
		screen(blankframe, 'TextSize', 20);
		screen(blankframe, 'TextFont', 'Courier');
		screen(blankframe, 'TextStyle', 1);	
		% =========================== GENERATE THE STIMULI ==================================
		
		
		
		%Generate random digits with replacement
		
		
		for(quad = 1:18)
			
			for y = 1:18
				
				dists(j,quad,y) = Distractors(ceil(rand*20));
				
				%	backwards repeat check if y > 1;
				
				if(y >1) 
					for f = 1:y-1
					while dists(j,quad,y) == dists(j,quad,f)
						dists(j,quad,y) = Distractors(ceil(rand*20));
					end
					end
				end
			
% 				
% 				if(y == 2)
% 					
% 					while(dists(j,quad,y) == dists(j,quad,y-1))
% 						dists(j,quad,y) = Distractors(ceil(rand*8));
% 					end
% 				elseif(y >2)  %check 2 back if we are at position 3 or more
% 					while(sum(dists(j,quad,y) == dists(j,quad,y-2:y-1)) > 0)
% 						dists(j,quad,y) = Distractors(ceil(rand*8));
% 					end
% 				end
			
			end
		end
	
		%		datafile = fopen('digitstimuli.txt','a');
		%			fprintf(datafile, '%s\t%d\n', rp, dists(j,quad,y));
		%		fclose(datafile)
		
		%Get random targets
		
		T2(j) = ceil(rand*8);
		T1(j) = T2(j);
		while(T1(j)==T2(j))
			T1(j)= ceil(rand*8);
		end
		T1(j) = Targs(T1(j));	
		T2(j) = Targs(T2(j));	
		
		% ===========================================TRIALS============================================
		wordlength = 1;
		textbox_x = textbox_center(1)+31;
		textbox_y = textbox_center(2) + 55.5;
		y=1;
		% Show the ready prompt (Press spacebar)
		FlushEvents('keyDown');
		
		if(disableinput==0)
			screen('CopyWindow',readywin, win);
			KbWait;
		end
	
		screen('CopyWindow',wblank, win);
		boxcolor = [100 0 0];
		% Show the fixation cross
		screen('CopyWindow',fixwin,win,[],[center-[30 30], center+[30 30]]);
		
		screen(0,'WaitBlanking', round(.200*framerate) );
		
	
		
% 		for w = 1:18
% 			dists(j,w,:) = 'A';
% 		end
		
		for i = 1:lengtho
			for(quad = 1:18)
				textsize  = 70;
				
				screen(quadscreens(i,quad),'FillRect', bgcolor, [0 0 300 300]);	
				%	screen('CopyWindow',wblank,quadscreens(i,quad),[-100,-100,100,100],[]);
				screen(quadscreens(i,quad), 'TextSize', textsize);
				screen(quadscreens(i,quad), 'TextStyle', 0);		
				screen(quadscreens(i,quad), 'TextFont', 'Arial');
				
				%screen(quadscreens(i,quad), 'TextStyle', 1);			
				
				if(i ==conds.t1ser(j) & conds.t1quad(j)==quad)
			     	TextWidth = SCREEN(quadscreens(i,quad), 'TextWidth', sprintf('%c',T1(j)));			
					
					screen(quadscreens(i,quad), 'DrawText', sprintf('%c',T1(j)),textbox_x-(TextWidth/2), textbox_y,textcolor);
				elseif((i ==conds.t1ser(j)+conds.soa(j)|i ==conds.t1ser(j)+conds.soa(j)+1) & conds.t2quad(j)==quad)
					TextWidth = SCREEN(quadscreens(i,quad), 'TextWidth', sprintf('%c',T2(j)));
					
					screen(quadscreens(i,quad), 'DrawText', sprintf('%c',T2(j)),textbox_x-(TextWidth/2), textbox_y,textcolor);
				else
					TextWidth = SCREEN(quadscreens(i,quad), 'TextWidth', sprintf('%c',dists(j,quad,i)));	
					
					screen(quadscreens(i,quad), 'DrawText', sprintf('%c',dists(j,quad,i)),textbox_x-(TextWidth/2), textbox_y,textcolor);
					
				end		
			
			end
		
		end	
	
		pos = circlepos(110,0,20);
		quad = 18;
		for i = 1:lengtho
			for w = 1:quad
				
				
				screen('CopyWindow', quadscreens(i,w) , win , [], [pos.x(w)-15 pos.y(w)-15 pos.x(w)+15 pos.y(w)+15]);
				
				screen('CopyWindow',fixwin,win,[],[center-[30 30], center+[30 30]]);
				
			end
			Frametimes(i) = GetSecs;	
			
			if (hm==1)
				screen(0,'WaitBlanking', round(0.250*framerate) );	
			elseif (hm==2)
				screen(0,'WaitBlanking', round(0.100*framerate) );	
			else
				screen(0,'WaitBlanking', round(0.053*framerate) );	
			end			
		
		end
		screen(quadscreens(i,quad),'Close')
		
		FlushEvents('keyDown');
		
		lasttime = GetSecs;
		
		
		screen(win,'FillRect',bgcolor);
		% GET SUBJECT RESPONSE
		ShowCursor;
		
		
		if(disableinput==0)
			
			screen(win, 'TextSize', 30);
			screen(win, 'TextFont', 'Arial');
			
			starty=center(2)-150;
			
			
			s = sprintf('Enter any digits that you saw, in order');
			
			screen(win, 'TextSize', 40);
			screen(win, 'TextFont', 'Arial');
			
			
			SCREEN(win,'DrawText',s,center(1)-500, starty-30);
			
			In1 = 0;
			numinput = 0;
			
			%	if(disableinput)
			
			%		In1 = 13;  %COMMMMENT THIS!!!
			%	end	
			
			
			while (In1(max(1,numinput)) ~=13)
				if(In1(max(1,numinput)) == 8)  %backspace
					numinput = max(numinput -1,1);
				else
					numinput = numinput + 1;
				end
				In1(numinput)  = GetChar;
				
				
				if(In1(max(1,numinput)) == 8)  %backspace
					s = sprintf('%c',' ');
					SCREEN(window,'DrawText',s,10+(numinput-1)*20,starty+50,[10,10,10]);
					%					SCREEN(win,'DrawText',s,10+(numinput-1)*20,center(1)-350, center(2)+3);
					SCREEN(win,'FillRect',[180,180,180],[10+(numinput-1)*20,starty+20,10+(numinput)*20,starty+70]);
					
				else
			
					s = sprintf('%c',In1(numinput));
					SCREEN(win,'DrawText',s,10+numinput*20, starty+70);
					
					
				end	
			end
		
		
			responsestring = In1;  %if we're collecting responses
			
			if responsestring == 13
				responsestring = ['00',13];
			elseif responsestring(length(responsestring)-1) == 13
				responsestring = responsestring(1:(length(responsestring)-1));
			end
		
		else
			responsestring = 'NN';
		end
	
		responsestring = responsestring(1:(length(responsestring)-1));
		
		if(length(responsestring) < 2)  %pads the response if it's shorter than 2
       		responsestring(2) = 1;
		end
	
		if (T1(j) == responsestring(1) | T1(j) == responsestring(2))
			t1corr = 1;
		else
			t1corr = 0;
		end
	
		if (T2(j) == responsestring(1) | T2(j) == responsestring(2))
			t2corr = 1;
		else
			t2corr = 0;
		end
	
		if conds.t1quad(j) == conds.t2quad(j)
			t1t2   = 1;
		elseif conds.t1quad(j) == 5
			t1corr = 0;
			t1t2 = 2;
		else
			t1t2 = 0;
		end
	
	
		% WRITE DATA TO FILE
		datafile = fopen('data.txt','a');
		trial = j;
		
		fprintf(datafile, '%d\t%d\t%d\t%d\t%d\t%d\t%d\t%s\t%d\t%d\t%d\t%d\t%d\n', ...
		s_num, t, rp, conds.soa(trial), conds.t1ser(trial), conds.t1quad(trial), ...
		conds.t2quad(trial), responsestring,T1(j),T2(j), ...
		t1corr, t2corr, t1t2);
		fclose(datafile);	
		
		
		datafile = fopen(sprintf('%dtiming.txt',s_num),'a');
		trial = j;
		fprintf(datafile, '%d,,,',trial);	
		for( i = 2:lengtho)
			fprintf(datafile, '%g,',Frametimes(i)-Frametimes(i-1));
		end
		fprintf(datafile, '\n');
		fclose(datafile);
		
		
	end


end



fclose('all');

msg = msgbox('The experiment has finished successfully.  Please get the experimenter now.', 'modal');
screen('CloseAll');
uiwait(msg);
