function [association,txChannels,rxChannels,txPositions,rxPositions] = tgaxDropNodes(txs,rxs,scenario,NumChannels)
%tgaxDropNodes Creates random node drops for residential apartment block scenario
%
%   This is an example helper function.

%   Copyright 2019 The MathWorks, Inc.

% reference site is used as positional origin
referenceSite = txsite('Name','referenceSite','AntennaHeight',0); 

numTx = prod(scenario.BuildingLayout);
numRx = scenario.NumRxPerRoom*numTx; % for now

dx = (0:scenario.BuildingLayout(1)-1)*scenario.RoomSize(1);
dy = (0:scenario.BuildingLayout(2)-1)*scenario.RoomSize(2);
dz = (0:scenario.BuildingLayout(3)-1)*scenario.RoomSize(3);

[x,y,z] = meshgrid(dx,dy,dz);

x0 = scenario.RoomSize(1)*rand(numTx,1);
y0 = scenario.RoomSize(2)*rand(numTx,1);
z0 = 1.5; % note we don't adjust z height

txPositions = [x(:) + x0,y(:) + y0,z(:) + z0];

x = repmat(x(:),[scenario.NumRxPerRoom,1]); 
y = repmat(y(:),[scenario.NumRxPerRoom,1]); 
z = repmat(z(:),[scenario.NumRxPerRoom,1]);
x1 = scenario.RoomSize(1)*rand(numRx,1);
y1 = scenario.RoomSize(2)*rand(numRx,1);
z1 = 1.5; % note we don't adjust z height
rxPositions = [x(:) + x1,y(:) + y1,z(:) + z1];

association = repmat(diag(true(numTx,1)),[1,scenario.NumRxPerRoom]);
pos2geo(txs,referenceSite,txPositions); % Update txsites
pos2geo(rxs,referenceSite,rxPositions); % Update rxsites

% Randomly assign non-overlapping channel for transmitters
txChannels = randi([1 min(NumChannels,numTx)],numTx,1);

% Replicate non-overlapping channels for receivers
rxChannels = repmat(txChannels,[scenario.NumRxPerRoom,1]);

end

function pos2geo(sites,referenceSite,pos) 
% For each site (txsite/rxsites) update Latitude/Longitude/AntennaHeight
% given Cartesian position pos = [x,y,z] relative to a referenceSite

    x = pos(:,1);
    y = pos(:,2);
    z = pos(:,3);

    [th,r] = cart2pol(x,y); % convert to polar coordinates
    th = rad2deg(th); % convert to degrees
    
    [lat,lon] = location(referenceSite,r,th);
    for idx = 1:length(sites)
        sites(idx).Latitude = lat(idx);
        sites(idx).Longitude = lon(idx);
        sites(idx).AntennaHeight = z(idx); % use AntennaHeight as 'z'-position
    end
end
