function eqns2odes(name, m, dxdt, Jx)
% call by running
% [dxdt Jx] = kron2eqns(m);
% eqns2odes(name, m, dxdt, Jx);

%% write the equations file
fid = fopen(sprintf('%s_eqns.m', name), 'w');

fprintf(fid, 'function dxdt = %s_eqns(t, x, p)\n\n', name);

fprintf(fid, '[');
for i = 1:m.nX
    fprintf(fid, '%s ', strrep(m.xNames{i}, ':', '_'));
end
fprintf(fid, '] = jdeal(x);\n\n');

fprintf(fid, '[');
for i = 1:m.nP
    fprintf(fid, '%s ', m.pNames{i});
end
fprintf(fid, '] = jdeal(p);\n\n');

fprintf(fid, 'dxdt = [\n');
for i = 1:m.nX
    fprintf(fid, '\t\t%s\n', dxdt{i});
end
fprintf(fid, '\t   ];');
% keyboard
% fprintf(fid, '[%s\t', name);

fclose(fid);

%% write the partial derivatives file
fid = fopen(sprintf('%s_jac.m', name), 'w');

fprintf(fid, 'function Jx = %s_jac(t, x, p)\n\n', name);
fprintf(fid, '[');
for i = 1:m.nX
    fprintf(fid, '%s ', strrep(m.xNames{i}, ':', '_'));
end
fprintf(fid, '] = jdeal(x);\n\n');

fprintf(fid, '[');
for i = 1:m.nP
    fprintf(fid, '%s ', m.pNames{i});
end
fprintf(fid, '] = jdeal(p);\n\n');

fprintf(fid, 'Jx = [\n');
for i = 1:m.nX
    fprintf(fid, '\t\t');
    for j = 1:m.nX
        fprintf(fid, '%s\t', Jx{i, j});
    end
    fprintf(fid, '\n');
end
fprintf(fid, '\t   ];');
% keyboard
% fprintf(fid, '[%s\t', name);

fclose(fid);

%% write the simulation script

fid = fopen(sprintf('%s_sim.m', name), 'w');

fprintf(fid, 'ic = [\n');

for i = 1:m.nX
    fprintf(fid, '\t\t%f\n', m.ic(i));
end
fprintf(fid, '\t  ];\n\n');

fprintf(fid, 'p = [\n');

for i = 1:m.nP
    fprintf(fid, '\t\t%f\n', m.p(i));
end
fprintf(fid, '\t  ];\n\n');

fprintf(fid, 'ode15s(@%s_eqns, [0 50], ic, odeset(''Jacobian'', @%s_jac), p);\n', name, name);

fclose(fid);