function out = tnormrnd (mu,sig,l,r)
%
%
% PURPOSE: returns random draws from the truncated normal
% distribution with mean (vector) u, standard deviation sig, and 
% left and right truncation points (or vectors) l and r.
%---------------------------------------------------
% INPUTS: 
% where: mu = mean or mean vector of the (untruncated) normal
%        sig = standard deviation (can be a vector if sig is unequal across
%        observations)
%        l = left trunction point or vector (must be of same length as mu)
%        r = right trunctaion point or vector (must be of same length as
%        mu)
%---------------------------------------------------
% OUTPUT:
% a vector of random draws from the truncated normal distribution     
%
%
% written by:
% Klaus Moeltner
% University of Nevada, Reno
n=length(mu);
% L=min(normcdf((l-mu)./sig),0.99999); % to avoid "1" for LOWER bound
% U=max(normcdf((r-mu)./sig),0.00001); % to avoid "0" for UPPER bound
% % this turned out unnecessary for the Bayesian selection model after
% eliminating errors in the GS
% also, this produces nonsensical results if L and U are given bounds
% (data)
L=normcdf((l-mu)./sig); 
U=normcdf((r-mu)./sig); 
u=L+(abs(U-L).*rand(n,1));
out=norminv(u).*sig + mu;