function posteriors = BayesRule( value, liks, priors)
%function posteriors = BayesRule( value, liks, priors)
%Function that returns posterior probability of 3 or 5 given the value of features in an image (this is a vector of size [1 x n], and the likelihoods of the features, and priors of class 3 and 5
%Note that value will be [1 x n] (row vector) and liks will be [2 x 2^n] size and priors will be [1 x 2] column vector for our '3' vs '5' problem
%Assuming that the features will be 0.5/255.5.

%Check sizes of inputs
if size(value, 1) ~= 1
    fprintf('Error: value must be a column vector..Function will exit. Press any key to continue')
    pause;
    posteriors = [-1 -1];
    return;
end
n = size(value, 2);
%if likelihoods are not of size 2^n, exit
if (2^n)~=size(liks, 1)
    fprintf('Error: likelihoods must have 2^n values. Function will exit. Press any key to continue')
    pause;
    posteriors = [-1 -1];
    return;
end
%if likelihoods are not having 2 columns, exit
if size(liks, 2)~=2
    fprintf('Error: likelihoods must have 2 columns. Function will exit. Press any key to continue')
    pause;
    posteriors = [-1 -1];
    return;
end
%if priors is not having 2 columns, exit
if size(priors, 2)~=2
    fprintf('Error: priors must have 2 columns. Function will exit. Press any key to continue')
    pause;
    posteriors = [-1 -1];
    return;
end
%if priors is not having 1 rows, exit
if size(priors, 1)~=1
    fprintf('Error: priors must have 1 row. Function will exit. Press any key to continue')
    pause;
    posteriors = [-1 -1];
    return;
end

%All size checks have finished.
%Convert feature from 0.5/255.5 representation to binary string
binary_string='';
for feat_num=1:n
    %If feature is 0.5, add '0' to binary_string 
    if value(feat_num)==0.5
        binary_string = sprintf('%s%s', binary_string, '0');
    %else add a '1' to binary_string
    else
        binary_string = sprintf('%s%s', binary_string, '1');
    end
end
%We now have the binary_string that represents the features value
%Just as in likFromTraining, convert to decimal, add 1. This gives the bin from which to read likelihoods
feature_bin = bin2dec( binary_string);
feature_bin = feature_bin+1;
%Read likelihood of current feature for 3 and 5 from the likelihoods matrix, liks 
lik3 = liks( feature_bin, 1);
lik5 = liks( feature_bin, 2);

%Posteriors using Bayes formula
posteriors(1) = (lik3*priors(1))/((lik3*priors(1))+(lik5*priors(2)));
posteriors(2) = 1-posteriors(1);
    
