function [tRTBox,tPTB]=RTBoxdemo_reportflashtimes(scrn)

% This is a demo which uses PTB to flash the whole screen white at random times,
% and use RTBox to measure the times at which the flashes occur.
% Attach the photodiode to the center of the monitor.
% I have found it essential to remove ambient light from the photodiode, by
% the simple expedient of draping the monitor in a towel!

% Jenny Read, 7/2010

if nargin<1, scrn=max(Screen('screens')); end % find last screen
ntrials=1000 ;  % # of trials
timeout=1;    % timeout for RT reading

tRTBox=nan(ntrials,1);
tPTB = tRTBox;

t0 = GetSecs;
try    % avoid dead screen in case of error
    [w r]=Screen('OpenWindow',scrn,0);  % open a dark screen
    ifi=Screen('GetFlipInterval',w);% flip interval
    ratio = RTBox('ClockRatio');
    RTBox('enable','light'); % enable light detection for trigger, also open device if needed
    % Stop RTBox responsding to button-presses; I only want to know about light
    RTBox('disable', { 'release' 'press' });

    ClockRandSeed;   % set random seed

    Priority(MaxPriority(w));   % raise priority for better timing
    i=0;
    while i<ntrials
        WaitSecs(abs(0.2+0.1*randn)); % wait a random time, mean ~200ms
        RTBox('clear'); % clear buffer before stim onset
        Screen('FillRect',w,255,r); % flash up rectangle
        t1=Screen('Flip',w);
        Screen('FillRect',w,0,r); %
        Screen('Flip',w); % remove rectangle
        
        t=RTBox('secs',timeout);  %read time of flash
        if ~isempty(t)
            i=i+1;
            tPTB(i) = t1-t0;
            tRTBox(i) = t-t0;
            fprintf('%dth flash occurred %5.3f seconds after start time according to RTBox and %5.3f seconds according to PTB.\n',i,tRTBox(i), tPTB(i))
            
        end
    end
catch
    lasterr
    Screen('CloseAll'); Priority(0);
    rethrow(lasterror);
end
Screen('CloseAll');
Priority(0);                % restore normal priority

% Plot distribution of flashtimes
figure
[y,x]=hist(diff(tRTBox),ntrials/10);
subplot(1,2,1)
bar(x,y)
title('Distribution of inter-flash intervals')
subplot(1,2,2)
mn = min([tRTBox tPTB]);mx = max([tRTBox tPTB]);
plot([mn mx],[mn mx],'k')
hold on
plot(tRTBox,tPTB,'r.')
title(sprintf('Mean difference is %5.3f ms',abs(mean(tRTBox-tPTB))*1e3))
xlabel('Times reported by RTBox')
ylabel('Times reported by PTB')

