% write_ss_initval_block.m
% Script called from convertmodfiles.m after make_ss_ramsey/make_ss_nash/etc.
% Rewrites the initval block in outfilename.mod with true steady-state values.
%
% Requires workspace variable: outfilename (set by convertmodfiles.m).
%
% SS computation is delegated to get_ss_values(), a separate function with
% its own clean workspace, to avoid eval scoping issues from convertmodfiles'
% global M_ declaration.

%% 1. Compute SS values (get_ss_values reads the .mod file itself)
ss_vals = get_ss_values(outfilename,varss_list,lmss_list);

ss_endovarlist = [varss_list;lmss_list];

%% 3. Build the initval block
fv       = @(x) sprintf('%.15g', x);
iv_lines = {'initval;'};
for kk = 1:length(ss_endovarlist)
    vname = ss_endovarlist{kk};
    if endsWith(vname,'_ss')
        vname = vname(1:end-3);
    end
    if isfield(ss_vals, vname) && isfinite(ss_vals.(vname))
        iv_lines{end+1} = [vname, ' = ', fv(ss_vals.(vname)), ';'];
    else
        iv_lines{end+1} = [vname, ' = 0;'];
    end
end
iv_lines{end+1} = 'end;';
new_initval = strjoin(iv_lines, newline);

modtxt = fileread([outfilename, '.mod']);

%% 4. Insert or replace the initval block in the .mod file
if ~isempty(strfind(modtxt, 'initval;'))
    % Case A: replace existing block
    modtxt_new = regexprep(modtxt, 'initval;.*?end;', new_initval, 'dotall');
else
    % Case B: no initval block — insert right after the model block's closing end;
    % Find the model keyword (handles both model; and model(...);)
    pos_semi  = strfind(modtxt, 'model;');
    pos_paren = strfind(modtxt, 'model(');
    model_pos = min([pos_semi, pos_paren]);

    % First 'end;' after the model keyword closes the model block
    after_model  = modtxt(model_pos:end);
    end_rel      = strfind(after_model, 'end;');
    end_abs      = model_pos + end_rel(1) - 1;   % absolute index of 'e' in 'end;'
    insert_after = end_abs + 3;                   % absolute index of ';' in 'end;'

    modtxt_new = [modtxt(1:insert_after), newline, new_initval, newline, ...
                  modtxt(insert_after+1:end)];
end

fid = fopen([outfilename, '.mod'], 'w');
fwrite(fid, uint8(modtxt_new));
fclose(fid);
fprintf('write_ss_initval_block: initval block written in %s.mod\n', outfilename);

%% 5. Clean up
clear modtxt modtxt_new ss_endovarlist ss_vals iv_lines new_initval fv kk vname
clear pos_semi pos_paren model_pos after_model end_rel end_abs insert_after
