function aa = aaCount(S,level);
% aaCount is used to count the amino acids stored in the sequenses S.
% If nessesary the amino acid must be converted from a character to an 
% integer representation. Gaps are not counted.
% Program by Steinar Thorvaldsen, april 2004. Latest modified 20. april 2006.

% Input
% S: character or integer array containing the sequence from M genes
% level: vecor containing 2D or 3D information about the sequence
% Output
% aa: M x 20 x levels matrix with the aa countings from the M sequences.

% To determine the number of sequences, M:
[M,N] = size (S);
% The function is made flexible conserning input parameters:
if nargin < 2
    level=ones(N,1,'int8'); % no levels
    D3=1;
end

% Some alignments may have few (~3) levels (no gaps). May cause problems***:
global maxlevel;
if maxlevel >= 1 % ~isempty(whos('global','maxlevel'))
    D3=maxlevel; % the number of levels stay constant as defined in main program
else 
    D3=max(level);
end

if N > length(level)
   error('Sequences and level vector must be same length! Make alignment.')
end;
aa = zeros (M, 20, D3);

for n=1:N
    for m=1:M
        if ischar (S(m,n))
            aaNo = aa2int(S(m,n)); % Convert amino acid from a character to an integer representation
        else
            aaNo = S(m,n);
        end
        if aaNo >0 & aaNo <21
            aa(m,aaNo,level(n)) = aa(m,aaNo,level(n)) + 1;
        end
    end
end
