function [ affinity ] = CalculateAffinityByAdamicAdar_Sparse( data, actual_graph_size, num_missing_nodes, num_attr_nodes, attWeight, connectPlaceholdersToNeighbors, addMissingAtt)
%UNTITLED2 adamic/adar(i,j) = sum( 1 / log(num_neighbors(k) | k is a
%neighbor of both i and j
%   Detailed explanation goes here

fprintf('CalculateAffinityByAdamicAdar_Sparse: NNZ(data) = %d\n', nnz(data));
%n = size(data,1);
%diag_indices = 1:n+1:n*n;
%data(diag_indices) = 1; %we consider each node as a neighbor of itself to obtain higher connectivity in the affinity matrix - i.e. each node will have a positive affinity to all its neighbors
if connectPlaceholdersToNeighbors > 0
      data = ConnectMissingNodesToNeighborsNeighbors( data, actual_graph_size, num_missing_nodes, num_attr_nodes, addMissingAtt );
end
affinity = zeros(size(data,1), size(data,2));

% Sigal 5.3.13: normalizeWeight
% make sure that ratio att/link is same w/1-w
if attWeight < 1 && attWeight >= 0
    normalizeWeight = attWeight/(1-attWeight);
else
    normalizeWeight = 1;
end

for k = 1 : size(data,1)
    %find all the neighbors of k
    neighbors_k_vec = data(k,:);
    neighbors_k_vec(k) = 1;%we consider each node as a neighbor of itself to obtain higher connectivity in the affinity matrix - i.e. each node will have a positive affinity to all its neighbors
    neighbors_k = find(neighbors_k_vec);
    num_neighbors_k = size(neighbors_k, 2);
    
    %sigal - 17.12.12 - find # social neighbors of k
    %sigal - update 5.3.13
    if num_attr_nodes>0
        neighbors_k_vec(1:num_attr_nodes)=0;
        neighbors_k_vec(k) = 1;
        neighbors_k_social = find(neighbors_k_vec);
        num_neighbors_k_social = size(neighbors_k_social, 2);
    else
        num_neighbors_k_social = num_neighbors_k;
    end
        
    
    if num_neighbors_k > 1
        if k>num_attr_nodes
            w = 1;
        else
            w = normalizeWeight;
        end
        inv_log_num_neighbors_k = w / log(num_neighbors_k);
        inv_log_num_neighbors_k_social = w / log(num_neighbors_k_social);
        for i  = neighbors_k
            for j = neighbors_k
                 if i>num_attr_nodes && j>num_attr_nodes
                    affinity(i,j) = affinity(i,j) + inv_log_num_neighbors_k_social;
                    affinity(j,i) = affinity(i,j);
%                 elseif i<=num_attr_nodes && j<=num_attr_nodes
%                     %skip
                 elseif k>num_attr_nodes
%                 else
                    affinity(i,j) = affinity(i,j) + inv_log_num_neighbors_k;
                    affinity(j,i) = affinity(i,j);
                end
            end
        end
    end
end

affinity = sparse(affinity);

% n = size(affinity,1);
% whos
% affinity(1:n+1:n*n) =  max(max(affinity)); %set diagonals

%normalize the matrix
affinity = affinity ./ max(max(affinity));

end

