function aaBin = aa2bin(aa, method);
% aa2bin is used to reduces the amino acid count matrix to 
% fewer categories based on selected grouping of related amino acids
% Program by Steinar Thorvaldsen, steinart@math.uit.no, Nov 2006. 
% Ref.: http://www.math.uit.no/bi/deltaprot/
% Last changes 21. Nov 2006.

% Input:
% aa: integer array containing the number of each aa.
% method: defining the new grouping of amino acids:
% 1:hydrophobic, 2:charged, 3:positive, 4:negative, 5:polar,
% 6:aromatic, 7:aliphatic, 8:tiny, 9:small, ...
% Output:
% aaBin:  matrix with the accumulated bin counts.
% The following mapping protocol is used:
% A R N D C Q E G H I  L  K  M  F  P  S  T  W  Y  V  - 
% 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
% where - are gaps.
% Use:
% aaCharged = aa2bin(aa, 2);

% The function is made flexible conserning input parameters:
if nargin < 2
    method=1;
end

[M,N,P] = size (aa);
if N ~= 20
    error('aa2bin: Matrix of amino acids counts must be of size Mx20');
end

method = round(method);
switch method
    case 1 % hydrophobic
        bin1=[1 8 10 11 13 14 15 18 20];
    case 2 % charged
        bin1=[2 4 7 9 12];
    case 3 % positive
        bin1=[2 12];
    case 4 % negative
        bin1=[4 7];
    case 5 % polar
        bin1=[3 5 6 9 16 17 18 19];
    case 6 % aromatic
        bin1=[9 14 18 19];
    case 7 % aliphatic
        bin1=[10 11 20];
    case 8 % tiny
        bin1=[1 8 16];
    case 9 % small
        bin1=[1 3 4 5 8 15 16 17 20];
    case 10 % pos or polar
        bin1=[2 3 5 6 9 12 16 17 18 19];
    case 11 % neg or polar
        bin1=[3 4 5 6 7 9 16 17 18 19];
    otherwise % No defined method
        error('aa2bin:UnknownMethod', ...
          'This ''method'' parameter is not known.');    
end
bin2=setdiff([1:N],bin1); %the rest of the amino acids

aaBin=zeros(M,2,P);
for p=1:P
  for m=1:M
    aaBin(m,1,p)=sum(aa(m,bin1,p),2); %sum in dimension 2
    aaBin(m,2,p)=sum(aa(m,bin2,p),2);
  end
end
