%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Part of the replication package for the paper
%   "Marginal Effects for Probit and Tobit with Endogeneity"
%   by Kirill S. Evdokimov, Ilze Kalnina, and Andrei Zeleneev.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function res_CI_j = fn_ivtobit_PE_CI(theta, CI_sig_Us, h, Sigma, j, alpha, bProb)
  if nargin<7; bProb=0; end
  assert(isreal(theta) && isreal(CI_sig_Us) && isreal(Sigma));
  
  %dim_theta = length(theta);
  res_CI_j = [0 0];
  for bUB = 0:1
    j0  = qyn(bUB,  j, -j);
    mul = qyn(bUB, -1,  1);
    fn_raw_CI_j = @(sig_Us) fn_ivtobit_PE_CI_at_sigUs(theta,sig_Us,h,Sigma,j0,alpha,bProb);
    fn_CI_j = @(sig_Us) mul*fn_raw_CI_j(sig_Us); %mul by -1 to find max
    [x_opt,fval_opt,exitflag] = fn_grid_fminbnd(fn_CI_j, CI_sig_Us(1), CI_sig_Us(2), 1e-7, 11); %#ok<ASGLU>
    res_CI_j(1+bUB) = mul*fval_opt;
  end
end

