function go_dotplot(go_conn, go_groups, apc_st4svm_ago, go_acp, fig_type, varargin)

% go_dotplot(go_conn, go_groups, apc_st4svm_ago, go_acp, 5,'goid_selection', unique([go_all(:).GOid]) )

verbose = 0;
alph_sort = 1;
ago_tresh = 90;
% p_markersize =20;
p_markersize =10;
group_number = 1;
group_name = [];
filename = [];
go_selection = [];
jac_tresh = 0.6;
no_ancestors = 0;

if ~isempty(varargin)
    i = 1;
    while i <= length(varargin),
        switch(varargin{i}),
            case 'group_number'
                i=i+1;
                group_number = varargin{i};
            case 'group_name'
                i=i+1;
                group_name = varargin{i};
                group_number = 0;
            case 'file'
                i=i+1;
                filename = varargin{i};
            case 'goid_selection'
                i=i+1;
                go_selection = varargin{i};
            case 'jaccard'
                i=i+1;
                jac_tresh = varargin{i};
            case 'verbose'
                verbose = 1;
            case 'no_ancestors'
                no_ancestors = 1;
            case 'sort'
                alph_sort = 1;
            otherwise
                error('Argument %s not known', varargin{i});
        end
        i = i+1;
    end
end

clus_no = size(apc_st4svm_ago,2);


if fig_type == 5,
    % Association study between go_terms in clusters, 
    % uses Matlab GraphViz to create figure 
    
    for i=1:length(go_acp),
        go_acp{i,3} = sscanf(go_acp{i,1}, 'GO:%d');
    end
    
    if ~isempty(go_selection),
        [C, V] = intersect([go_acp{:,3}], go_selection);
        go_acp_sel = {};
        for i=1:length(V), 
            go_acp_sel{i,1} = go_acp{V(i), 1};
            go_acp_sel{i,2} = go_acp{V(i), 2}; 
            go_acp_sel{i,3} = go_acp{V(i), 3}; 
        end    
    else
        go_acp_sel = go_acp;
    end
    
    apc_st4svm_agob = apc_st4svm_ago > ago_tresh;
    V = find(sum(apc_st4svm_agob,2) > 2);
    apc_st4svm_agos = apc_st4svm_agob(V,:);
    for i=1:length(V),
        go_acp_sel{i,1} = go_acp{V(i), 1};
        go_acp_sel{i,2} = go_acp{V(i), 2};
        go_acp_sel{i,3} = go_acp{V(i), 3};
    end
    
    CC = squareform(pdist(apc_st4svm_agos, 'jaccard'));
    [R,C] = find(CC < jac_tresh);
    % figure; plot(R, C, 'rx')

    rel_print = 'graph';
    
    switch (rel_print) 
        case 'print'
            for i=1:length(R);
                if R(i) <= C(i), continue; end;
                if no_ancestors == 1,
                    go_grc = pg_query(go_conn, 0, my_GO('ancestors_from_id'), go_acp_sel{R(i),1});
                    [go_grcm] = intersect(go_acp_sel{C(i),1}, {go_grc{:,1}});
                    if ~isempty(go_grcm), continue; end
                end
                fprintf('%s - %s\n', go_acp_sel{R(i),2}, go_acp_sel{C(i),2});
            end
    
        case 'plot'
            figure; plot(R, C, 'rx');
            
        case 'graph'
            N=size(apc_st4svm_agos, 1);
            s = zeros(N*N-N,3);
            j=1;
            for i=1:N
                for k=[1:i-1,i+1:N]
                    s(j,1)=i; s(j,2)=k; s(j,3)=-CC(i,k);
                    j=j+1;
                end;
            end
            idx =apcluster(s, median(s(:,3)));
            uidx = unique(idx);
            
            apc_ctr = zeros(length(uidx), size(apc_st4svm_agos, 2));
            for i=1:length(uidx),
                memb = find(idx == uidx(i));
                apc_ctr(i, :) = sum(apc_st4svm_agos(memb, :)) > 0;
            end
            
            ctr = {go_acp{V(uidx), 2}};
            %ctr = {go_acp_sel{uidx, 2}};
            
            apc_jac = squareform(pdist(apc_ctr, 'jaccard'));
            ctr_dist = apc_jac;
            ctr_dist = abs( 1-ctr_dist);
            ctr_dist = (ctr_dist > 0.3) .* ctr_dist;
            ctr_dist = tril(ctr_dist);
            bgraph = biograph(ctr_dist, ctr, 'LayoutType','hierarchical', 'ShowArrows', 'off');
            view (bgraph)
    end

    return;
    
end



go_grago = zeros(length(go_groups), size(apc_st4svm_ago,1));
for i=1:length({go_acp{:,1}})
    go_grc = pg_query(go_conn, 0, my_GO('ancestors_from_id'), go_acp{i,1});
    [go_grcm, go_grci] = intersect(go_groups, {go_grc{:,1}});
    if ~isempty(go_grci), go_grago(go_grci, i) = 1; end
end
%
go_grc = [];
go_grcm = zeros(length(go_groups), 1);
for i=1:length(go_groups),
    if sum(go_grago(i,:)) ~= 0,
        go_grci = find(go_grago(i,:) == 1);
        if alph_sort == 1,
            go_acp_cat = {go_acp{go_grci,2}};
            [go_acp_cats, go_acp_catidx] = sort(go_acp_cat);
            go_grci = go_grci(go_acp_catidx);
        end
        go_grc = [ go_grc, go_grci ];
    end
    go_grcm(i) = length(go_grc);
end

go_grstat = zeros(size(apc_st4svm_ago,2), length(find(sum(go_grago, 2) ~= 0)));
go_grsize = zeros(length(find(sum(go_grago, 2) ~= 0)),1);
go_grterm = {};

V=[0; unique(go_grcm)]; j=1;
for i=find(sum(go_grago, 2) ~= 0)',
    go_grstat(:,j) = sum(apc_st4svm_ago(go_grc(V(j)+1:V(j+1)),:) > 90);
    go_grsize(j) = V(j+1) - V(j);
    go_grterm{j,1} = go_groups{i};
    U=pg_query(go_conn, 0, my_GO('term_from_acc'), go_groups{i});
    go_grterm{j,2} = U{1};
    j=j+1;
end

go_grcmu = unique(go_grcm);
if go_grcmu(1) == 0, go_grcmu = go_grcmu(2:end); end

if fig_type < 4,
    figure; hold on
end

if fig_type == 1,
    % Raw plot

    for i=1:2:length(go_grcmu)-1,
        rectangle('Position',[0, go_grcmu(i), 40, go_grcmu(i+1)-go_grcmu(i)], 'FaceColor', [0.8, 0.8, 0.8], 'EdgeColor', 'none', 'EraseMode', 'xor');
    end
    for i=1:clus_no,
        U=find(apc_st4svm_ago(go_grc,i) > ago_tresh);
        plot(repmat(i, [length(U), 1]), U, '.',  'MarkerSize', p_markersize);
    end
    % calculate the middle between divisions label them ticks/terms
    V=[0; unique(go_grcm)];
    U=[];
    for i=1:length(V)-1, U=[U,(V(i) + V(i+1)) / 2]; end
    set(gca,'XGrid', 'on')
    set(gca,'XTick',[1:39])
    set(gca,'YTick',U)
    set(gca,'YTickLabel',{go_grterm{:,2}})
    set(gca,'TickDir','out')
    set(gca,'FontSize', 8)

elseif fig_type == 2,
    % Figure categorized by go_groups
    % (Figure from paper)
    
    
    tinc = 50;
    
    tinc_c = tinc;
    for i=1:length(go_grcmu)-1,
        text(20, go_grcmu(i) + tinc_c, go_grterm{i,2}, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'top'); 
        
        if mod(i,2) ~= 0, 
            rectangle('Position',[0, go_grcmu(i)+tinc_c, 40, go_grcmu(i+1)-go_grcmu(i)+tinc], 'FaceColor', [0.8, 0.8, 0.8], 'EdgeColor', 'none', 'EraseMode', 'xor');
        end
        tinc_c = tinc_c + tinc;
    end
    text(20, go_grcmu(i+1) + tinc_c, go_grterm{i+1,2}, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'top'); 

    for i=1:clus_no,
        Ur=find(apc_st4svm_ago(go_grc,i) > ago_tresh);
        U = Ur;
        
        for j=1:length(go_grcmu)-1,
            V=find(Ur > go_grcmu(j));
            U(V) = U(V) + tinc;
        end
        
        plot(repmat(i, [length(U), 1]), U, '.',  'MarkerSize', p_markersize);
    end
    % calculate the middle between divisions label them ticks/terms
    V=[0; unique(go_grcm)];
    U=[];
    for i=1:length(V)-1, U=[U,(V(i) + V(i+1)) / 2]; end
    set(gca,'XGrid', 'on')
    set(gca,'XTick',[1:39])
    set(gca,'YTick',[])
    set(gca,'TickDir','out')
    %set(gca,'FontSize', 8)

elseif fig_type == 3,
    % Figure categorized by go_groups
    % Each go_group only with big yes/no rectangular box
    
    tinc = 1;
    
    tinc_c = tinc;
    ago_tresh = 0;
    
    apc_st4svm_ago_sel = apc_st4svm_ago(go_grc,:);
    ago_bin = zeros(length(go_grcmu), 39);
    ago_bin(1,:) = sum(apc_st4svm_ago_sel(1:go_grcmu(1)-1,:) > ago_tresh,1) > 0;
    for i=2:length(go_grcmu)
        ago_bin(i,:) = sum(apc_st4svm_ago_sel(go_grcmu(i-1):go_grcmu(i)-1,:) > ago_tresh,1) > 0;
    end
    
    for i=1:length(go_grcmu)-1,
        text(20, i + tinc_c, go_grterm{i,2}, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'top'); 
        
        if mod(i,2) ~= 0, 
            rectangle('Position',[0, i+tinc_c, 40, 1+tinc], 'FaceColor', [0.8, 0.8, 0.8], 'EdgeColor', 'none', 'EraseMode', 'xor');
        end
        tinc_c = tinc_c + tinc;
    end
    text(20, i+1 + tinc_c, go_grterm{i+1,2}, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'top'); 

    for i=1:clus_no,
        Ur=find(ago_bin(:,i) > 0);
        U = Ur;
        
        for j=1:length(go_grcmu)-1,
            V=find(Ur > j);
            U(V) = U(V) + tinc;
        end
        
        plot(repmat(i, [length(U), 1]), U - 0.5, 's',  'MarkerEdgeColor','b', 'MarkerFaceColor', 'b', 'MarkerSize', 15);
    end
    set(gca,'XGrid', 'on')
    set(gca,'XTick',[1:39])
    set(gca,'YTick',[])
    set(gca,'TickDir','out')
    %set(gca,'FontSize', 8)

elseif fig_type == 4,
    % Print the GO contents of each cluster, sorted by go_groups
    % either to .csv or to screen
    
    
    group_inp = group_number;
    
    if group_inp == 0,
        group_inp = strmatch(group_name, {go_grterm{:,2}});
        if isempty(group_number),
            error('No group with the name %s', group_name);
        end
    elseif group_inp < 0,
        % do all groups if < 0
        group_inp = 1:length(go_grcmu);
    end
    
    
    file_csv = 0;
    if ~isempty(filename),
        fid = fopen(filename, 'w');
        if ~isempty(regexp(filename, '\.csv$'))
            file_csv = 1;
            fprintf(fid, '"cluster","parent_goid","parent_goterm","goid","goterm"\n');
        end
    else
        fid = 1;
    end
    
    for group_number = group_inp, 
        if group_number == 1,
            go_grc_s = 1;
        else
            go_grc_s = go_grcmu(group_number-1) + 1;
        end
        if group_number > length(go_grcmu),
            go_grc_e = length(go_grc);
        else
            go_grc_e = go_grcmu(group_number);
        end
        
        if file_csv == 0,
            fprintf(fid, '%s %s\n\n', go_grterm{group_number,1}, go_grterm{group_number,2});
            for i=1:clus_no,
                U=find(apc_st4svm_ago(go_grc(go_grc_s:go_grc_e),i) > ago_tresh);
                fprintf(fid, 'Cluster %d\n', i);
                % fprintf(fid, '%s %s\n', go_acp{go_grc(go_grc_s-1+U),1}, go_acp{go_grc(go_grc_s-1+U),2})
                go_tid = {go_acp{go_grc(go_grc_s-1+U),1}};
                go_tn = {go_acp{go_grc(go_grc_s-1+U),2}};
                for j=1:length(go_tid),
                    fprintf(fid, '%s %s\n', go_tid{j}, go_tn{j});
                end
                fprintf(fid, '\n');
            end
        else
            for i=1:clus_no,
                U=find(apc_st4svm_ago(go_grc(go_grc_s:go_grc_e),i) > ago_tresh);
                % fprintf(fid, '%s %s\n', go_acp{go_grc(go_grc_s-1+U),1}, go_acp{go_grc(go_grc_s-1+U),2})
                go_tid = {go_acp{go_grc(go_grc_s-1+U),1}};
                go_tn = {go_acp{go_grc(go_grc_s-1+U),2}};
                for j=1:length(go_tid),
                    fprintf(fid, '%d,"%s","%s","%s","%s"\n', i, go_grterm{group_number,1}, go_grterm{group_number,2}, go_tid{j}, go_tn{j});
                end
            end
        end
    end

    if ~isempty(filename),
        fclose(fid);
    end

elseif fig_type == 6
    % Just print the Y axis of fig_type = 3 divided by categories
    
    for group_number = 1:length(go_grcmu), 
        if group_number == 1,
            go_grc_s = 1;
        else
            go_grc_s = go_grcmu(group_number-1) + 1;
        end
        if group_number > length(go_grcmu),
            go_grc_e = length(go_grc);
        else
            go_grc_e = go_grcmu(group_number);
        end
 
        
        fprintf('%s %s\n\n', go_grterm{group_number,1}, go_grterm{group_number,2});
        go_tid = {go_acp{go_grc(go_grc_s:go_grc_e),1}};
        go_tn = {go_acp{go_grc(go_grc_s:go_grc_e),2}};
        for j=1:length(go_tid),
            fprintf('%s %s\n', go_tid{j}, go_tn{j});
        end
        fprintf('\n');
        
    end
    
    
elseif fig_type == 7
    
    group_inp = 1:length(go_grcmu);
    for group_number = group_inp,
        if group_number == 1,
            go_grc_s = 1;
        else
            go_grc_s = go_grcmu(group_number-1) + 1;
        end
        if group_number > length(go_grcmu),
            go_grc_e = length(go_grc);
        else
            go_grc_e = go_grcmu(group_number);
        end
        
        fprintf('%s %s\n\n', go_grterm{group_number,1}, go_grterm{group_number,2});
        for i=1:clus_no, 
            for j=i+1:clus_no,
                go_dots = zeros(go_grc_e - go_grc_s, 2);
                U=find(apc_st4svm_ago(go_grc(go_grc_s:go_grc_e),i) > ago_tresh);
                go_dots(U,1) = 1;
                U=find(apc_st4svm_ago(go_grc(go_grc_s:go_grc_e),j) > ago_tresh);
                go_dots(U,2) = 1;
                [H, P, STATS] = fishertest(go_dots);
                if STATS.phi > 0.75, fprintf('%d x %d = %f\n', i, j, STATS.phi); end
            end; 
        end
        fprintf('\n');
    end
    
else
    
    error('Figure type %d not known', fig_type);
end
