% setup_toolbox.m
%
% Run this script ONCE from the toolbox root after cloning or moving the
% toolbox to a new location.  It embeds absolute paths to 'utilities' and
% 'toolbox_programs' into setpathdynare6_5.m so that file can be copied
% into any subfolder and still point back to the right directories.
%
% Usage:  run setup_toolbox   (from the toolbox root, or any directory)

% ── Locate this script (= toolbox root) ──────────────────────────────────
toolbox_root = fileparts(mfilename('fullpath'));

utilities_path        = fullfile(toolbox_root, 'utilities');
toolbox_programs_path = fullfile(toolbox_root, 'toolbox_programs');
setpath_file          = fullfile(toolbox_root, 'setpathdynare6_5.m');

% ── Validate ─────────────────────────────────────────────────────────────
if ~exist(utilities_path, 'dir')
    error('setup_toolbox: utilities/ not found at:\n  %s', utilities_path);
end
if ~exist(toolbox_programs_path, 'dir')
    error('setup_toolbox: toolbox_programs/ not found at:\n  %s', toolbox_programs_path);
end
if ~exist(setpath_file, 'file')
    error('setup_toolbox: setpathdynare6_5.m not found at:\n  %s', setpath_file);
end

% ── Read setpathdynare6_5.m ──────────────────────────────────────────────
fid = fopen(setpath_file, 'r');
if fid == -1
    error('setup_toolbox: cannot open %s', setpath_file);
end
content = fread(fid, '*char')';
fclose(fid);

% ── Replace dir2 / dir3 assignments ──────────────────────────────────────
% Escape backslashes on Windows so they survive the replacement string.
utilities_esc        = strrep(utilities_path,        '\', '\\');
toolbox_programs_esc = strrep(toolbox_programs_path, '\', '\\');

content = regexprep(content, "dir2\s*=\s*'[^']*';", ...
    sprintf("dir2 = '%s';", utilities_esc));
content = regexprep(content, "dir3\s*=\s*'[^']*';", ...
    sprintf("dir3 = '%s';", toolbox_programs_esc));

% ── Write back ───────────────────────────────────────────────────────────
fid = fopen(setpath_file, 'w');
if fid == -1
    error('setup_toolbox: cannot write to %s', setpath_file);
end
fwrite(fid, content, 'char');
fclose(fid);

% ── Report ───────────────────────────────────────────────────────────────
fprintf('\nsetpathdynare6_5.m updated with absolute paths:\n');
fprintf('  utilities        -> %s\n', utilities_path);
fprintf('  toolbox_programs -> %s\n', toolbox_programs_path);
fprintf('Done. You can now copy setpathdynare6_5.m into any subfolder.\n\n');
