function [P_cc,p_query] = BR_Nilsson_method(KB,query)
% BR_Nilsson_method - Nilsson's probabilistic logic method (max value)
% On input:
%     KB (KB struct): KB clauses
%     query (KB struct): query
% On output:
%     P_cc (kx1 vector): model probabilities
%     p_query (float): probability of query
% Call:
%     KB(1).clauses = [1];
%     KB(1).prob = 0.7;
%     KB(2).clauses = [-1,2];
%     KB(2).prob = 0.7;
%     query.clauses = [2];
%     query.prob = 0;
%     [P,pt] = BR_Nilsson_method(KB,thm);
% Author:
%     T. Henderson
%     UU
%     Summer 2018
%

p_query = 0;

num_sentences = length(KB);
vars = BR_vars(KB,query);
num_vars = length(vars);
num_cc = 2^num_vars;
query_sat = zeros(1,num_cc);
V = zeros(num_sentences+1,num_cc);
P_s = zeros(num_sentences+1,1);
V(end,:) = ones(1,num_cc);
P_s(end) = 1;

for s = 1:num_sentences
    P_s(s) = KB(s).prob;
    for cc = 0:num_cc-1
        bits = BR_int2bits(cc,num_vars);
        V(s,cc+1) = BR_sat(KB(s).clauses,bits);
        query_sat(cc+1) = BR_sat(query.clauses,bits);
    end
end

%P_cc = V\P_s;
P_cc = lsqlin(V,P_s,[],[],[],[],zeros(num_cc,1),ones(num_cc,1));
p_query = query_sat*P_cc;
