function  [Ccos,Csin,padded_stim] = PLM_convolve(stim,Idef)

%PLM_CONVOLVE -- Illustrate part of the processing within PLM_INPUT
%
%  [Ccos,Csin] = PLM_convolve(stim,Idef)
%  [Ccos,Csin,padded_stim] = PLM_convolve(stim,Idef)
%
%  This function is not neccessary for the application of the model.
%  It is provided for its instructional value only.
%
%  STIM is a grayscale image (in IJ coordinates when IDEF.flipud=1=deflt).
%  IDEF is a "front-end definition structure" produced by MAKE_PLFRONTEND.
%  CCOS and CSIN are 4-D arrays of size [FFT_size(1) x FFT_size(2) x
%  x N_orient x N_spfreq]. Each "page" Cxxx(:,:,o,f) is a grayscale
%  image derived by convolving STIM with the corresponding Gabor filter.
%  The optional PADDED_STIM outputs the normalized, zero-padded image
%  that was actually filtered.
%
%  Example:
%   Ipar=PLM_input_params ; load saturn;stim=saturn1;sz=size(stim);
%   Ipar.img_size=sz;Ipar.D_orient=[-45:15:45];Ipar.D_spfreq=[1 2 4 6];
%   Ipar=PLM_input_params(Ipar) ; Idef=make_PLFrontend(Ipar) ;
%   [Ccos,Csin,pstim]=PLM_convolve(stim,Idef);
%   o=6;f=3;c=Ccos(:,:,o,f);s=Csin(:,:,o,f);  % O=+30 deg, F=4 cyc/dva
%   subplot(2,2,1);imagesc(pstim,[-1 1]);axis xy;colormap gray;
%   subplot(2,2,3);imagesc(c,[-.15 .15]);axis xy;title('cos phase');
%   subplot(2,2,4);imagesc(s,[-.15 .15]);axis xy;title('sin phase');
%   subplot(2,2,2);imagesc(-c.^2-s.^2);axis xy;title('energy');
%
%  See also PLM_STIM_ENERGY, MAKE_PLFRONTEND, PLM_RFIELDS, CONV2.

%  Original coding by Alexander Petrov, UC Irvine.
%  $Revision: 2.0 $  $Date: 2002/06/20 09:00 $

global FRONTEND_MEMOIZATION

%-- Make sure that the memoization store is up to date
if (FRONTEND_MEMOIZATION.CRC ~= Idef.memo_CRC)
   error('FRONTEND_MEMOIZATION is obsolete. Call MAKE_PLFRONTEND.') ;
end

%-- Decipher IDEF
N_orient = Idef.N_orient ;
N_spfreq = Idef.N_spfreq ;
img_size = Idef.img_size ;
FFT_size = Idef.FFT_size ;
pad_XY = Idef.pad_XY ;

%-- Normalize the stimulus
s = (stim-Idef.LUT_gray) ./ Idef.LUT_span ;    % now in [-.5 +.5] range
background_color = s(Idef.bkgr_idx) ;
if (Idef.flipud)       % STIM is in IJ- instead of XY-coordinates?
   s = flipud(s) ;     % See PLM_STIM_ENERGY for details
end

%-- Pad with BACKGROUND_COLOR and take the Fourier transform
padded_stim = repmat(background_color,FFT_size) ; 
padded_stim([1:img_size(1)]+pad_XY(1),[1:img_size(2)]+pad_XY(2)) = s ;
stim_FFT = fft2(padded_stim) ;

%-- Convolve with each of the filters cached in FRONTEND_MEMOIZATION
Ccos = zeros([FFT_size,N_orient,N_spfreq]) ;    % e.g. [128,128,37,3]
Csin = zeros([FFT_size,N_orient,N_spfreq]) ;
for o = 1:N_orient
   for f = 1:N_spfreq
      H = stim_FFT .* FRONTEND_MEMOIZATION.RFcosFFT{o,f} ;
      Ccos(:,:,o,f) = real(ifft2(H)) ;
      H = stim_FFT .* FRONTEND_MEMOIZATION.RFsinFFT{o,f} ;
      Csin(:,:,o,f) = real(ifft2(H)) ;
   end
end

%--- Return CCOS, CSIN, and optionally PADDED_STIM
%%%%% End of file PLM_CONVOLVE.M
