function [b, a, L] = design_fir_filter(F, A, D, L)

% design_fir_filter - design equiripple fir filter
% ------------------------------------------------
%
% [a, b] = design_fir_filter(F, A, D, L)
%
% Input:
% ------
%  F - band edges, not including 0 and nyquist
%  A - band amplitudes
%  D - band distortions
%  L - filter length
%
% Output:
% -------
%  b, a - filter coefficients ('a' is always 1 in this case)

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

%--
% set default distortion
%--

if nargin < 3 || isempty(D)
	D = 0.01 * ones(size(A));
end

%--
% revert to lowpass
%--

if F(1) < 0
	F = F(3:end); A = A(2:end); D = D(2:end);
end

%--
% revert to highpass
%--

if F(end) > 1
	F = F(1:end-2); A = A(1:end-1); D = D(1:end-1);
end

%--
% estimate order and prepare input for design function
%--

if nargin < 4 || isempty(L)
	[L, F, A, W] = firpmord(F, A, D); L = min(L, 256);
else
	F = [0; F(:); 1]'; A = kron(A, [1 1]); W = (1 ./ D); W = W ./ min(W);
end

%--
% update length for highpass and bandstop if needed
%--

if A(end) && mod(L, 2)
	L = L + 1;
end

%-------------------------------
% DESIGN FILTER
%-------------------------------

b = firpm(L, F, A, W); a = 1;
