#' @export

repBIRT=function(object,nrep=1000,silent=FALSE){
  mcmc=object$mcmc
  model=object$model
  inflated=object$inflated
  N=nrow(object$z)
  nit=ncol(object$z)
  item.out=object$output

  alpha=rstan::extract(mcmc,"alpha")$"alpha"
  nsamples0=nrow(alpha)
  if(nsamples0<nrep) stop("the nrep provided exceeds the number of actual posterior samples")
  index=rev(seq(nsamples0,nsamples0-nrep,by=-1))
  alpha=alpha[index,]
  beta=rstan::extract(mcmc,"beta")$"beta"[index,]
  phi=rstan::extract(mcmc,"phi")$"phi"[index,]
  theta=rstan::extract(mcmc,"theta")$"theta"[index,]


  if(inflated=="zero" | inflated=="both") gamma0_c=rstan::extract(mcmc,"gamma0")$"gamma0"[index,] else gamma0_c=matrix(-Inf,nrep,nit)
  if(inflated=="one" | inflated=="both") gamma1_c=rstan::extract(mcmc,"gamma1")$"gamma1"[index,] else gamma1_c=matrix(Inf,nrep,nit)


  if(inflated=="zero" | inflated=="both"){
    if(inflated=="zero"){
      one_mask=rep(0,nit)
      one_mask_matrix=diag(0,nit)
    }
    zero_mask=1*(is.finite(item.out[,"gamma0"]))
    zero_mask_matrix=matrix(0,sum(zero_mask),nit)
    for(i in 1:nit){
      if(zero_mask[i]==1) zero_mask_matrix[sum(zero_mask[1:i]),i]=1
      if(zero_mask[i]==0) zero_mask_matrix[sum(zero_mask[1:i]),i]=0
    }
  }

  if(inflated=="one" | inflated=="both"){
    if(inflated=="one"){
      zero_mask=rep(0,nit)
      zero_mask_matrix=diag(0,nit)
    }
    one_mask=1*(is.finite(item.out[,"gamma1"]))
    one_mask_matrix=matrix(0,sum(one_mask),nit)
    for(i in 1:nit){
      if(one_mask[i]==1) one_mask_matrix[sum(one_mask[1:i]),i]=1
      if(one_mask[i]==0) one_mask_matrix[sum(one_mask[1:i]),i]=0
    }
  }

  gamma0=gamma0_c%*%zero_mask_matrix
  gamma0[,zero_mask==0]=-Inf
  gamma1=gamma1_c%*%one_mask_matrix
  gamma1[,one_mask==0]=Inf

  z_rep=array(NA,dim=c(nrep,N,nit))
  for(s in 1:nrep){
    if(!silent) cat("Simulating replicated data for posterior sample: ",s,"\r")
    z_rep[s,,]=rBIRT(N,nit,alpha[s,],beta[s,],phi[s,],theta[s,],gamma0[s,],gamma1[s,],model = model)
  }
  if(!silent) cat("\n")
  return(z_rep)
}
