% Algorithm steps
% 1. Declare fixed parameter values. (in the mod file)
% 2. Declare intial steady state values.
% 	2.1. Store in a vector that is able to update its values later on.
% 3. Declare parameter initial values for moment matching.
% 4. Declare a vector with target moments.
% 5. Set options for optimizing.
% 6. Optimize

% Notes:
% -Fixed parameter values are declared directly in the mod file.
% -Initial ss values are given by numerically computed ss with initial 
% parameter values.
% -

% Characteristics of the function to get to zero:
% criterion
% 1. Must take as arguments:
% 	1.1. Vector containing target values. (tgt)
% 	1.2. Vector containing parameter values for computing moments. (prs).
% 3. Assign prs to the mod file.
% 4. Compute moments with current parameter values using dynare and oo_ output.
% 5. Compute norm between current parameter resulting moments and tagets
% and return this norm.

% Initial steady state values with no calibration
lambda_0 = 0.0201722;
c_0 = 48.0318;
n_0 = 0.467879;
m_0 = 11.8626;
k_0 = 490.997;
i_0 = 0.04535;
pi_0 = 0.01;
r_0 = 0.0579104;
I_0 = 12.2749;
w_0 = 26.045;
y_0 = 60.9059;
a_0 = 1;
vc_0 = 4.049;
vI_0 = 1.03475;
sc_0 = 0.00572784;
sI_0 = 0.0264003;
S_TC_0 = 1;
S_TCc_0 = 1;
S_TCI_0 = 1;
mu_0 = 0.0194697;
mc_0 = 0.666926;
pi_ast_0 = 0.0203061;
ups_0 = 1.00031;
xn_0 = 1.63137;
xd_0 = 2.42234;
lambdaX_0 = -0.0025589;
X_0 = 48.0318;

% Store initial steady state values in a vector
current_full_ss = [lambda_0, c_0, n_0, m_0, k_0, i_0, pi_0, r_0, I_0, w_0, ...
y_0, a_0, vc_0, vI_0, sc_0, sI_0, S_TC_0, S_TCc_0, S_TCI_0, mu_0, mc_0, ...
pi_ast_0, ups_0, xn_0, xd_0 lambdaX_0, X_0];

save cur_full_ss current_full_ss

% Initial values for parameters
theta_0 = 0.5;
prs_0 = [theta_0];

% Target moments
n_tgt = 1;
tgt = [n_tgt];

% options = optimset('Display','on','TolFun',1e-4,'MaxIter',10000, ...
%     'TolX',2e-10,'MaxFunEvals',10000);
options = optimset('Display','on');

[prs_1 Fval] = fsolve(@(prs) l2_norm(tgt,prs), prs_0, options);

prs_1

function q = l2_norm(tgt,prs)

	prs(1) % current value of theta
	save parameters_aux prs % saves the current value such that it's loaded 
	% in the mod file
	display('Current values') 
	display(mat2str(prs)) % Print values for checking

	dynare('num_cal.mod','noclearall')

	% Get full steady state for using it as the next steady state initvals
	global oo_
	current_full_ss = oo_.steady_state;
	save cur_full_ss current_full_ss % Update existing cur_full_ss to current

	% Get current target values
	cur_n_ss = oo_.steady_state(3)

	current_tgt_ss = [cur_n_ss];

	q(1) = tgt(1) - current_tgt_ss(1);
end