function usg_noise_bayes1(std_param0,param0,k,LB,UB,tar);
%usg_noise_bayes1(std_param0,param0,k,tar,LB,UB);
%computes the value of k that delivers an 
%acceptance rate (tar) of about tar percent. The parameter k is  a scale factor of the variance of the stand in distribution.  
%This code is a sub-routine of a suite of programs that performs Bayesian estimation of the open economy model with stationary, nonstationary, and noise shocks and imperfect information presented in the book Open Economy Macroeconomics, by Martín Uribe and Stephanie Schmitt-Grohé (Princeton University Press) in  the chapter `Business Cycles in Emerging Countries: Productivity Shocks Versus Financial Frictions.'' 
%(c) M. Uribe and S. Schmitt-Grohe, January 2014. 

format compact

%Number of draws of the MCMC chain
ndraw = 1e+6;

%Number of estimated parameters
np = length(param0);

%load data
Y1 = xlsread('mexico_data.xls');
%columns: date, growth rate of output, growth rate of consumption, growth rate of investment, trade-balance-to-gdp ratio.
%mexico_data.xls was created by running data_level2growth.m in
%c:\data\uribe\book\noise_shocks\mfiles
T = size(Y1,1);  %number of observations

%Demean the data and remove date column
Y = Y1(:,2:end) - ones(T,1)*mean(Y1(:,2:end));

pick_variables = [1 2 3 4]; %picks the elements of the policy function (rows of gx) corresponding to the observables.

%Initial Prior likelihood
logprior0 = log(prod( duniform(param0,LB,UB)));
 
%Calculate the initial log likelihood of the model for param0
loglikelihood0 =  log_likelihood(param0,pick_variables,Y);
 
%calculate initial posterior density value
logposterior0 =  loglikelihood0 + logprior0;

mean_k = k;
param_current = param0; 


logposterior_current = logposterior0;

%start drawing from posterior distribution
for j=1:ndraw

exitflag = 4;

%Draw parameter value
param = param_current +  mean_k * std_param0 * randn(np,1);

%Make sure the draw is within bounds

if (param>=LB) & (param <= UB) 

 [LL,exitflag] =  log_likelihood(param,pick_variables,Y);


%Make sure eq'm is locally unique
if exitflag==1

logposterior =LL + logprior0;

%Determine whether to accept or reject the draw
if rand <= exp(logposterior-logposterior_current) 

exitflag = 5; 

param_current = param;

logposterior_current = logposterior;

end %if rand

end %if exitflag

end %^if param>=LB ...

mean_k = mean_k*(j-1)/j + k/j;

%update the scaling factor of the variance of the stand-in distribution
k = k * (1+  0.01 * ((exitflag==5)-tar));

end %for j=1:ndraw

eval(['save usg_noise_bayes1.mat  param0 std_param0 mean_k tar '])