function [affinity] = CalcPHsAffinityByAttributes(data, attData, last_known_node, addMissingAtt, threshold, add2level)
    % sigal 29.10.13 
    % based on CalcAttributesAffinity_S5

    % sigal 19.2.14 - choose between attribute from direct Neighbor (add2level == 0)
    % or NeighborNeighbors (add2level == 1)
    if nargin < 6
        add2level = 0;
    end
    
    n = size(data,1);
    numAtt = size(attData,2);

    firstPH = last_known_node+1;
    numPHs = size(data,1) - firstPH +1;

    if firstPH > n
        LogMsg(sprintf('*** ERROR: CalcPHsAffinityByAttributes firstPH %d >size %d.',firstPH, n));
        return
    end
    
    
    if addMissingAtt > 0 && last_known_node < n
        attData = AddMissingNodesAttrFromNeighborsNeighbors(data, attData, last_known_node, addMissingAtt, add2level);
    end
    
    attData = attData(firstPH:end,:);
    
    count = sum(attData,2);
    nnz_n = nnz(count);
    nnz_p = 100*nnz_n/numPHs;
    LogMsg(sprintf('PHsAttAffinity count  (%d, %.3f) - nnz=%d, %7.5f%%',numAtt,threshold,nnz_n, nnz_p));

    % full calculation  
    common = attData*attData';
    affinity = zeros(numPHs,numPHs);
    for i=1:numPHs
        for j=1:numPHs
            val = common(i,j);
            total = count(i)+count(j)-val;
            if total > 0 && val/total > threshold
               affinity(i,j) = val/total;
            end
        end
    end

    nnz_n = nnz(affinity);
    nnz_p = 100*nnz_n/(numPHs*numPHs);
    LogMsg(sprintf('PHsAttAffinity totalC (%d, %.3f) - nnz=%d, %7.5f%%',numAtt,threshold,nnz_n,nnz_p));

    clear('common');
    clear('count');
    
end %function
