%%% steady state computation with numerically obtained parameters

function [ys,params,check] =ss_function(ys,exo,M_,options_)

	%global M_ 

    % load relevant matrices for the guess parameters
    guess_locations
    guess_variables

	if isfield(M_,'param_nbr') == 1
        check = 0;
	end

    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%% find ss parameters by finding fixed point %%%
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
           
    guess_vars=Guess(:,1)';
    guess_vars_upd=cell(1,10);
    for f = 1 : numel(guess_vars)
            guess_vars_upd{f} = [guess_vars{f} '_upd;'];           
    end
    initial_guess=cell2mat(Guess(:,2))';

    N_guess=length(guess_vars);
    for j=1:N_guess
        guess_params.(guess_vars{j}) = initial_guess(j);
    end
    diff1=1;
    guess_old=initial_guess;
    iter_search=0;
    

	fields.guess_params = fieldnames(guess_params, '-full');
	numberOfFields.guess_params = length(fields.guess_params);
    
    
    while diff1>10^-10&&iter_search<450
        iter_search=iter_search+1;
        
        for j=1:N_guess
            guess_old(j) = guess_params.(guess_vars{j}); 
        end 
        
        for f = 1 : numberOfFields.guess_params
            M_.params(guess_loc.(guess_vars{f}))=guess_params.(fields.guess_params{f});    
        end

        %%%%%%%%%%%%% equations file %%%%%%%%%%%%
        steady_state_equations2
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
        for f = 1 : numberOfFields.guess_params   
            M_.params(guess_loc.(guess_vars{f}))=upd(f);
        end
            
        for j=1:N_guess
            guess_params.(guess_vars{j}) = upd(j);       % guess_params.kG_ss= kG_ss_upd ....
        end
        diff1  =((upd - guess_old)*(upd - guess_old)')^0.5;   % get root of the squared difference between updated and previous value of parameters       
    end
    
    DISP=0;
    
    if DISP==1
        disp(['stopped at ' num2str(iter_search) ' iterations, sum of squared differences: ' num2str(diff1^2)])
    end
    
    if isfield(M_,'param_nbr') == 1
        if isfield(M_,'orig_endo_nbr') == 1
            NumberOfEndogenousVariables = M_.orig_endo_nbr;
        else
            NumberOfEndogenousVariables = M_.endo_nbr;
        end
        ys = zeros(NumberOfEndogenousVariables,1);
        for iter = 1:NumberOfEndogenousVariables
            ys( iter)=M_.params(loc_ss(iter));    
        end
    else
        check = 0;
    end
    
    n_aux=M_.endo_nbr-M_.orig_endo_nbr;  %%% get number of aux variables
    ys=[ys;zeros(n_aux,1)];
    params=M_.params;
    if rand<0.1 && ~any(isnan(upd))            
        fileID = fopen('guess_variables.m','w');
        fwrite(fileID,'Guess ={');
        for j=1:numel(guess_vars)   
            fwrite(fileID,['''' guess_vars{j} '''' ',' num2str(upd(j),20) ';']);
        end
        fwrite(fileID,'};');
        fclose(fileID);
    end
end


