function subst2aa = substPairs2aa(substPairs, aa);
% substPairs2aa is used to poole the substitution matrix into 
% two aa-categories like to-Alanin vs. from-Alanin
% Program by Steinar Thorvaldsen, steinart@math.uit.no, Dec 2006. 
% Ref.: http://www.math.uit.no/bi/deltaprot/
% Last changes 22. Dec 2006.

% Input:
% substPairs: array containing the number of each aa substitution.
% aa: the number 1-20(21) of the aa to pool (x->aa) 
% Output:
% subst2aa:  1x2 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:
% subst2A = substPairs2aa(substPairs, 1);

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

[M,N,P] = size (substPairs);
if (M ~= 20 & M ~= 21) | (N ~= 20 & N ~= 21)
    error('substPairs2aa: Substitution matrix must be of size 20x20 or 21x21');
end
aa = round(aa);
if (aa < 1) || (aa >21)
    error('substPairs2aa:Unknownaminoacid', ...
          'This ''aa'' parameter must be from 1 to 21.');  
end
if (aa == 21 & M ~= 21) | (aa == 21 & N ~= 21)
    error('substPairs2aa: Substitution matrix must be of size 21x21 to contain gaps');
end

subst2aa=zeros(1,2,P);
for p=1:P
    %removing diagonal elements (non-substitutions):   
    sP=substPairs(:,:,p)-diag(diag(substPairs(:,:,p)));
    subst2aa(1,1,p)=sum(sP(aa,:)); %subst aa->x
    subst2aa(1,2,p)=sum(sP(:,aa)); %subst x->aa
    %subst2aa(1,2,p)=sum(sum(sP(:,:)))-subst2aa(1,1,p); %subst x->not-aa
end
