% Gregory Ng (gregng at stanford)
% EE 362/Psych 221
% Stanford University
% March 2005

% Find the average of a particular patch out of an image.

function [imavg, imvar] = average_images( folder, filenames, x1, x2, y1, y2, gamma )


if (nargin == 7)
	g1 = 1 / gamma;
else
	g1 = 1;
end

%------------------------
% Initialization
slen = size(filenames,1);
sx = x2 - x1 + 1;
sy = y2 - y1 + 1;
[sx sy];

imstdev = zeros(slen+1, 4);
%------------------------
%savepatches = 0;


if (x1 ~= x2 && y1 ~= y2) 
	process_patch = 1;
else
	process_patch = 0;
end


for idx = 1:slen
	%------------------------
	fullname = sprintf('%s%s%s', folder, filesep, filenames(idx, :) );
	
	% We're interested in the part that's not the filename.
	[pathstr fname ext versn] = fileparts(fullname);
	%------------------------
	
	disp(sprintf('%s',fullname) );
	im = imread( deblank( fullname ) );
	
	if (process_patch) 
		% Take a patch out of the upper left corner
		im = im(y1:y2, x1:x2, :);
	else
		%im = (im);
	end
	
	% mult by 255 is to renormalize from im2double's scaling down to 1
	if (gamma ~= 1)
		im = (im2double(im) .^ g1) .* 255;
	else
		im = im2double(im) .* 255;
	end
	
	if (idx == 1)
		imavg = im;
		imvar = imavg .* imavg ;
	else		
		imavg = imavg + im;
		imvar = imvar + im .* im;
	end
	
	%if (savepatches == 1 && process_patch == 1)
	%	% Save the patch
	%	imwrite(im ./256, sprintf('%s%s%s_%s.png', folder, filesep, output_prefix, fname), 'PNG');
	%end
	
	pause(0.5);
end
clear im;

imavg = imavg ./ slen;

% per-pixel variance ( E[x^2] - E[x]^2 )
imvar = (imvar ./ slen) - (imavg .* imavg);
