function Y = box_filter(X,F,b,opt)

% box_filter - linear box filtering
% ---------------------------------
% 
% Y = box_filter(X,F,b,opt)
%   = box_filter(X,F,b,opt)
%
% Input:
% ------
%  X - input image
%  F - box filter
%  b - boundary behavior (def: -1, look at 'image_pad')
%  opt - pad option (def: 1)
%
% Output:
% -------
%  Y - box filtered image

%--------------------------------
% Author: Harold Figueroa
%--------------------------------
% $Date: 2005-08-22 17:25:38 -0400 (Mon, 22 Aug 2005) $
% $Revision: 1623 $
%--------------------------------

% TODO: generalize function to handle multiple boxes

%--------------------------------------
% HANDLE INPUT
%--------------------------------------

%--
% set default padding
%--

if ((nargin < 4) || isempty(opt))
	opt = 1;
end 

%--
% set boundary behavior
%--

if (nargin < 3)
	b = -1;
end

%--
% ensure double image
%--

X = double(X); 

%--------------------------------------
% COMPUTE
%--------------------------------------

%--
% handle multiple plane images
%--

if (ndims(X) > 2)
	
	[r,c,d] = size(X);
	
	for k = 1:d
		Y(:,:,k) = box_filter(X(:,:,k),F,b,opt);
	end	
	
%--
% scalar image
%--

else
		
	%--
	% create equivalent box filter
	%--
	
	% NOTE: any filter value information is discarded, the support is used
	
	[m,n] = size(F);
	
	F = zeros(m + 2,n + 2);
	
	F(1,1) = 1; 
	F(m + 1,1) = -1;
	F(1,n + 1) = -1;
	F(m + 1,n + 1) = 1;
	
	%--
	% pad image if needed
	%--
	
	if (opt)
		X = image_pad(X,[(m - 1), (n - 1)] ./ 2,b);
	end
	
	%--
	% integrate and use sparse linear filter
	%--
	
	% TODO: improve or get rid of 'image_pad'
	
	X = image_pad(X,[1 1],-1);
		
	Y = integral_image_(X);
	
	Y = linear_filter_sparse_(Y,F);
		
end
