%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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, PE_j] = fn_ivtobit_PE_CI_at_sigUs(theta,sig_Us,h,Sigma,j0,alpha,bProb)
  % when j0<0 return the left end of the CI_PE for h_j with j=-j0, otherwise return the right end
  % bProb = 1 => PE^{Pr}, otherwise PE^{E}
  if nargin<7; bProb=1; end
  
  theta = theta(:); h = h(:);
  dim_theta = length(theta);
  assert(all(size(Sigma)==dim_theta*[1 1]));
  assert(length(h)==dim_theta);
  
  if j0>0
    j =  j0; bUB = 1;
  else
    j = -j0; bUB = 0;
  end
  theta_h = theta'*h;
  common_mul = normpdf(theta_h/sig_Us)/sig_Us;
  e_j = zeros(dim_theta,1); 
  e_j(j) = 1;
  
  if bProb
    PE_j = common_mul*theta(j);
    grad_j = (-(theta_h*theta(j)/sig_Us^2)*h + e_j)*common_mul;
  else
    ncdf = normcdf(theta_h/sig_Us);
    PE_j = ncdf*theta(j);
    grad_j = common_mul*theta(j)*h + e_j*ncdf;
  end
  se_j = sqrt(grad_j'*Sigma*grad_j);
  c_alpha = norminv(1-alpha/2);
  if bUB
    res_CI_j = PE_j + c_alpha*se_j;
  else
    res_CI_j = PE_j - c_alpha*se_j;
  end
end

