function sample04(duration)
% list 4: 2-D Gabor in a temporal Gaussian window (b)
% Usage: sample04(duration_in_sec)
%
%       25/3/2015 Hiroshi Ashida


if nargin<1
    duration=4;
end
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);
    frameInterval=Screen('GetFlipInterval',w);
    %frameRate=Screen('NominalFrameRate',w);
    frameRate=round(1/frameInterval);
    
    %% stimulus preparation
    isize=256;
    [X,Y]=meshgrid(-isize/2+1:isize/2,-isize/2+1:isize/2);
    X=X/isize; Y=Y/isize; % -0.5...0.5
    sf=6;   % c/img
    tf=4.0; % Hz
    ct=0.8;
    grey=127;
    ssigma=1/6; GaussW=exp(-(X.^2+Y.^2)/(2*ssigma^2));
    tsigma=duration/8;
    th=pi/4;
    nFrames=floor(frameRate*duration);

    %% drawing
    for f=1:nFrames
        t=frameInterval*(f-1);
        tg=exp(-(t-duration/2)^2/(2*tsigma^2));
        % drawing a Gabor patch
        G=(ct*cos(2.0*pi*sf*(X*sin(th)+Y*cos(th))+2.0*pi*tf*t).*GaussW*tg+1.0)/2 *255;
        tp(f)=Screen('MakeTexture',w,G); 
    end

    %% showing
    Priority(MaxPriority(w));
    Screen('FillRect',w,grey);
    [VBLTimestamp1 StimulusOnsetTime1 FlipTimestamp1 Missed1 Beampos1]=Screen('Flip',w);
    for f=1:nFrames
        Screen('DrawTexture',w,tp(f));
        [VBLTimestamp2 StimulusOnsetTime2 FlipTimestamp2 Missed2 Beampos2]=Screen('Flip',w);
    end
    Priority(0);
    Screen('CloseAll');
catch exception
    Priority(0);
    Screen('CloseAll');
    throw(exception);
end

%% results
fprintf(1,'1 frame = %10.4f s\n', frameInterval);
fprintf(1,'Duration = %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,'frames  %5d\n', nFrames);