function [ S, B ] = asso_vectorized( C, k, tau, w_plus, w_minus )
%ASSO implements Mietine's ASSO algorithm for the Boolean matrix decomposition
% vectorized implementation of pseudocode
% return Boolean matrices S and B for which C \aproxeq S \circ B

% k represents the number of factors
% tau \in [0, 1], ideal 0.9
% w_plus, w_minus \in R, ideal w_plus = w_minus = 1


[m, n] = size(C);
S = logical([]); B = logical([]);
covered = false(m,n);
A = false(n,n); % nutna uprava pro vektorizaci
zap = false(m,n);
a = logical([]);
b = logical([]);

% association matrix A, vectorized
for i=1:n
    A(i,:) = ((sum(repmat(C(:,i),[1 n]).*C))/sum(C(:,i))) >= tau;
end

% select k basis vectors
for l=1:k
    display(l);
    best_cover = -Inf;
    best_rowcount = false(m,1);
    
     % for each row of A
    for i=1:size(A,1)        
        cover = 0;
        rowcount = zeros(m,1);
        row = A(i,:);        
        
        % compare with original matrix
        for j=1:m 
            pom = bitand(~zap(j,:),row);
            rowcount(j) = sum(bitand(C(j,:), row)) - sum(bitand(~C(j,:), pom));
              
            if rowcount(j)>0
                cover = cover + rowcount(j); 
            end
        end
        
        if cover > best_cover
            best_cover = cover;
            best = i;
            best_rowcount = (rowcount > 0); 
        end
    end
    
    % the best result
    B = [B; A(best,:)];
    S = [S, best_rowcount];
    
    % already covered part, vectorized
    covered(best_rowcount>0, A(best,:)) = 0;
    zap(best_rowcount>0, A(best,:)) = 1;
    
    % remove selected row of A
    A(best,:) = [];
end

end
