% Find local min.
% This code tries to find local min.
% Just running Matlab fmincon does not seem to find the right place.
% We supplement fmincon with our own program (cross section min.)

clear;
format longG;

lb = [0,0,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf];
ub = Inf*ones(1,10);
AA = []; b = []; Aeq = []; beq = []; nonlcon = [];
options = optimset('TolX',10^-24,'MaxFunEvals',3000,'TolFun',10^-24,'Algorithm','interior-point');

num_iter = 25; % set this number to suit your case. in this case, it runs until 5 iterations with about 650 seconds of execution time.
x_update_all = NaN(num_iter,10);
fval_update_all = NaN(num_iter,1);
exitflag_update_all = NaN(num_iter,1);
x_update_new_all = NaN(num_iter,10);
f_old_all = NaN(num_iter,1);
f_new_all = NaN(num_iter,1);
usualx = NaN(num_iter,1);
load 'C:\Users\LoweryR\Documents\My Dropbox\UND_research_Banking\Final_files\output_files\theta_GMM1st_KLW.mat';
% the file has 'x_1stGMM','fval_1stGMM','exitflag_1stGMM'
x_seed = x_1stGMM;
     
for i = 1:num_iter
    tic
    [x_update,fval_update,exitflag_update] = fmincon(@param_obj_cont_KLW,x_seed,AA,b,Aeq,beq,lb,ub,nonlcon,options);
    while exitflag_update == 0
    [x_update,fval_update,exitflag_update] = fmincon(@param_obj_cont_KLW,x_update,AA,b,Aeq,beq,lb,ub,nonlcon,options);
    end
    if exitflag_update == 1
        break
    end
    x_update_all(i,:) = x_update;
    fval_update_all(i,:) = fval_update;
    exitflag_update_all(i,:) = exitflag_update;
    x_updateforfn = x_update;
    [x_update_new,f_old,f_new,minf,x_minf,theparam_length] = fn_obj_cont_KLW(x_updateforfn);
    if f_new <= minf
        usualx(i) = 1;
        x_update_new_all(i,:) = x_update_new;
        f_new_all(i,:) = f_new;
    elseif f_new > minf
        usualx(i) = 2;
        x_update_new_all(i,:) = x_minf;
        f_new_all(i,:) = minf;
    end
    x_seed = x_update_new_all(i,:);
    f_old_all(i,:) = f_old;
    
    i
    [x_update;x_update_new_all(i,:)]
    [fval_update;f_new_all(i,:)]
    if x_update_new_all(i,:) == x_updateforfn
        break
    elseif  theparam_length > 1 % meaning more than one parameter satisfy minf=f_new
        break
    end
    toc
end
x_update
fval_update
exitflag_update

save('C:\Users\LoweryR\Documents\My Dropbox\UND_research_Banking\Final_files\output_files\findmin_KLW.mat',...
    'x_update_all','x_update_new_all','fval_update_all','exitflag_update_all','f_old_all','f_new_all','usualx');
