
function fname = soundrippleexp_improved(subjID)
% SOUND RIPPLE REACTION TIME EXPERIMENT (IMPROVED)
%
% Usage:
%   fname = soundrippleexp_improved(subjID)
%
% Teaching-oriented reaction-time experiment:
% detect onset of spectrotemporal modulation ("ripples") in noise.
%
% IMPORTANT:
% - RTs are measured relative to ripple onset
% - Absolute RTs are not hardware-timed

if nargin < 1
    subjID = 1;
end

rng('shuffle');

%% Parameters
fs          = 44100;
nTrials     = 30;
leadInRange = [0.7 1.3];
maxDuration = 5;
amp         = 0.05;

modRate     = 4;     % Hz
modDepth    = 0.8;   % 0..1

%% Storage
RT_sound  = NaN(nTrials,1);
RT_ripple = NaN(nTrials,1);
keyPressed = strings(nTrials,1);
early = false(nTrials,1);
aborted = false(nTrials,1);

%% Instructions
fig = figure('Color','w','MenuBar','none','ToolBar','none', ...
    'Name','Ripple RT','NumberTitle','off');
axis off
text(0.5,0.6,'Ripple Reaction Time Experiment','HorizontalAlignment','center','FontSize',18,'FontWeight','bold');
text(0.5,0.45,'Detect when the sound STARTS TO MODULATE','HorizontalAlignment','center','FontSize',12);
text(0.5,0.35,'Press ANY KEY as fast as possible','HorizontalAlignment','center','FontSize',12);
text(0.5,0.15,'Press any key to start','HorizontalAlignment','center','FontSize',10,'FontAngle','italic');
waitforbuttonpress;
clf;

%% Main loop
for it = 1:nTrials

    leadIn = leadInRange(1) + diff(leadInRange)*rand;
    t = 0:1/fs:maxDuration;

    noise = randn(size(t));
    env = ones(size(t));
    idx = t >= leadIn;
    env(idx) = 1 + modDepth*sin(2*pi*modRate*(t(idx)-leadIn));

    x = amp * noise .* env;

    p = audioplayer(x,fs);

    clf; axis off
    text(0.5,0.5,sprintf('Trial %d / %d',it,nTrials),'HorizontalAlignment','center','FontSize',16);
    drawnow;

    RTkey = NaN;
    keyStr = "";
    responded = false;

    set(fig,'KeyPressFcn',@keycb);
    tStart = tic;
    play(p);

    while toc(tStart) < maxDuration && ~responded
        pause(0.001);
    end

    stop(p);
    set(fig,'KeyPressFcn',[]);

    RT_sound(it) = RTkey;
    RT_ripple(it) = RTkey - leadIn;
    keyPressed(it) = keyStr;

    if ~isnan(RTkey) && RTkey < leadIn
        early(it) = true;
    end

    if keyStr == "escape"
        aborted(it:end) = true;
        break
    end

    pause(0.3);
end

close(fig);

%% Save
ts = datestr(now,'yyyy-mm-dd_HH-MM-SS');
fname = sprintf('soundrippleRT_sub-%03d_%s.csv',subjID,ts);

T = table((1:nTrials)',RT_sound,RT_ripple,early,keyPressed,aborted, ...
    'VariableNames',{'trial','RT_sound','RT_ripple','early','key','aborted'});

writetable(T,fname);
fprintf('Saved data to %s\n',fname);

    function keycb(~,evt)
        if ~responded
            RTkey = toc(tStart);
            keyStr = string(evt.Key);
            responded = true;
        end
    end
end
