function [b,a]=order2filter(type,fs,G,f0,Q)
%
% Derive coefficients for a second order peak or shelf filter with
% a given amplitude and peak or transition frequency.
%
% Usage:     [b,a]=order2filter(type,fs,G,f0,Q);
%
%            type is a character string defining filter type
%                 Choices are: 'Peak', 'Bass', or 'Treble'
%            fs is the sampling rate in Hz (samples/second)
%            G is the gain in dB
%            f0 is the peak or transition frequency in Hz
%            Q determines with width of the peak filter and the slope
%              of the shelf filters. Note that for shelf filters, a
%              value of Q > 2 results in peaking around the transition
%              frequency.
%
% Algorithm: The function computes the coefficients for the correspoonding
%            analog filter and then uses the MATLAB function bilinear
%            to determine the corresponding digital filter coefficients.
%            The analog formulas are inverted for G < 0.
%
% Author:    Warren Koontz 1/8/2018
%
b=0; a=0; % default result in case of error
g=10^(abs(G)/20); % convert dB to straight gain
w0=2*pi*f0; % convert frequency to rad/sec
% compute analog filter coefficients
switch type
    case {'Bass','bass'} % bass shelf filter
        B=[1 2*sqrt(g)*w0/Q g*w0^2];
        A=[1 2*w0/Q w0^2];
    case {'Treble','treble'} % treble shelf filter
        B=g*[1 2*w0/Q w0^2];
        A=[1 2*sqrt(g)*w0/Q g*w0^2];
    case {'Peak','peak'} % peak filter
        B=[1 g*w0/Q w0^2];
        A=[1 w0/Q w0^2];
    otherwise
        warning(['Unsupported Filter Type: ' type]);
        return
end
% convert to digital filter
if G>=0
    [b,a]=bilinear(B,A,fs,f0);
else % invert transfer function
    [b,a]=bilinear(A,B,fs,f0);
end