function [A_probs,S_probs] = BR_new_MC_partial(KB,A_probs0,a_set,...
    num_trials,thresh,step)
%
% [ap,Sp] = BR_new_MC_partial(KB5,ap,a_set,100000,0.001,0.0001);
%
%  actual   computed
%--------------------
%  0.700    0.700
%  0.571    0.572
%  0.475    0.476
%  0.368    0.369
%  0.186    0.188

THRESH = 0.01;
STEP = step;

vars = BR_vars(KB,[]);
len_KB = length(KB);
num_vars = length(vars);
samples= [];
A_probs = A_probs0;
probs = zeros(1,len_KB);
for s = 1:len_KB
    L_probs = A_probs;
    clause = KB(s).clauses;
    len_clause = length(clause);
    for l = 1:len_clause
        if clause(l)<0
            L_probs(abs(clause(l))) = 1 - A_probs(abs(clause(l)));
        end
    end
    S_probs(s) = BR_prob_or(clause,L_probs);
    probs(s) = KB(s).prob;
end

wb = waitbar(0,'New MC Partial');
t = 1;
variable_indexes = find(a_set==0);
if isempty(variable_indexes)
    close(wb);
    return
end
num_variable_indexes = length(variable_indexes);
while t<num_trials&norm(S_probs-probs)>thresh
    t = t + 1;
    waitbar(t/num_trials);
    t_probs = A_probs;
    var_index = randi(num_variable_indexes);
    index = variable_indexes(var_index);
    dir = sign(rand-t_probs(index));
    t_probs(index) = max(0,min(1,t_probs(index) + dir*STEP));
    for s = 1:len_KB
        L_probs = t_probs;
        clause = KB(s).clauses;
        len_clause = length(clause);
        for l = 1:len_clause
            if clause(l)<0
                L_probs(abs(clause(l))) = 1 - t_probs(abs(clause(l)));
            end
        end
        t_S_probs(s) = BR_prob_or(clause,L_probs);
    end
    dist_Sp = norm(t_S_probs-probs);
    if mod(t,100)==0
        [dist_Sp, max(abs(t_S_probs-probs))]
    end
    if dist_Sp<norm(S_probs-probs)
        A_probs = t_probs;
        S_probs = t_S_probs;
    end
end
close(wb);
tch = 0;
