function [prob,q,tr] = BR_MC_query_P(KB,query,num_initial,near,...
    max_samples,P)
%

NUM_INITIAL = num_initial;
NEAR = near;

prob = 0;

%figure(1);
%clf
%hold on

m = length(KB);
p = zeros(m,1);
for c = 1:m
    p(c) = KB(c).prob;
end

vars = BR_vars(KB,[]);
n = length(vars);
query_clause = query(1).clauses;
samps = rand(NUM_INITIAL,n)<0.5;
true_counts = zeros(m,1);
true_query = 0;
q = zeros(m,1);
for s = 1:NUM_INITIAL
    for c = 1:m
        true_counts(c) = true_counts(c) + BR_sat(KB(c).clauses,samps(s,:));
    end
    true_query = true_query + BR_sat(query_clause,samps(s,:));
end
q = true_counts/NUM_INITIAL;
tr = q';
num_samples = NUM_INITIAL;
total_samps = num_samples;
count = 0;
while num_samples<max_samples
    total_samps = total_samps + 1;
    samp = BR_get_samp_P(P);
    num_samples = num_samples + 1;
    for c = 1:m
        true_counts(c) = true_counts(c)...
            + BR_sat(KB(c).clauses,samp);
    end
    true_query = true_query + BR_sat(query_clause,samp);
    q = true_counts/num_samples;
    q'
    tr = [tr;q'];
    %    plot(1,num_samples,'ro');
    %    plot(2,total_samps,'g*');
    %    drawnow
end
prob = true_query/num_samples;
tch = 0;
