function OUT = rand_loc_wtd(X,M,Tot)

% RAND_LOC_WTD distributes random points in a series of polygons WEIGHTED
%              by a 'reference measure' like population.

% FUNCTIONS CALLED: pt_in_poly.m, polyform.m, rand_loc.m

% INPUTS: X = boundary file in format of 'polyform.m'
%         M = reference measure values for each polygon of X
%             (assumed to be in same order as polygons of X)
%         Tot = total number of points to be generated.

% OUTPUT: Loc = Nx2-vector of all point coordinates generated.
%         Num = Point fequencies in each polygon


% Generate sampling probabilites over polygons

s = 23311 ; % Random seed

out = zeros(1,2); % Place holders for rand_num output

k = length(M) ; % number of polygons

N = 50; % number of points to be generated

u = ones(1,k);

m = u*M ;

P = M/m ;

% Form cdf

F = zeros(k,1);

F(1) = P(1) ;

i = 2 ;

while i <= k
   
   F(i) = P(i) + F(i-1) ;
   
   i = i + 1;
   
end

% Construct Polygon Sample Numbers

Num = zeros(k,1) ;

i = 1 ;

while i <= N
   
   out = rand_num(s) ;
   
   x = out(1);
   
   s = out(2);
   
   j = 1 ;
   
   % Locate Polygon Interval containing x
   
   while j <= k
      
      if x <= F(j)
         
         Num(j) = Num(j) + 1 ;
         
         break
         
      end
      
      j = j + 1 ;
      
   end
   
   i = i + 1 ;
   
end

% Now sample random points

Z = polyform(X);

OUT = rand_loc(X,Z,Num) ;


