function files = tdcs_export_all(outRoot)
%TDCS_EXPORT_ALL Export every data variation to CSV in an organized folder tree.
%   FILES = TDCS_EXPORT_ALL() writes, under analysis/matlab/export/:
%     curated_all.csv          the 12-animal curated long data (day >= 0)
%     scenarios/<merge>_<win>.csv   each GLMM scenario table (all groups in that
%                              merge/window): 3 merges x 3 windows = 9 files
%     anchors/<merge>_B2vsA2.csv    the Box-B2(tDCS=1) vs Box-A2(tDCS=0) subset
%                              (full range) with the tDCS factor: 3 files
%     phases/<merge>_phase_<lo>-<hi>.csv   the anchor subset within each learning
%                              phase (dayp = day - phaseStart): 3 x 3 = 9 files
%   A MANIFEST.txt listing all files is also written. FILES is a cellstr of the
%   absolute paths written.
%
%   TDCS_EXPORT_ALL(OUTROOT) writes under OUTROOT instead of the default.

if nargin < 1 || isempty(outRoot)
    outRoot = fullfile(fileparts(mfilename('fullpath')), 'export');
end
cfg = tdcs_config();
merges  = {'unmerged', 'mergeA2', 'mergeB2'};
windows = {'full', 'd0_10', 'd0_13'};
phases  = {[0 5], [6 10], [6 13]};

scDir = fullfile(outRoot, 'scenarios');
anDir = fullfile(outRoot, 'anchors');
phDir = fullfile(outRoot, 'phases');
cellfun(@localMkdir, {outRoot, scDir, anDir, phDir});

files = {};

% 1. curated long data
f = fullfile(outRoot, 'curated_all.csv');
writetable(tdcs_load_data(), f); files{end+1} = f; %#ok<AGROW>

% 2. scenario tables (merge x window)
for mi = 1:numel(merges)
    for wi = 1:numel(windows)
        sc = [merges{mi} '_' windows{wi}];
        S = tdcs_scenario_data(sc);
        f = fullfile(scDir, [sc '.csv']);
        writetable(S, f); files{end+1} = f; %#ok<AGROW>
    end
end

% 3. anchor (Box-B2 vs Box-A2) subsets + tDCS factor, full range
% 4. phase subsets of the same
for mi = 1:numel(merges)
    S = tdcs_scenario_data([merges{mi} '_full']);
    A = S(ismember(S.group, {cfg.anchorLow, cfg.anchorHigh}), :);
    A.tDCS = double(A.group == cfg.anchorHigh);   % Box-B2 = 1, Box-A2 = 0
    f = fullfile(anDir, [merges{mi} '_B2vsA2.csv']);
    writetable(A, f); files{end+1} = f; %#ok<AGROW>
    for pi = 1:numel(phases)
        p = phases{pi};
        P = A(A.day >= p(1) & A.day <= p(2), :);
        P.dayp = P.day - p(1);
        f = fullfile(phDir, sprintf('%s_phase_%d-%d.csv', merges{mi}, p(1), p(2)));
        writetable(P, f); files{end+1} = f; %#ok<AGROW>
    end
end

% manifest
mfid = fopen(fullfile(outRoot, 'MANIFEST.txt'), 'w');
if mfid >= 0
    cleanup = onCleanup(@() fclose(mfid)); %#ok<NASGU>
    fprintf(mfid, 'tDCS data export -- %d files\n', numel(files));
    for i = 1:numel(files)
        fprintf(mfid, '  %s\n', strrep(files{i}, [outRoot filesep], ''));
    end
end
files = files(:);
fprintf('tdcs_export_all: wrote %d CSVs under %s\n', numel(files), outRoot);

end

function localMkdir(d)
if ~exist(d, 'dir'); mkdir(d); end
end
