function  [img,rawnoise] = make_PLE_stim(P,orient,diff,backgr,rawnoise)

%MAKE_PLE_STIM -- Makes the specified stimulus for the PL Experiment1.
%
%  [img,rawnoise] = make_PLE_stim(P,orient,diff,backgr,rawnoise)
%
%  RAWNOISE is passable as an optional parameter. (ver 2.1, 2003/02/24)
%
%  P is a "master parameter structure" specifying the image size, the
%  set of possible orientations, frequencies, contrasts, etc.
%  The following fields are relevant: 'Gabor','Filter','noise_params',
%  'LUT_params','colors','noise_Cpeak', and 'mask_idx'.
%  ORIENT is an index along the third dimension of P.Gabor. It specifies
%  the orientation of the Gabor patch (see also P.Gabor_orient).
%  DIFF is an index along the fourth dimension of P.Gabor. It specifies
%  the stimulus contrast and hence the difficulty level (P.Gabor_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).
%  IMG is a matrix of integers (0:255) ready for presentation.
%
%  MAKE_PLE_STIM calls FILTNOISE to generate a new patch of filtered noise
%  with the specified properties, then forms an additive mixture of
%  P.Gabor(:,:,orient,diff) and the noise. Finally, it converts the
%  gray levels into lookup table indices and crops everything into a
%  circular window (using P.mask_idx).
%
%  See also MAKE_PLE_STIM, CACHE_INPUTS, FILTNOISE.

%  Original coding by Alexander Petrov, UC Irvine.
%  $Revision: 2.1 $  $Date: 2003/02/24 14:47 $

%-- Generate a fresh patch of white noise
if  (nargin<5)
   range = P.noise_params.sigma * P.noise_params.outcut ;
   rawnoise = randn(P.size) .* P.noise_params.sigma ;      % mean=0
   rawnoise = max(-range,min(rawnoise,+range)) ;
%else rawnoise supplied by caller
end

%-- Apply the appropriate filter
range = [-1 +1] .* P.noise_Cpeak ;
outcut = P.noise_params.outcut ;    % outlier cutoff ctiterion
noise = filtnoise(P.Filter(:,:,backgr),range,outcut,rawnoise) ;

%-- Form the additive mixture. The contrasts are already built in.
stim = P.Gabor(:,:,orient,diff) + noise ;
% mean(stim(:)) should be 0 as both mean(noise) and mean(Gabor) are 0.

%-- Plot descriptive statistics on the screen
%foo=P.Gabor(:,:,orient,diff) ;
%valid_pixels = setdiff([1:prod(P.size)]',P.mask_idx) ;
%describe([foo(valid_pixels),rawnoise(valid_pixels),...
%          noise(valid_pixels),stim(valid_pixels)]) ;

%-- Align with the lookup table
img = round(stim.*P.LUT_params.span) + P.colors.gray ;

%-- Crop and return
img(P.mask_idx) = P.colors.gray ;
img = min(max(img,P.colors.black),P.colors.white) ;

%%%  Return IMG (and NOISE, though the latter is not advertized)
%%%%% End of file MAKE_PLE_STIM.M
