function BR_KB2GD(KB,fname)
%

num_clauses = length(KB);
vars = BR_vars(KB,[]);
num_vars = max(vars);

file_name = [fname,'.m'];
fd = fopen(file_name,'w');

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

% Create symolic vector
fprintf(fd,'syms');
for v = 1:num_vars
    fprintf(fd,' x%s',num2str(v));
end
fprintf(fd,' real\n\n');

% Create actual vector
fprintf(fd,'x = [');
for v = 1:num_vars-1
    fprintf(fd,'x%s;',num2str(v));
end
fprintf(fd,'x%s];\n\n',num2str(num_vars));

% Create function
fprintf(fd,'f = ');
S_full = [];
for c = 1:num_clauses-1
    s = BR_sentence2formula(KB(c).clauses,KB(c).prob);
    s = ['(',s,')^2 + '];
    S_full = [S_full,s];
end
s = BR_sentence2formula(KB(num_clauses).clauses,KB(num_clauses).prob);
s = ['(',s,')^2;'];
S_full = [S_full,s];
fprintf(fd,'%s\n\n',S_full);

% Create gradient
fprintf(fd,'gradf = jacobian(f,x).'';\n');

% Create Hessian
fprintf(fd,'hessf = jacobian(gradf,x);\n');

% Creare callable function
fprintf(fd,'fh = matlabFunction(f,gradf,hessf,''vars'',{x});\n\n');

% Set up options
fprintf(fd,'options = optimoptions(''fminunc'',...\n');
fprintf(fd,'''FunctionTolerance'',10^(-10),...\n');
fprintf(fd,'''SpecifyObjectiveGradient'',true,...\n');
fprintf(fd,'''HessianFcn'',''objective'',...\n');
fprintf(fd,'''Algorithm'',''trust-region'',...\n');
fprintf(fd,'''Display'',''off'',...\n');
%fprintf(fd,'''Display'',''iter'',...\n');
fprintf(fd,'''OutputFcn'',@BR_outfun);\n\n');

% Clear persistent variables in BR_outfun
fprintf(fd,'clear BR_outfun\n\n');

% Call fminunc
fprintf(fd,'[xfinal,fval,exitflag,output] = fminunc(fh,x0,options);\n');
fclose(fd);
