function sample05(duration)
% List 5: random dot optic flow
% Usage: sample05(duration_in_sec)
% 25/3/2015 Hiroshi Ashida

if nargin<1
    duration=10;
end
fieldSize=640; maxR=fieldSize/2;
dotSize=6; nDot=300; lifeTime=10; v=3.0;
%% preparing dots
for i=1:nDot
    [X(i) Y(i) R(i) TH(i)]=randR(maxR);
end
X=X'; Y=Y'; R=R'; TH=TH';
Life=ceil(rand(nDot,1)*lifeTime);
try
    %% opening screen
    wWidth=1024; wHeight=640;
    AssertOpenGL;
    screens=Screen('Screens');
    sNumber=max(screens);
    [sWidth,sHeight]=Screen('WindowSize',sNumber);
    w=Screen('OpenWindow',sNumber,0,[0 0 wWidth wHeight]); % window presentation
%    w=Screen('OpenWindow',sNumber,0);
    [sWidth,sHeight]=Screen('WindowSize',sNumber);
    %frameRate=Screen('FrameRate',w);
    frameInterval=Screen('GetFlipInterval',w);
    frameRate=round(1/frameInterval);
    xc=sWidth/2; yc=sHeight/2;

    %% drawing & showing
    nFrames=frameRate*duration;
    phi=rand*2*pi; dphi=2*pi/nFrames;
    Screen('FillRect',w,0);
    [VBLTimestamp1 StimulusOnsetTime1 FlipTimestamp1 Missed1 Beampos1]=Screen('Flip',w);
    for f=1:nFrames   
        % drawing dots
        XY=[X Y]';
        Screen('DrawDots',w,XY,dotSize,[],[xc,yc]);
        % for next frame
        TH=TH+v*sin(phi)./R;
        R=R+v*cos(phi);
        X=R.*cos(TH); Y=R.*sin(TH);
        Life=Life-1;
        for i=1:nDot
            if Life(i)==0
                Life(i)=lifeTime;
                [X(i) Y(i) R(i) TH(i)]=randR(maxR);
            end
        end
        [VBLTimestamp2 StimulusOnsetTime2 FlipTimestamp2 Missed2 Beampos2]=Screen('Flip',w);
        phi=phi+dphi;
    end
    Screen('CloseAll');
catch exception
    Priority(0);
    Screen('CloseAll');
    throw(exception);
end

%% results
fprintf(1,'1 frame = %10.4f s\n', frameInterval);
fprintf(1,'ExpectedDuration = %10.3f s\n', duration);
fprintf(1,'        VBLTimestamp StimulusOnsetTime FlipTimestamp\n');
fprintf(1,'start   %12.3f %17.3f %13.3f\n', VBLTimestamp1, StimulusOnsetTime1, FlipTimestamp1);
fprintf(1,'end     %12.3f %17.3f %13.3f\n', VBLTimestamp2, StimulusOnsetTime2, FlipTimestamp2);
fprintf(1,'duraion %12.3f %17.3f %13.3f\n', VBLTimestamp2-VBLTimestamp1, StimulusOnsetTime2-StimulusOnsetTime1, FlipTimestamp2-FlipTimestamp1);
fprintf(1,'fps %12.3f %17.3f %13.3f\n', nFrames/(VBLTimestamp2-VBLTimestamp1), nFrames/(StimulusOnsetTime2-StimulusOnsetTime1), nFrames/(FlipTimestamp2-FlipTimestamp1));
fprintf(1,'frames  %5d\n', nFrames);


function [x y r th]=randR(maxR)
x=(rand-0.5)*maxR*2;
y=(rand-0.5)*maxR*2;
r=sqrt(x^2+y^2);
while r>maxR
    x=(rand-0.5)*maxR*2;
    y=(rand-0.5)*maxR*2;
    r=sqrt(x^2+y^2);
end
th=atan2(y,x);
    