#' Compute the corrected estimator via estimating equations
#'
#' This function computes the corrected estimator for a linear model
#' with measurement error in covariates by solving the corrected
#' estimating equations using a nonlinear root-finding algorithm.
#'
#' @param y Numeric vector of length \code{n}. Response variable.
#' @param Wbar Numeric matrix of dimension \code{n × p}. Error-prone
#'   covariates at the averaged (replicate) level.
#' @param Zmat Numeric matrix of dimension \code{n × q}. Error-free
#'   covariates (including intercept if applicable).
#' @param estSigmaU_bar Measurement error variance/covariance associated
#'   with the averaged covariates. Can be \code{n × p × p} or \code{n × 1}.
#' @param beta_in Optional numeric vector of length \code{p + q}. Initial
#'   value for the estimating equation solver.
#'
#' @return Numeric vector of length \code{p + q}, the corrected estimator.
#'
#' @details
#' The estimator is obtained by solving
#' \deqn{E_n(\beta) = 0}
#' where \code{E_n} is the corrected estimating equation implemented in
#' \code{estim_eq_corrected()}.
#'
#' @seealso \code{\link{estim_eq_corrected}}
#'
#'@keywords internal
#'
computing_corrected_estimator <- function(y,
                                          Wbar,
                                          Zmat,
                                          estSigmaU_bar,
                                          beta_in = NULL) {

  n <- length(y)
  p <- ncol(Wbar)
  q <- ncol(Zmat)

  # default initial value
  if (is.null(beta_in)) {
    beta_in <- rnorm(p + q)
  }

  # estimating equation
  D <- function(b) {
    estim_eq_corrected(y, Wbar, Zmat, b, estSigmaU_bar)
  }

  # solve D(b) = 0
  sol <- nleqslv::nleqslv(
    x = beta_in,
    fn = D,
    control = list(trace = 0)
  )

  sol$x
}
