function BR_KB2F(KB,fname)
% BR_KB2F - convert KB to .m function file
% On input:
%     KB (KB struct): CNF KB
%     fname (string): root name of file
% On output:
%     N/A - side effect is creation of 2 files:
%       fname.m: has vector function for sentence probabilities
%       fnames.m: scalar output function (norm(F) from fname.m)
% Call:
%     BR_KB2F(KB,'IJ');
% Author:
%     T. Henderson
%     UU
%     Fall 2017
%

num_clauses = length(KB);

% fsolve function (vector output)
file_name = [fname,'.m'];

fd = fopen(file_name,'w');

fprintf(fd,'function F = %s(x)\n',fname);
fprintf(fd,'%%\n\n');

for c = 1:num_clauses
    F = BR_sentence2formula(KB(c).clauses,KB(c).prob);
    F = ['F(',num2str(c),') = ',F];
    fprintf(fd,'%s;\n',F);
end
fclose(fd);

% fmincon function (scalar - error output)
file_name = [fname,'s.m'];

fd = fopen(file_name,'w');

fprintf(fd,'function err = %s(x)\n',[fname,'s']);
fprintf(fd,'%%\n\n');

for c = 1:num_clauses
    F = BR_sentence2formula(KB(c).clauses,KB(c).prob);
    F = ['F(',num2str(c),') = ',F];
    fprintf(fd,'%s;\n',F);
end
fprintf(fd,'err = norm(F);\n');
fclose(fd);
