function IIR_cof_gen(name, b, a, type)
% IIR_cof_gen(name, coeff, type)
%
% Creates filter coefficients in a .cof file 
% name must be a character string, i.e. 'myfile'
% b codes B(z) and a codes A(z), where H(z)=B(z)/A(z)
% type must either be 'fixed' or 'float'
% fixed point implementations will be scaled

% Do H inifinity scaling so that the maximum frequency component
% has magnitude one.
Hinf=max(abs(freqz(b,a)));

[H,G]=tf2sos(b./Hinf,a);

if (type == 'fixed')
    H=round(2^15.*H); % Scale by 2^15 and round to nearest integer
    G=round(2^15*G);
end

% if (type == 'float'), dont' scale


[Ns col]=size(H);                       % Find number of stages, Ns

                                        % Response is length N+1
s=[name '.cof'];
fid = fopen(s,'w');		                % Open (or create) file

s=['// IIR Filter ' name '.cof \n\n'];
fprintf(fid,s);                         % Label file


s=['#define Ns ' num2str(Ns) '\n\n'];
fprintf(fid,s);                         % Define N where N is the filter order

% second-order section numerators

if (type == 'fixed')
    s=['int G=' num2str(G) ';\n\n'];
    fprintf(fid,s);                         % Define Ns
    s=['int b[Ns][2]=\n{\n'];
    fprintf(fid,s);                     % Print "short b[Ns][3]={" 
                                        % where Ns is the number of stages
end

if (type == 'float')
    s=['float G=' num2str(G) ';\n\n'];
    fprintf(fid,s);                         % Define Ns
    s=['float b[Ns][2]=\n{\n'];
    fprintf(fid,s);                     % Print "float b[Ns][3]={"
                                        % where Ns is the number of stages
end

for i=1:Ns
    fprintf(fid,'{%d, ', H(i,2));       % Print b[Ns][1]
    fprintf(fid,'%d},\n', H(i,3));      % Print b[Ns][2]
end

fprintf(fid,'};\n\n');                  % Print closing bracket

% second-order section denominators

if (type == 'fixed')
    s=['int a[Ns][2]=\n{\n'];
    fprintf(fid,s);                     % Print "short a[Ns][2]={"
                                        % where Ns is the number of stages
end

if (type == 'float')
    s=['float a[Ns][2]=\n{\n'];
    fprintf(fid,s);                     % Print "float a[Ns][2]={" 
                                        % where Ns is the number of stages
end

for i=1:Ns
    fprintf(fid,'{%d, ', H(i,5));       % Print a[Ns][1]
    fprintf(fid,'%d},\n', H(i,6));      % Print a[Ns][2]
end

fprintf(fid,'};\n');                    % Print closing bracket

fclose(fid);						    % Close file
