function  noise = make_PLE2_backgr(P,backgr,N)

%MAKE_PLE2_BACKGR -- Makes the specified stimulus for the PL Experiment1.
%
%  noise = make_PLE2_backgr(P,backgr)
%  noise = make_PLE2_backgr(P,backgr,N)
%
%  P is a "master parameter structure" generated by PLEXP2_PARAMS.
%  The following fields are relevant:
%    'size', 'Filter', 'noise_params', and 'noise_Cpeak'.
%  BACKGR is an index along the third dimension of P.Filter. It specifies
%  the orientation of the background filtered noise (see P.noise_orient).
%  N is the number of noise patches requested (default N=1).
%  NOISE is a (set of) filtered Gaussian noise patches, each suitable to
%  be mixed with a Gabor into a composite stimulus (see MAKE_PLE2_STIM).
%  NOISE is a 64x64xN matrix with elements b/n - and +noise_Cpeak.
%
%  Example:
%   P=PLExp2_params;n1=make_PLE2_backgr(P,1);n2=make_PLE2_backgr(P,2);
%   subplot(1,2,1);imagesc1(n1);subplot(1,2,2);imagesc1(n2);
%
%  See also MAKE_PLE2_STIM, CACHE_PLE2_BACKGR, FILTNOISE, PLEXP2_PARAMS.

%  Original coding by Alexander Petrov, UC Irvine.
%  $Revision: 1.0 $  $Date: 2003/08/04 17:10 $

if (nargin==2)  N = 1 ; end     % default

%-- Decipher params
sz = P.size ;                   % 64x64
sigma = P.noise_params.sigma ;
rawrange  = sigma * P.noise_params.outcut ;
filtrange = [-1 +1] .* P.noise_Cpeak ;
outcut = P.noise_params.outcut ;    % outlier cutoff ctiterion

%-- Select the appropriate filter
F = P.Filter(:,:,backgr) ;      % 64x64; 1=-15 deg, 2=+15 deg

%-- Main loop
noise = zeros([sz,N]) ;         % e.g. 64x64x300
for k = 1:N
  %- Generate a fresh patch of white noise
  rawnoise = randn(sz) .* sigma ;    % mean=0
  rawnoise = max(-rawrange,min(rawnoise,+rawrange)) ;
  %- Apply the filter
  noise(:,:,k) = filtnoise(F,filtrange,outcut,rawnoise) ;
end

%%%  Return NOISE
%%%%% End of file MAKE_PLE2_BACKGR.M
