function  img = make_PLE2_stim(P,orient,diff,NC_idx)

%MAKE_PLE2_STIM -- Makes the specified stimulus for the PL Experiment2.
%
%  img = make_PLE2_stim(P,orient,diff,NC_idx)
%
%  IMG is a matrix of integers (0:255) ready for presentation.
%  P is a "master parameter structure" specifying the image size, the
%  set of possible orientations, frequencies, contrasts, etc.
%  These fields are relevant: 'Gabor','LUT_params','colors','mask_idx'.
%  ORIENT specifies the orientation of the Gabor patch (see also
%  P.Gabor_orient). When ORIENT is 1 or 2, it is an index along the 
%  third dimension of P.Gabor, as used in PLEXP2. When ORIENT is 3 or 4,
%  a stimulus with ORIENT=1 or 2, respectively, is generated and then
%  rotated 90 degrees clockwise. See PLEXP2A for more details.
%  DIFF is an index along the fourth dimension of P.Gabor. It specifies
%  the stimulus contrast and hence the difficulty level (P.Gabor_Cpeak).
%  NC_IDX is an index in the global variable NOISE_CACHE. 
%  *** It is the responsibility of the caller (PLEXP2 and DO_PLE2_TRIAL)
%  *** to ensure that this global variable is properly initialized.
%  See also MAKE_PLE2_BACKGR and CACHE_PLE2_BACKGR.
%
%  MAKE_PLE2_STIM forms an additive mixture:
%    P.Gabor(:,:,orient,diff) + NOISE_CACHE(:,:,NC_idx)
%  It then converts the gray levels into lookup table indices and
%  crops everything into a circular window (using P.mask_idx).
%
%  See also PLEXP2, CACHE_PLE2_BACKGR, DO_PLE2_TRIAL, MAKE_PLE_STIM.

%  Original coding by Alexander Petrov, UC Irvine.
%  $Revision: 1.1 $  $Date: 2003/09/03 14:44 $

global NOISE_CACHE

%-- Intercept non-canonical orientations: 3=rot90(1), 4=rot90(2)
if (orient>2)
   img = make_PLE2_stim(P,orient-2,diff,NC_idx) ;   % now ORIENT=1 or 2
   img = flipLR(img') ;        % rotate 90 degrees clockwise
   return
%else  ORIENT is either 1 or 2 --> continue with the main work
end

%-- Retrieve the background noise patch from the cache, no error checking
noise = NOISE_CACHE(:,:,NC_idx) ;

%-- 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),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
%%%%% End of file MAKE_PLE2_STIM.M
