function steadystate(fname)
% function steadystate(fname)
% Crée le fichier steadystate de Dynare

%disp('Creating Steady-State file')
truncfname = fname(1:(length(fname)-4));
f = fopen([ fname '_steadystate.mod' ],'r');
if f == -1
    f = fopen([ fname '_steadystate.dyn' ],'r');
	if f == -1
        f = fopen([ truncfname '_steadystate.mod' ],'r');
        if f == -1
            f = fopen([ truncfname '_steadystate.dyn' ],'r');
            if f == -1
                return
            end
        end
    else
        truncfname = fname;
    end
else
    truncfname = fname;
end
file = textscan(f, '%s', 'delimiter', '\n');
fclose(f);
lignes=file{1};
nblignes = size(lignes,1);

f = fopen([ truncfname '_steadystate.m' ],'w');

fprintf(f, [ 'function [ys,check] = ' truncfname '_steadystate(ys,exe)\n' ]);
fprintf(f, 'global M_ lgy_\n\n');

fprintf(f, 'if isfield(M_,''param_nbr'') == 1\n');
fprintf(f, 'NumberOfParameters = M_.param_nbr;\n');
fprintf(f, 'for i = 1:NumberOfParameters\n');
fprintf(f, '  paramname = deblank(M_.param_names(i,:));\n');
fprintf(f, '  eval([ paramname '' = M_.params('' int2str(i) '');'']);\n');
fprintf(f, 'end\n');
fprintf(f, 'check = 0;\n');
fprintf(f, 'end\n\n');

for k = 1:nblignes
    fprintf(f, '%s\n', char(lignes(k,:)));
end

fprintf(f, '\nfor iter = 1:length(M_.params)\n');
% Correction of the following line.  Thanks to "jpfeifer" from the Dynare forum.
%fprintf(f, '  evalin(''base'',[ ''M_.params('' num2str(iter) '') = '' M_.param_names(iter,:) '';'' ])\n');
fprintf(f, '  eval([ ''M_.params('' num2str(iter) '') = '' M_.param_names(iter,:) '';'' ]);\n');
fprintf(f, 'end\n');

fprintf(f, '\nif isfield(M_,''param_nbr'') == 1\n');
fprintf(f, '\nif isfield(M_,''orig_endo_nbr'') == 1\n');
fprintf(f, 'NumberOfEndogenousVariables = M_.orig_endo_nbr;\n');
fprintf(f, 'else\n');
fprintf(f, 'NumberOfEndogenousVariables = M_.endo_nbr;\n');
fprintf(f, 'end\n');
fprintf(f, 'ys = zeros(NumberOfEndogenousVariables,1);\n');
fprintf(f, 'for i = 1:NumberOfEndogenousVariables\n');
fprintf(f, '  varname = deblank(M_.endo_names(i,:));\n');
fprintf(f, '  eval([''ys('' int2str(i) '') = '' varname '';'']);\n');
fprintf(f, 'end\n');
fprintf(f, 'else\n');
fprintf(f, 'ys=zeros(length(lgy_),1);\n');
fprintf(f, 'for i = 1:length(lgy_)\n');
fprintf(f, '    ys(i) = eval(lgy_(i,:));\n');
fprintf(f, 'end\n');
fprintf(f, 'check = 0;\n');
fprintf(f, 'end\n');

fclose(f);
