function  sample = random_table(entry_points,N)

%RANDOM_TABLE -- Draw Gaussian variates from the global NRANDOM_TABLE.
%
%  sample = random_table(entry_points,N)
%
%  Draw a set of Gaussian variates from the global variable NRANDOM_TABLE.
%  ENTRY_POINTS must be a integer matrix with R rows and two columns.
%  Each row defines an independent draw from NRANDOM_TABLE. The first 
%  integer is the index of the first element of the sample; the second
%  integer specifies the step size (which can be positive or negative
%  but not zero). The length of NRANDOM_TABLE is a large prime number
%  (currently 999983) and all indices are taken modulo this number.
%  N is a positive integer specifying the number of desired values in
%  each sample.
%  The result SAMPLE is an R-by-N matrix of iid normal(0,1) variates.
%
%  Example:
%    entry_points = make_chev(N_trials); N = Mparams.rep_size ;
%    noise = random_table(entry_points,N+1) ; hist(noise(:)) ;
%    rep_ns = noise(:,1:N).*Mparams.rep_noise ; 
%    out_ns = noise(:,N+1).*Mparams.out_noise ;
%
%  See also RANDN, MAKE_CHEV, PLMODEL1.

%  Original coding by Alexander Petrov, UC Irvine.
%  $Revision: 1.0 $  $Date: 2002/07/26 14:47 $

global NRANDOM_TABLE

if (isempty(NRANDOM_TABLE))
   disp('Global NRANDOM_TABLE not set. Generating one, L=999983...') ;
   NRANDOM_TABLE = randn(999983,1) ;
end
table_length = length(NRANDOM_TABLE) ;  % some large prime, e.g. 999983

%-- Expand indices: start=entry_points(:,1), step=entry_points(:,2)
if (size(entry_points,2)<2)
   error('ENTRY_POINTS should have at least two columns.') ;
end
idx = entry_points(:,2) * [0:N-1] ;             % [0:step:(N-1)*step]
idx = idx + repmat(entry_points(:,1)-1,1,N) ;   % [start:step:end]
idx = mod(idx,table_length) + 1 ;

%-- Draw from the table
sample = NRANDOM_TABLE(idx) ;
if (size(entry_points,1)==1)   % fix a nuisance
   % SAMPLE is a column-vector when R==1 because NRANDOM_TABLE is col-v.
   sample = reshape(sample,1,N) ;
end

%--- Return SAMPLE
%%%%% End of file RANDOM_TABLE.M
