% this function takes a stack of images named PATCH(heigh, width, #images)
% and a provided weight vector W  and output the decision value
% Yout
function Yout = YoutFromPatchSimple(PATCH, W)

		[n_W n_AU] = size(W);
		n_PATCH= size(PATCH,3);
		Yout = zeros(n_PATCH, n_AU);  % #images x #AUs

		%Andrew: if you're short of time, this part can be precomputed and store in files.
		gb = InitGaborPyramid();  

		for i=1:n_PATCH
			Yout(i,:)=YoutFromImage(PATCH(:,:,i), W, gb);
		end
return



% obtain gb from GaborPyramid(), and generate a new field padFilter attached
% to the original gb struct-array. The padFilter is obtained by padding and
% FFT rawFilter.
function [gb] =InitGaborPyramid()
		%prepare filters
		gb = GaborPyramid();
		for i=1:prod(size(gb))
			H=gb(i).rawFilter;
			szPad = size(H)*2-1; %assume incoming image has same size
			pH = zeros(szPad);
			pH(1:size(H,1), 1:size(H,2)) = H; 
			gb(i).padFilter=fft2(pH);
		end
return

% 
function [Y F]=YoutFromImage(Pimg, W, gb)
			F=FeatFromImage(Pimg, gb);
			Y= F*W;
return 

function F=FeatFromImage(Pimg, gb)
			F=[]; %the size of Feature is actuall KNOWN ahead of time, but I'm lazy...
			[nLevel nDir]=size(gb);

			for pyLevel=1:nLevel
				% (1) down-sample to the same size as "rawFilter" to construct Pyramid
				% matlab default imresize with bicubic interpolation, hope you find some similar function
				% any good interpolation is OK.
				X=imresize(Pimg, size(gb(pyLevel,1).rawFilter));

				% (2) padding to 2x-1 size, similar to what we did for rawFilter->padFilter
				szPad = size(X)*2-1;
				padX = zeros(szPad);
				padX(1:size(X,1), 1:size(X,2))=X;
				padXFFT = fft2(padX);

				for pyOri=1:nDir
					%convolution filtering and remove the borders
					[img_h img_w]=size(X);
					Fx = ifft2(padXFFT.* gb(pyLevel,pyOri).padFilter);
					Fx = Fx((img_h/2):(3*img_h/2-1), (img_w/2):(3*img_w/2-1)); %cut the center rigion
					Fmag = abs(Fx(:)');

					%normalize
					subF = Fmag./norm(Fmag,2);

					% linear predictor
					F=[F subF];

				end %for-orientation
			end %for-level
			F= [F 1];
return
