%==============================================================================
%    rand_control.m
%    Copyright (C) 2007  Amoolya H. Singh, singh@embl.de
%
%    This program is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    This program is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this program.  If not, see <http://www.gnu.org/licenses/>.
%===============================================================================
function [avg, stdev, pval] = rand_control(n, X, obs)
%------------------------------------------------------------------------------
%
% [avg, stdev, pval] = rand_control(n, X, obs) continuously draws
% samples from source X until either (1) a threshold number of samples
% (currently set to 1e+5) have been drawn, or (2) a sample is drawn
% whose value is greater than a given observation
%
% Input: 
%   n, number of rows (genes) of X to draw per sample
%   X, data matrix from which to draw rows (genes)
%   obs, threshold value determining when to stop sampling
% Output:
%   avg, average of all samples drawn
%   std, standard deviation of all samples drawn
%   pval, 1/actual number of samples drawn
%
%------------------------------------------------------------------------------

rand('state',sum(100*clock));

A = [];
count = 0; 
signif = 1e+5;

while (1)
  ind = ceil(rand(n,1)*size(X,1));
  Y = X(ind,:);
  m = mean(eudist(X(ind,:)));
  if (m < obs || count == signif)
    ntrials = count;
    A = [A; m];
    break
  else
    count = count + 1;
    A = [A; m];
  end
end

avg = mean(A);
stdev = std(A);

pval = 1/ntrials;
