function sloc=randsample1d(R,N,M,rflag);
%
% function sloc=randsample1d(R,N,M,rflag);
%
% generate R>=2*M+1 randomly located samples with a uniform distribution
% ensuring that they are unique and within one period (1:N)
% where N is an integer multiple of 2*M+1.  Samples are 1-based.
%
% if rflag==0, uniformly distributed random locations
% if rflag==1, regularly spaced sample locations (ignores R)
% if rflag==2, constrained random sampling (locally uniform)
%

% DGL 15 April 2006
% revised DGL 22 Dec 2010 + add constrained random sampling

if (rflag==1) % set uniformly spaced locations
  sloc=floor([1:(2*M+1)]-1)*(N/(2*M+1))+1;
else          % irregular locations with no duplicates (disjoint)
  du=round(N/(2*M+1));
  if du<=1
    du=2;
  end
  
  it=floor(N*rand);
  if it==0
    it=1;
  end
  ir=1;
  sloc=it;

  while ir<R
    iflag=1;
    icnt=0;
    lmul=1;
    while iflag>0
      if rflag==2 % special constrained uniform distribution
	it=floor(lmul*2*du*(rand-0.5)+(ir-1)*du); % narrow possible sample locations
      else        % pure uniform distribution
	it=floor(N*rand);
      end
      if it<=0
	it=1;
      end
      if it>N
	it=N;
      end
      in=find(sloc==it);
      if isempty(in)
	sloc=[sloc it];
	ir=ir+1;
	iflag=0;
      else
	icnt=icnt+1;
      end
      if icnt>100    % helps ensure that disjoint locations can be generated
	lmul=lmul*2;
	icnt=0;
      end
    end
  end
  sloc=sort(sloc); % sort location order for convenience
end



