function [User Asso_User] = Neighbour(Sim, Num_Cell, K, path_loss_dB, BS,User,M,noise_dBm)

%%% -----------------------------------------------------------------------
%%% This function finds the nearest M neighbouring BS's for every user
%%% accoring to the pathloss and BS trasnmit power budget
%%% -----------------------------------------------------------------------
Total_BS = Sim.Num_BS;
%User = struct([]);
% Tx_Power = [P_max_Macro_dBm*ones(1,L_Macro) P_max_Pico_dBm*ones(1,L_Pico)];
% Tx_Power_Matrix = kron(Tx_Power,ones(Num_Cell,1));
Asso_User = zeros(M,Num_Cell,Total_BS);
%num of users claiming each BS as the strongest BS

per_BS_power_constraint_matrix = zeros(Num_Cell,Total_BS);
for c=1:Num_Cell
    for b = 1:Total_BS
        if b <= Sim.Num_Macro
            per_BS_power_constraint_matrix(c,b) = dB2dec(Sim.P_max_Macro_dBm);
        else
            per_BS_power_constraint_matrix(c,b) = dB2dec(Sim.P_max_Pico_dBm);
        end
    end
end



for iCell = 1:Num_Cell
    for k = 1:K
        
        path_loss = squeeze(path_loss_dB(:,:,iCell,k));
        Rcv_Power = dec2dB(per_BS_power_constraint_matrix) - path_loss;
        Rcv_Power_vec =reshape(Rcv_Power',[],1);
        
        %         sum_rcv_power = sum(dB2dec(Rcv_Power_vec));
        %         intf = sum_rcv_power - Rcv_Power_vec;
        %         intf_noist = intf + dB2de
        
        [~,SortedBS] = sort(Rcv_Power_vec,'descend');
       % User(iCell,k).NeighbourCluster = SortedBS(1:M); 
       %for data sharing scheme
        User(iCell,k).NeighbourCluster = 1:Num_Cell*Total_BS;
        User(iCell,k).ServingCluster = zeros(length(User(iCell,k).NeighbourCluster),2);
        
        for c = 1:length(User(iCell,k).NeighbourCluster)
            BS_idx = User(iCell,k).NeighbourCluster(c);
            User(iCell,k).ServingCluster(c,1) = ceil(BS_idx / Total_BS);
            User(iCell,k).ServingCluster(c,2) = BS_idx - (User(iCell,k).ServingCluster(c,1)-1)*Total_BS;
        end
        
%        User(iCell,k).data_sharing_BSs = User(iCell,k).ServingCluster; 

        User(iCell,k).data_sharing_BSs = [];
        
        for iBS = 1:size(User(iCell,k).data_sharing_BSs,1)
            Cell_idx = User(iCell,k).data_sharing_BSs(iBS,1);
            BS_idx = User(iCell,k).data_sharing_BSs(iBS,2);
            BS(Cell_idx,BS_idx).data_sharing_users = [BS(Cell_idx,BS_idx).data_sharing_users; [iCell k]];
        end
        
        
        
        for m = 1:M
            Cell_index = ceil(SortedBS(m)/Total_BS);
            BS_index = mod(SortedBS(m)-1,Total_BS)+1;
            User(iCell,k).Neighbour(m).Cell_BS = [Cell_index BS_index];
            
            Asso_User(m, Cell_index, BS_index) = Asso_User(m, Cell_index, BS_index) + 1;
            
        end
        
    end
end
