%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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 [CI_PE_Corr,CI_sig_Us] = fn_CI_PE_and_sig_Us(bProbit,R,alpha,alpha_bonf_1,Sig_theta_V_sig_e1,sig_U,Sigma_theta)
  % Calculate CI for PE and sig_Us
  %
  % --- KEY INPUTS -----
  %  R  : source of R.sig_Us_LB_1, R.sig_Us_LB_2, R.theta, R.h_for_PEs
  %
  %  Reference: xobit_empirical_application, calc. of asy_CI

  dim_theta    = length(R.theta);
  if nargin<5
    Sig_theta_V_sig_e1 = R.asy_Sig_for_bounds(2:3,2:3);
    sig_U              = R.sig_U;
    Sigma_theta        = R.asy_Sig_eta(1:dim_theta,1:dim_theta);
  end
  assert(all(size(Sig_theta_V_sig_e1)==[2,2]))
  assert(isscalar(sig_U))
  assert(isscalar(alpha))
  assert(alpha_bonf_1<alpha)
  assert(bProbit==0 || bProbit==1)

  asy_CI_sig_Us2_LB = max(1e-7, inference_on_max([R.sig_Us_LB_1^2 R.sig_Us_LB_2^2], Sig_theta_V_sig_e1,            alpha_bonf_1/2));
  asy_CI_sig_Us     = [sqrt(asy_CI_sig_Us2_LB) 0];
  asy_CI_sig_Us(2)  = R.sig_U + sqrt(R.asy_Sig_for_bounds(1,1)) * norminv(1-alpha_bonf_1/2);

  CI_sig_Us = asy_CI_sig_Us;

  CI_PE_Corr = zeros((2-bProbit)*dim_theta,2);
  for bProb=[qyn(bProbit, [], 0) 1] %inference on Pr or E. "for bProb = 1", or "for bProb = [0 1]"
    for j = 1:dim_theta
      res_CI_j   = fn_ivtobit_PE_CI(R.theta,CI_sig_Us,R.h_for_PEs,Sigma_theta,j,alpha-alpha_bonf_1,bProb);
      if bProbit
        i_row = j;
      else
        i_row = j+bProb*dim_theta;% one line: i_row = j+(~bProbit)*bProb*dim_theta
      end
      CI_PE_Corr(i_row,1:2) = res_CI_j;
    end
  end

end

