% 23 Oct_2003 - evan
% reward jpeg for version1 from isaac
% get a few random people to do test runs 
% isaac probably has more novel images for us

% 9 Oct 2003
% Addressed question at end of yesterday's effort, see below.
% Add column descriptions at top of text file output, checked it
% out in Excel and tab delimiters make it look good.

% 8 Oct 2003
% Added many comments
% Added click sound for when wheel stops and shifted cashreg and asterisk sounds
% to present simultaneously with their screens.
% Encapsulated novel JPG and WAV initialization code for version 3 in an
% if-statement, added a diagnostic that finds the longest WAV file, and
% made the novel list be multiple shuffled batches of what is available.
% NEED TO ASK IF ALL SHOULD BE USED ONCE BEFORE ANY REPEATS? (Two options
% available below.)
% Q PRESS QUIT NOT MOUSE SENSITIVE? (Turns out that left-mouse button is
% part of KbCheck matrix, so q-press code unchanged and other
% keyboard/mouse code simplified to just keyboard.)

% 24 Sep 2003 notes
% Added q = q/max([abs(max(max(q))) abs(min(min(q)))]) to keep all sounds
% in same volume range and especially to make soft ones louder.

% 17 Sep 2003 notes
% Add max pause before automatic spin
% Version 3, will have index of maybe 100 images and sounds to use.

% 10 Sep 2003 notes.
% 1. Ensure that at least six spins between asterisks,
% but natural randomness aftre sixth.
% 2. Adjust to key and mouse click.
% 3. Initial screen for investigator control (backtick key).
% 4. Versions 2 always ends on 10 except asterisk every eighth trial.
% Number reward screen will simply count "Trial = 1", "Trial = 2", "Trial = 3"...
% until asterisk and then reset, no $$$ indicator.
% 5. Version 3.

% Wheel graphics Numbers themselves white, number backgrounds light blue
% and red, 0 black, * green

% myIMROTATEMMDD.m
% by Daniel Shima, Vanderbilt Vision Research Center.

clear all;
close all;

warning off MATLAB:DeprecatedLogicalAPI;
GetSecs;

% *********** USER DEFINED VARIABLES ***********

versionnumber = 2;

multb = 2; % Starting value of multiplier for number hits.
multbincrement = 3; % When asterisk hit, multb will increase by this value.
totalplaytime = 60; % Number of seconds subject plays roulette, starts as soon as wheel appears for first time.
minspintime = 5; % Lower limit of randomized wheel spin time.
maxspintime = 10; % Upper limit of randmoized wheel spin time.
wheelstopperiod = 1; % Number of seconds wheel visible after it stops and before reward screen appears.
rewardscreenperiod = 2; % Number of seconds reward screen visible.
interasteriskspins = 3; % Forced minimum hits on number between asterisk hits.
startresult = ' 7'; % Single digit results like 7 need to have a space like ' 7'.

% How many batches of all your novel sounds and pictures do you want to shuffle into a big list?
% Should consider the total number you have of each and how long your subject is playing.
novellistmultiple = 10;

% **********************************************

spinsnoasterisk = 0;
totalmoney = 0;
j = 0; % Variable j is index for output array.

% Set up output text file with date & time stamp name.
stamp0 = datestr(now,6); % 'mm/dd' (e.g., 03/01)
stamp1 = datestr(now,13); % ' 'HH:MM:SS' (e.g., 15:13:40)
stamp3 = datestr(now,10); % 'yyyy' (e.g., 2003)
stamp2 = [stamp3 stamp0(1:2) stamp0(4:5) stamp1(1:2) stamp1(4:5) stamp1(7:8)]; % 0301151340
outputfid = fopen([stamp2 'output.txt'],'wt');
fprintf(outputfid,'hittype\tsubjpressdelay\trewardscrtime\thitvalue\tmultb\ttotalmoney\trequestspintime\tactualspintime\n\n');

% Open the main monitor screen and hide the cursor.
pixelSize = 32;
backgroundcolor = [63 63 63];  % Background RGB color, [0 0 0] is black and [255 255 255] is white.
[w, screenRect] = SCREEN(0,'OpenWindow',backgroundcolor,[],pixelSize); % Define your output screen as your monitor which is screen 0, give it an RGB backgroundcolor.
HideCursor;

framerate = SCREEN(w,'FrameRate'); % Grab frame rate of current monitor.

% Load precalculated parameters and arrays to save time.
load Data_mywheel_0910; % Variables mywheelarray, valueA, and characters.
load Data_invalidpoints_0818; % Variables invalidpoints, height, and width.
load Data_rotatedimage001deg_0915; % Variables rotatedimage and frames.

% This is the point that is at the bottom center of the wheel where the top
% of the yellow arrow will be.
bottomwheelPoint = [screenRect(3)/2 screenRect(4)/2 screenRect(3)/2 screenRect(4)/2] + [0 height/2 0 height/2];

% Create scr for each angle of wheel.
for i = 1:1:frames
    scr(i) = SCREEN(w,'OpenOffscreenWindow',backgroundcolor,[0 0 width height]);
    SCREEN(scr(i),'PutImage',rotatedimage(:,:,:,i),[0 0 width height]);
end

% Knowing how the wheel looks, the order or the numbers and asterisks, the fact that each
% one uses 18 degrees of the circle, and that the initial position of the
% arrow is in the center of the first number, assign the appropriate result to each angle
% of the wheel.
for (i =         1:           9) result(i,:) = characters( 1,:); end;
for (i = 9+1+ 0*18:9+1+ 0*18+17) result(i,:) = characters(20,:); end;
for (i = 9+1+ 1*18:9+1+ 1*18+17) result(i,:) = characters(19,:); end;
for (i = 9+1+ 2*18:9+1+ 2*18+17) result(i,:) = characters(18,:); end;
for (i = 9+1+ 3*18:9+1+ 3*18+17) result(i,:) = characters(17,:); end;
for (i = 9+1+ 4*18:9+1+ 4*18+17) result(i,:) = characters(16,:); end;
for (i = 9+1+ 5*18:9+1+ 5*18+17) result(i,:) = characters(15,:); end;
for (i = 9+1+ 6*18:9+1+ 6*18+17) result(i,:) = characters(14,:); end;
for (i = 9+1+ 7*18:9+1+ 7*18+17) result(i,:) = characters(13,:); end;
for (i = 9+1+ 8*18:9+1+ 8*18+17) result(i,:) = characters(12,:); end;
for (i = 9+1+ 9*18:9+1+ 9*18+17) result(i,:) = characters(11,:); end;
for (i = 9+1+10*18:9+1+10*18+17) result(i,:) = characters(10,:); end;
for (i = 9+1+11*18:9+1+11*18+17) result(i,:) = characters( 9,:); end;
for (i = 9+1+12*18:9+1+12*18+17) result(i,:) = characters( 8,:); end;
for (i = 9+1+13*18:9+1+13*18+17) result(i,:) = characters( 7,:); end;
for (i = 9+1+14*18:9+1+14*18+17) result(i,:) = characters( 6,:); end;
for (i = 9+1+15*18:9+1+15*18+17) result(i,:) = characters( 5,:); end;
for (i = 9+1+16*18:9+1+16*18+17) result(i,:) = characters( 4,:); end;
for (i = 9+1+17*18:9+1+17*18+17) result(i,:) = characters( 3,:); end;
for (i = 9+1+18*18:9+1+18*18+17) result(i,:) = characters( 2,:); end;
for (i = 9+1+19*18:9+1+19*18+ 8) result(i,:) = characters( 1,:); end;

% Screen numberscr will be used after the wheel stops on a number.
numberscr = SCREEN(w,'OpenOffscreenWindow');
SCREEN(numberscr,'TextSize',24);
cashwidth = SCREEN(numberscr,'TextWidth','$$$ CASH $$$');

% Screen asteriskscr will be used after the wheel stops on an asterisk.
asteriskscr = SCREEN(w,'OpenOffscreenWindow');
SCREEN(asteriskscr,'TextSize',24);

% Screen wheelscr will be used to show the wheel itself and the spin bar.
wheelscr = SCREEN(w,'OpenOffscreenWindow',backgroundcolor);
spinwidth = SCREEN(wheelscr,'TextWidth','SPIN');

% Screen startscr is used in the very beginning while the program waits for
% a backtick from the keyboard or generated by the scanner pulse.
startscr = SCREEN(w,'OpenOffscreenWindow',backgroundcolor);
SCREEN(startscr,'TextSize',24);
backtickstartwidth = SCREEN(startscr,'TextWidth','Hit the backtick to start.');
SCREEN(startscr,'DrawText','Hit the backtick to start.',screenRect(3)/2-backtickstartwidth/2,screenRect(4)/2,[0 0 0]);

% Shift initial position of wheel until it is on variable startresult
% defined above.
i = 1;
while (1)
    if (result(i,:) == startresult)
        starti = i;
        initialstarti = i;
        break;
    else
        i = i + 18;
    end
end

% Initialize certain flags and values.
endflag = 0;
textendx1 = 0;
textendy1 = 0;
textendx2 = 0;
textendy2 = 0;
textendx3 = 0;
textendy3 = 0;

% Read sounds and scale them between 1 and -1.
[yspinhit,fsspinhit,nbits,opts] = WAVREAD('SPINHIT');
yspinhit = yspinhit/max([abs(max(max(yspinhit))) abs(min(min(yspinhit)))]);
[yasterisk,fsasterisk,nbits,opts] = WAVREAD('ASTERISK');
yasterisk = yasterisk/max([abs(max(max(yasterisk))) abs(min(min(yasterisk)))]);
[ycashreg,fscashreg,nbits,opts] = WAVREAD('CASHREG');
ycashreg = ycashreg/max([abs(max(max(ycashreg))) abs(min(min(ycashreg)))]);
[yding,fding,nbits,opts] = WAVREAD('DING');
yding = yding/max([abs(max(max(yding))) abs(min(min(yding)))]);

yclick = repmat([-1 -0.5 0 0.5 1 0.5 0 -0.5],1,10); fsclick = 11025;

if (versionnumber == 3)
    % There should be a local directory called novel which contains all the
    % pictures and sounds that you want to use for Version 3.  The following
    % two lines will capture a list of each.
    noveljpglist = dir('novel\*.jpg');
    novelwavlist = dir('novel\*.wav');
    
    % Find the longest novel sound file in the group.
    longestnovelwav = 0;
    for i = 1:size(novelwavlist,1)
        wavsize(i) = novelwavlist(i).bytes;
        [ycurrentnovelwav,fscurrentnovelwav,nbits,opts] = WAVREAD(['novel\' novelwavlist(i).name]);
        currentnovelwav = length(ycurrentnovelwav)/fscurrentnovelwav;
        if (currentnovelwav > longestnovelwav)
            longestnovelwav = currentnovelwav;
            longestindex = i;
        end
    end
%     % This code is a diagnostic for displaying the longest WAV-file in the
%     % novel directory and gives its calculated and measured length.  The idea
%     % is that maybe we want to make Version 3 numberscr always last the length
%     % of the longest WAV-file on queue.
%     calculatedlongesttime = 
%     filelongesttime = novelwavlist(longestindex)
%     [ycurrentnovelwav,fscurrentnovelwav,nbits,opts] = WAVREAD(['novel\' novelwavlist(longestindex).name]);
%     startlongest = GetSecs;
%     WAVPLAY(ycurrentnovelwav,fscurrentnovelwav,'sync');
%     stoplongest = GetSecs;
%     measuredlongesttime = stoplongest - startlongest
    
    % Create the two shuffled lists for novel sounds and pictures.
    
    % Use this code if you want to shuffle the list of novel pictures and
    % sounds one at a time so that no picture or sound is repeated until
    % every one is shown once.
    noveljpgorder = [];
    novelwavorder = [];
    for i = 1:novellistmultiple
        noveljpgorder = [noveljpgorder shuffle([1:size(noveljpglist,1)])];
        novelwavorder = [novelwavorder shuffle([1:size(novelwavlist,1)])];
    end
      
%     % Use this code if you want the order of the novel pictures and sounds
%     % to be a shuffling of all batches at once.
%     noveljpgorder = shuffle(repmat([1:size(noveljpglist,1)],1,novellistmultiple));
%     novelwavorder = shuffle(repmat([1:size(novelwavlist,1)],1,novellistmultiple));
    
    currentnovelitem = 1; % Index to walk through shuffled JPG and WAV files.
    
    % Load current novel JPG and WAV for next use and, after used, load the next one.
    currentnoveljpg = IMREAD(['novel\' noveljpglist(noveljpgorder(currentnovelitem)).name]);
    [ycurrentnovelwav,fscurrentnovelwav,nbits,opts] = WAVREAD(['novel\' novelwavlist(novelwavorder(currentnovelitem)).name]);
    ycurrentnovelwav = ycurrentnovelwav/max([abs(max(max(ycurrentnovelwav))) abs(min(min(ycurrentnovelwav)))]);
    currentnovelitem = currentnovelitem + 1;
end

% Wait for investigator to hit backtick key.
SCREEN('CopyWindow',startscr,w);
[keyIsDown,secs,keyCode] = KbCheck;
while (1)
    [keyIsDown,secs,keyCode] = KbCheck;
    if (keyIsDown)
        if (KbName(find(keyCode)) == '`')
            SCREEN(w,'FillRect',backgroundcolor);
            break;
        end
    end
end
while (KbCheck) end;

% Create initial wheel, yellow arrow indicator, and button graphic at bottom.
SCREEN(w,'FillPoly',[255 255 0],[screenRect(3)/2,screenRect(4)/2+height/2; screenRect(3)/2-10/2,screenRect(4)/2+height/2+10; screenRect(3)/2+10/2,screenRect(4)/2+height/2+10]);
SCREEN(w,'FillRect',[0 0 0],[-150 -20+50 150 20+50] + bottomwheelPoint);
SCREEN(w,'FillRect',[255 255 255],[-150+5 -20+50+5 150-5 20+50-5] + bottomwheelPoint);
SCREEN(w,'DrawText','SPIN',bottomwheelPoint(1)-spinwidth/2,bottomwheelPoint(2)+55,[0 0 0]);
SCREEN('CopyWindow',scr(starti),w,[0 0 width height],CenterRect([0 0 height width],screenRect));
wheeltime = GetSecs;
startplay = wheeltime;

% While still under total playing time and while the 'q' key has not been
% pressed.
while (~endflag & GetSecs - startplay < totalplaytime)
% while (~endflag)
    
    % Wait for keyboard or mouse press. (Left-mouse button is part of KbCheck.)
    while (~KbCheck) end;
    j = j + 1; % Spin counter j.
    % Code for animating SPIN bar as it is pressed.
    SCREEN(w,'FillRect',[255 255 255],[-150 -20+50 150 20+50] + bottomwheelPoint);
    SCREEN(w,'FillRect',[0 0 0],[-150+5 -20+50+5 150-5 20+50-5] + bottomwheelPoint);
    SCREEN(w,'DrawText','SPIN',bottomwheelPoint(1)-spinwidth/2,bottomwheelPoint(2)+55,[255 255 255]);
    % Wait for keyboard or mouse release.  (Left-mouse button is part of KbCheck.)
    while (KbCheck) end;
    subjectpresstime = GetSecs; % Record time subject RELEASED the button to start spinning.
    % Code for animating SPIN bar as it is released.
    SCREEN(w,'FillRect',[0 0 0],[-150 -20+50 150 20+50] + bottomwheelPoint);
    SCREEN(w,'FillRect',[255 255 255],[-150+5 -20+50+5 150-5 20+50-5] + bottomwheelPoint);
    SCREEN(w,'DrawText','SPIN',bottomwheelPoint(1)-spinwidth/2,bottomwheelPoint(2)+55,[0 0 0]);
    
    % This code is a diagnostic for covering up result info in the
    % upper-left of wheelscr.
    SCREEN(w,'FillRect',backgroundcolor,[0 0 max([textendx1 textendx2 textendx3]) max([textendy1 textendx2 textendx3])+10]); % Plus 10 for text comma removal.
    
    WAVPLAY(yspinhit,fsspinhit,'async'); % Play spinhit WAV-file upon button release.
    
    % For Versions 1 and 3, assign the current random spin time between min
    % and max limits, transform it into number of frames, check to see if
    % it will land on an asterisk, and adjust if necessary.
    if (versionnumber == 1 | versionnumber == 3)
        spintime = RandSample([minspintime:maxspintime]); % Randomly spin between minspintime and maxspintime seconds.
        requestedspintime = spintime;
        spinframes = spintime*framerate;
        if (result(mod(starti-1+spinframes,frames)+1,:) == ' *' & spinsnoasterisk < interasteriskspins)
            spinframes = spinframes + RandSample([-4 -3 -2 -1 1 2 3 4])*18;
%             % This code is a diagnostic from when spinnoasterisk first
%             % implemented.
%             fprintf('Asterisk result avoided because spinsnoasterisk was %d.\n',spinsnoasterisk);
        end
    % For Version 2, spin time is first selected randomly but then adjusted
    % so that wheel returns to desired number (or asterisk) each time.
    % Requested spin time and actual spin time are recorded in output text
    % file.
    elseif (versionnumber == 2)
        spintime = RandSample([minspintime:maxspintime]); % Randomly spin between minspintime and maxspintime seconds.
        requestedspintime = spintime;
        % This next line converts spintime into closest multiple of 360
        % frames for a complete rotation and return to original number.
        spinframes = round(spintime*framerate/frames)*frames;
        % This while-statemenet will break when spinframes take wheel to
        % the chossen number hit for Version 2 and that is valid, or when
        % spinframes takes wheel to an asterisk and that is valid.
        % Otherwise, it keeps added 18 degrees to rotation and rechecking.
        while (1)
            if (mod(starti-1+spinframes,frames)+1 == initialstarti & spinsnoasterisk < interasteriskspins)
                break;
            elseif (result(mod(starti-1+spinframes,frames)+1,:) == ' *' & spinsnoasterisk == interasteriskspins)
                break;
            else
                spinframes = spinframes + 18;
%                 % This code is a diagnostic from when asterisk part of
%                 % Version 2 first implemented.
%                 fprintf('Shifted to "%s".\n',result(mod(starti-1+spinframes,frames)+1,:));
            end
        end
    end

    % This is the code that makes the wheel spin.  It is spun a certain
    % number of frames, but also have a clock timer around it in case those
    % values ever want to be verified or used.
    startspin = GetSecs;
    for i = starti:starti-1+spinframes;
        SCREEN(w,'WaitBlanking',1);
        SCREEN('CopyWindow',scr(mod(i,frames)+1),w,[0 0 width height],CenterRect([0 0 height width],screenRect));
    end
    finishspin = GetSecs;
    actualspintime = finishspin - startspin;
    
    WAVPLAY(yclick,fsclick,'async');

    % Adjust starti to an equivalent frame between 1 and 360, kind of just
    % a housekeeping calculation.
    starti = mod(i,frames)+1;
    
    % This code is a diagnostic put in the upper-left of wheelscr
    % confirming where the wheel stopped and what values were used in
    % calculations.
    [textendx1 textendy1] = SCREEN(w,'DrawText',['FRAME ' num2str(mod(i,frames)+1) ', RESULT "' result(mod(i,frames)+1,:) '"'],15,15,[255 255 0]);

    if (result(mod(i,frames)+1,:) == ' *') % If asterisk hit.
        startwait = GetSecs; % Reference time for when wheel stopped spinning.
        multb = multb + multbincrement; % Incremenet multiplier when asterisk hit.
        spinsnoasterisk = 0; % Reset spins-no-asterisk parameter.

        SCREEN(asteriskscr,'FillRect',[63 0 0]); % Blank darker red screen.
        % Version 1 asterisk give current total money info.
        if (versionnumber == 1)
            totalwidth = SCREEN(asteriskscr,'TextWidth',['You have won a total of $' num2str(totalmoney,'%0.2f')]);
            SCREEN(asteriskscr,'DrawText',['You have won a total of $' num2str(totalmoney,'%0.2f')],screenRect(3)/2-totalwidth/2,screenRect(4)/2,[255 0 0]);
        end
        % Version 1 and 2 asterisk both give info in increase of multiplier
        % value.
        if (versionnumber == 1 | versionnumber == 2)
            multwidth = SCREEN(asteriskscr,'TextWidth',['The multiplier will be increased to ' num2str(multb)]);
            SCREEN(asteriskscr,'DrawText',['The multiplier will be increased to ' num2str(multb)],screenRect(3)/2-multwidth/2,screenRect(4)/2+24*2,[255 0 0]);
        end
        % Version 3 asterisk only says "Get ready for more spins".
        if (versionnumber == 3)
            getreadywidth = SCREEN(asteriskscr,'TextWidth',['Get ready for more spins!']);
            SCREEN(asteriskscr,'DrawText',['Get ready for more spins!'],screenRect(3)/2-getreadywidth/2,screenRect(4)/2,[255 0 0]);
        end
        
        while (GetSecs - startwait < wheelstopperiod) end % Let stopped wheel pause for period.
        WAVPLAY(yasterisk,fsasterisk,'async'); % Play the asterisk sound.
        SCREEN('CopyWindow',asteriskscr,w,screenRect,screenRect); % Show the asterisk screen constructed above.
        rewardscreentime = GetSecs; % Record time that reward screen was presented.
        % Save trial info to output text file.
        output(j,1:8) = [1 subjectpresstime-wheeltime rewardscreentime-startplay 0 multb totalmoney requestedspintime actualspintime];
        
        % Prepare wheelscr for next wheel spin.
        SCREEN(wheelscr,'FillPoly',[255 255 0],[screenRect(3)/2,screenRect(4)/2+height/2; screenRect(3)/2-10/2,screenRect(4)/2+height/2+10; screenRect(3)/2+10/2,screenRect(4)/2+height/2+10]);
        SCREEN(wheelscr,'FillRect',[0 0 0],[-150 -20+50 150 20+50] + bottomwheelPoint);
        SCREEN(wheelscr,'FillRect',[255 255 255],[-150+5 -20+50+5 150-5 20+50-5] + bottomwheelPoint);
        SCREEN(wheelscr,'DrawText','SPIN',bottomwheelPoint(1)-spinwidth/2,bottomwheelPoint(2)+55,[0 0 0]);
        SCREEN('CopyWindow',scr(mod(i,frames)+1),wheelscr,[0 0 width height],CenterRect([0 0 height width],screenRect));
        
        % Wait for duration of wheelstopperiod, present the wheel screen,
        % and record the time that it is presented.
        while (GetSecs - startwait < wheelstopperiod + rewardscreenperiod) end
        SCREEN('CopyWindow',wheelscr,w);
        wheeltime = GetSecs;
    
    else % Else a number hit.
        startwait = GetSecs; % Reference time for when wheel stopped spinning.
        totalmoney = totalmoney + str2num(result(mod(i,frames)+1,:))*multb/100; % Update total money.
        spinsnoasterisk = spinsnoasterisk + 1; % Increment number of spins without an asterisk.

        % This code is a diagnostic to indicate money won on current spin
        % and total money at that point.
        [textendx2 textendy2] = SCREEN(w,'DrawText',['$' num2str(str2num(result(mod(i,frames)+1,:))/100,'%0.2f') ' x ' num2str(multb) ' = $' num2str(str2num(result(mod(i,frames)+1,:))*multb/100,'%0.2f')],15,30,[255 255 0]);
        [textendx3 textendy3] = SCREEN(w,'DrawText',['TOTAL MONEY $' num2str(totalmoney,'%0.2f')],15,60,[255 255 0]);

        SCREEN(numberscr,'FillRect',[0 63 0]); % Initialize a darker green screen.
        % Version 1 number hit shows word CASH and money equation won on that spin.
        if (versionnumber == 1)
            ynumberhit = ycashreg; fsnumberhit = fscashreg;
            winwidth = SCREEN(numberscr,'TextWidth',['$' num2str(str2num(result(mod(i,frames)+1,:))/100,'%0.2f') ' x ' num2str(multb) ' = $' num2str(str2num(result(mod(i,frames)+1,:))*multb/100,'%0.2f')]);
            SCREEN(numberscr,'DrawText','$$$ CASH $$$',screenRect(3)/2-cashwidth/2,screenRect(4)/2,[0 191 0]);
            SCREEN(numberscr,'DrawText',['$' num2str(str2num(result(mod(i,frames)+1,:))/100,'%0.2f') ' x ' num2str(multb) ' = $' num2str(str2num(result(mod(i,frames)+1,:))*multb/100,'%0.2f')],screenRect(3)/2-winwidth/2,screenRect(4)/2+24*2,[0 191 0]);
            numberscrperiod = rewardscreenperiod;
        end
        % Version 2 number hit merely says "Trial #".
        if (versionnumber == 2)
            ynumberhit = yding; fsnumberhit = fding;
            trialwidth = SCREEN(numberscr,'TextWidth',['Trial ' num2str(j)]);
            SCREEN(numberscr,'DrawText',['Trial ' num2str(j)],screenRect(3)/2-trialwidth/2,screenRect(4)/2+24*2,[0 191 0]);
            numberscrperiod = rewardscreenperiod;
        end
        % Version 3 number hit present the next novel sund and picture in
        % the shuffled list.
        if (versionnumber == 3)
            ynumberhit = ycurrentnovelwav; fsnumberhit = fscurrentnovelwav;
            SCREEN(numberscr,'PutImage',currentnoveljpg);
            numberscrperiod = length(ycurrentnovelwav)/fscurrentnovelwav;
        end

        while (GetSecs - startwait < wheelstopperiod) end % Wait remainder of wheel stop period.
        WAVPLAY(ynumberhit,fsnumberhit,'async'); % Play appropriate number hit sound for this version 1, 2, or 3.
        SCREEN('CopyWindow',numberscr,w,screenRect,screenRect); % Present number hit screen.
        rewardscreentime = GetSecs; % Record time number hit screen presented.
        % Save trial info to output text file.
        output(j,1:8) = [2 subjectpresstime-wheeltime rewardscreentime-startplay str2num(result(mod(i,frames)+1,:))/100 multb totalmoney requestedspintime actualspintime];
        
        % Prepare wheelscr for next wheel spin.
        SCREEN(wheelscr,'FillPoly',[255 255 0],[screenRect(3)/2,screenRect(4)/2+height/2; screenRect(3)/2-10/2,screenRect(4)/2+height/2+10; screenRect(3)/2+10/2,screenRect(4)/2+height/2+10]);
        SCREEN(wheelscr,'FillRect',[0 0 0],[-150 -20+50 150 20+50] + bottomwheelPoint);
        SCREEN(wheelscr,'FillRect',[255 255 255],[-150+5 -20+50+5 150-5 20+50-5] + bottomwheelPoint);
        SCREEN(wheelscr,'DrawText','SPIN',bottomwheelPoint(1)-spinwidth/2,bottomwheelPoint(2)+55,[0 0 0]);
        SCREEN('CopyWindow',scr(mod(i,frames)+1),wheelscr,[0 0 width height],CenterRect([0 0 height width],screenRect));

        % If Version 3, get next novel sound and picture ready and
        % increment novel list counter.
        if (versionnumber == 3)
            currentnoveljpg = IMREAD(['novel\' noveljpglist(noveljpgorder(currentnovelitem)).name]);
            [ycurrentnovelwav,fscurrentnovelwav,nbits,opts] = WAVREAD(['novel\' novelwavlist(novelwavorder(currentnovelitem)).name]);
            ycurrentnovelwav = ycurrentnovelwav/max([abs(max(max(ycurrentnovelwav))) abs(min(min(ycurrentnovelwav)))]);
            currentnovelitem = currentnovelitem + 1;
        end

        % Wait remainder of novel screen period and present wheel screen
        % and recod time.
        while (GetSecs - startwait < wheelstopperiod + numberscrperiod) end
        SCREEN('CopyWindow',wheelscr,w);
        wheeltime = GetSecs;
        
        % This code is a diagnostic to indicate money won on current spin
        % and total money at that point.
        [textendx1 textendy1] = SCREEN(w,'DrawText',['FRAME ' num2str(mod(i,frames)+1) ', RESULT "' result(mod(i,frames)+1,:) '"'],15,15,[255 255 0]);
        [textendx2 textendy2] = SCREEN(w,'DrawText',['$' num2str(str2num(result(mod(i,frames)+1,:))/100,'%0.2f') ' x ' num2str(multb) ' = $' num2str(str2num(result(mod(i,frames)+1,:))*multb/100,'%0.2f')],15,30,[255 255 0]);
        [textendx3 textendy3] = SCREEN(w,'DrawText',['TOTAL MONEY $' num2str(totalmoney,'%0.2f')],15,60,[255 255 0]);
    end
    
    % This code reacts also user to quit by pressing 'q'.
    while (1)
        [keyIsDown,secs,keyCode] = KbCheck;
        if (keyIsDown)
            if (find(keyCode) == KbName('q'))
                endflag = 1;
            end
            break;
        end
    end
    
end

for i = 1:size(output,1)
    for j = 1:size(output,2)
        if (j == size(output,2))
            fprintf(outputfid,'%0.3f\n',output(i,j));
        else
            fprintf(outputfid,'%0.3f\t',output(i,j));
        end;
    end
end

st = fclose(outputfid);

FlushEvents('keyDown');
ShowCursor;
% Close all screens.
SCREEN('CloseAll');

% % Chunk of old code previously commented out in area were spinframes for
% % Version 2 being calculated.
%         while (1)
%             if (result(mod(starti-1+spinframes,frames)+1,:) == startresult & spinsnoasterisk < interasteriskspins)
%                 break;
%             elseif (result(mod(starti-1+spinframes,frames)+1,:) == ' *' & spinsnoasterisk == interasteriskspins)
%                 break;
%             else
%                 spinframes = spinframes + 18;
%                 % fprintf('Shifted to "%s".\n',result(mod(starti-1+spinframes,frames)+1,:));
%             end
%         end

% % Chunck of old code that made random line pattern for Version 3 number screen.
% for k = 1:360
%    [novelx,novely] = POL2CART(k/360*2*pi,RandSample([1:screenRect(4)/2]));
%    SCREEN(numberscr,'DrawLine',[0 191 0],screenRect(3)/2,screenRect(4)/2,screenRect(3)/2+novelx,screenRect(4)/2+novely);
% end

% % Chunck of old code from before I knew that left-mouse button part of KbCheck.
%     % Wait for keyboard or mouse press.
%     [mousex,mousey,mousebutton] = GetMouse;
%     while (~KbCheck & ~mousebutton)
%         [mousex,mousey,mousebutton] = GetMouse;
%     end
%     % Wait for keyboard or mouse release.
%     [mousex,mousey,mousebutton] = GetMouse;
%     while (KbCheck | mousebutton)
%         [mousex,mousey,mousebutton] = GetMouse;
%     end
