function make_matched_effort()
%MAKE_MATCHED_EFFORT Compare the previous (_f) study to the current study at
%   EQUAL cumulative effort (total attempts), not equal calendar days.
%
%   The current animals attempt far more reaches per session than the previous
%   (Forouzan) animals, so at equal day counts they have far more practice. This
%   picks the current-study day cutoff 0..D whose per-animal cumulative attempts
%   best matches the previous study's FULL (days 0-9) per-animal attempts, then
%   builds two variation subfolders under variations/ and fits the paper's LME
%   (behavior ~ stim + day + stim:day + (1|rat), on the success COUNT) in each:
%
%     variations/prev_f_full/            previous study, b2_f vs a2_f, days 0-9
%     variations/matched_current_d0_<D>/ current anchors Box-B2 vs Box-A2, 0..D
%
%   Each folder holds the usual three files (data.csv, analyze.m, result.txt).
%   A comparison of the two interaction estimates is printed at the end.

thisDir = fileparts(mfilename('fullpath'));
template = fullfile(thisDir, 'variation_analyze.m');
root = fullfile(thisDir, 'variations');
if ~exist(root, 'dir'); mkdir(root); end

Tf = forouzan_load_data();
Tc = tdcs_load_data();
B2 = 'Electrode-Box-B2'; A2 = 'Electrode-Box-A2';

% Target: previous study's per-animal cumulative attempts over its full span.
target = localPerAnimalMeanTotal(Tf, 0, 9);
fprintf('Previous (_f) full 0-9: %.0f attempts/animal\n', target);

% Choose the current-study cutoff whose cumulative attempts best matches it.
anc = Tc(ismember(cellstr(Tc.group), {A2, B2}), :);
bestD = NaN; bestDiff = inf; bestVal = NaN;
for d = 2:9
    v = localPerAnimalMeanTotal(anc, 0, d);
    fprintf('  current anchors 0-%d: %.0f attempts/animal\n', d, v);
    if abs(v - target) < bestDiff
        bestDiff = abs(v - target); bestD = d; bestVal = v;
    end
end
fprintf('=> matched-effort window: current days 0-%d (%.0f vs %.0f attempts/animal)\n\n', ...
    bestD, bestVal, target);

% Build the two comparison folders and fit the paper LME in each.
prevName = 'prev_f_full';
currName = sprintf('matched_current_d0_%d', bestD);
rPrev = localBuildAndRun(root, prevName, ...
    localStimTable(Tf, 'b2_f'), template);
rCurr = localBuildAndRun(root, currName, ...
    localStimTable(anc(anc.day >= 0 & anc.day <= bestD, :), B2), template);

fprintf('\n=== PAPER LME interaction (stim x day) at matched effort ===\n');
fprintf('%-26s %5s %5s  %-22s %-14s\n', 'dataset', 'nRat', 'nObs', 'interaction', 'stim(Day1)');
localCmpRow(prevName, rPrev);
localCmpRow(currName, rCurr);
fprintf(['\n(Both now represent ~%.0f attempts/animal of practice. The previous\n' ...
    'study spreads that over 10 sessions; the current study reaches it in %d days.)\n'], ...
    target, bestD);

end

% ---- per-animal mean cumulative attempts over a day window --------------
function m = localPerAnimalMeanTotal(T, lo, hi)
T = T(T.day >= lo & T.day <= hi, :);
subj = unique(T.subject);
tot = zeros(numel(subj), 1);
for i = 1:numel(subj)
    tot(i) = sum(T.total(T.subject == subj(i)));
end
m = mean(tot);
end

% ---- add a stim column (1 for treatGroup, 0 otherwise) -----------------
function D = localStimTable(T, treatGroup)
stim = double(strcmp(cellstr(T.group), treatGroup));
D = table(string(T.subject), string(T.group), T.day, T.success, T.total, stim, ...
    'VariableNames', {'subject', 'group', 'day', 'success', 'total', 'stim'});
end

% ---- write data.csv + analyze.m, run it (isolated), return VARRESULT ----
function r = localBuildAndRun(root, name, D, template)
folder = fullfile(root, name);
if ~exist(folder, 'dir'); mkdir(folder); end
writetable(D, fullfile(folder, 'data.csv'));
copyfile(template, fullfile(folder, 'analyze.m'));
r = localRun(fullfile(folder, 'analyze.m'));
end

function r = localRun(scriptPath)
run(scriptPath);
r = VARRESULT; %#ok<NODEF>
end

function localCmpRow(name, r)
sig = 'n.s.';
if r.interP < 0.05; sig = 'SIG'; end
fprintf('%-26s %5d %5d  %+6.2f/day p=%.3f %-4s  p=%.3f\n', ...
    name, r.nRats, r.nObs, r.interEst, r.interP, sig, r.stimP);
end
