% Run a test of the sychnrony capabilities of screen flashes with LSL
% markers.

%Written by Matthew Grivich SCCN/UCSD

function PsychLSLScreenTimingTest()

%open lsl event outlet
lib = lsl_loadlib();


%open lsl engine outlet
info = lsl_streaminfo(lib,'EngineEvents-PsychoPhysics','Markers',1,60,'cf_string','uniquesourceid23444');
synchInfo = info.desc().append_child('synchronization');
synchInfo.append_child_value('offset_mean', '-.01613');
synchInfo.append_child_value('can_drop_samples', 'true');
disp('Opening Engine outlet...');
engineOutlet = lsl_outlet(info);

% Make sure this is running on OpenGL Psychtoolbox:
AssertOpenGL;


% Choose screen with maximum id - the secondary display on a dual-display
% setup for display:
screenid = max(Screen('Screens'));

% Open a fullscreen onscreen window on that display, choose a background
% color of 128 = gray, i.e. 50% max intensity:
win = Screen('OpenWindow', screenid, 0);


% Make sure the GLSL shading language is supported:
AssertGLSL;

black = BlackIndex(win);
white = WhiteIndex(win);

% Wait for release of all keys on keyboard, then sync us to retrace:
KbReleaseWait;

%for for keypress
while ~KbCheck
    Screen('Flip',win);
end
KbReleaseWait;

duration = 60; %frames
count = 0;
trueCount = 0;

while ~KbCheck && trueCount < inf
    
    if count == 0
    
      Screen(win,'fillrect',white,[0 0 1600 1200]);  
      Screen('Flip', win);
      %engineOutlet.push_sample({'flip'});
      engineOutlet.push_sample({'white'})
      %outlet.push_sample({'white'});
    elseif count == duration
      Screen(win,'fillrect',black,[0 0 1600 1200]);
      Screen('Flip', win);
      %engineOutlet.push_sample({'flip'});
      engineOutlet.push_sample({'black'});
      %outlet.push_sample({'black'});
    elseif count == duration*2
      count = -1;
      trueCount = trueCount -1;
    else
      Screen('Flip', win);
      engineOutlet.push_sample({'flip'});
    end
    count = count + 1;
    trueCount = trueCount + 1;
 
end

% We're done. Close the window. This will also release all other resources:
Screen('CloseAll');
java.lang.System.gc();

return;
