function [] = aaFreqPlot(aaFq, aaStd1, aaOrder);
% aaFreqPlot is used to plot the frequences of amino acids
% Program by Steinar Thorvaldsen, april 2004. Last changes 22. Sept 2005.

% Use:      
%           aaFreqPlot(aaFreq, aaStd1, 3)
% Input
% aaFq:    matrix(Number of pop x aa x level)containing the aa freq
% aaStd1:  standard deviation of group 1 (the baseline group)
% aaOrder: plot order of the different amino acids:
%           1:standard
%           2:classified (charged, polar, hydrophobic)
%           3:sorted by frequences


% The function is made flexible conserning input parameters:
if nargin < 3
    aaOrder=1; % standard
end

% Reconstructing the Maximal dimension of the data:
[Mpop,Maa,Mlayer] = size(aaFq);
% The standard order of amino acids:
aa_letter=char('A','R','N','D','C','Q','E','G','H','I','L','K','M','F','P','S','T','W','Y','V');
aaNr=[1:20]; %standard order

% An alternative classification:
aaNrClass=[4 7 12 2 9 16 17 19 5 3 6 18 1 20 14 15 13 10 11 8];
if aaOrder == 2     
    aaNr=aaNrClass; %order based on grouping (charged, polar, hydrophobic)       
end

% Each layer is plotted separately:
for layer=1:Mlayer
    if aaOrder == 3
        % To sort the frequences in descending order:
        [aa_freq_group1_sorted, aaNr] = sort(aaFq(1,:,layer)); %aaNr takes care of the sorting
        aaNr = fliplr(aaNr); % just changing order
    end
    figure
    ymax=14;
    max_percent=ceil(max(max(aaFq(Mpop,:,layer)))); %adjusting y-axes
    if max_percent>12 ymax=max_percent+2; end
    %plot (1:20, aa_freq_group1_sorted, '-b','LineWidth',3)
    title(['Variation in composition of amino acids, layer ', num2str(layer)]);
    axis ([0 21 0 ymax]);
    hold on
    %errorbar (1:20, aa_freq_group1_sorted, aa_std_group1,'-b','LineWidth',1)
    errorbar (1:20, aaFq(1,aaNr,layer), aaStd1(aaNr,layer),'-sb','LineWidth',1)
    plot (1:20, aaFq(2:Mpop,aaNr,layer),'LineWidth',1)
    set(gca,'XTick',1:1:20);
    set(gca,'XTickLabel',{aa_letter(aaNr)}); %labeling plot in selected order of the aa
    hold off;
end %layer loop
