clear all;

syms x y alpha beta       % variables
syms a b c real

%define (example) symbolic expressions:
symExpr1 = 2*sin(alpha)^2 + (1+y)^(3/2) + (5/4)*(1+2*sin(alpha)^2)
                                % First C/C++ function to be generated

%example with vectorial symbolic variable:
symExpr21 = solve(sym('x^3 + a*x^2 + b*x + c')) %result 
% is a sybolic expression with 3 elements (the 3 solutions to the equation).
% The equations are pretty complicated and contains common (repeted)
% subexpressions.
symExpr22 = x + y + cos(alpha) % second expression (scalar) for the second
                                % C/C++ function to be generated         

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%% Generate C/C++ files from these expressions %%%%%%%%%%%%%%%%%

% A .cpp source file and a .h header file must be generated.
% All variables in C/C++ code are assumed to be part of a datastructure
% (d). 
% Each code line is stored as a string in a cell-array, cfun for .cpp file
% and hdecl for the header file.

tic
disp('Starting C++ code generation') 

clear cfun;
clear hdecl;

%.cpp:
cfun{1}='#include "conversionDemo.h" \n#include "toBeIncluded1.h" \n#include "toBeIncluded2.h" \n\n';  %files your code needs
cfun{2}=['// File generated on ' date ', Basile.Graf@epfl.ch \n\n\n'];

%.h:
hdecl{1}=['#ifndef CONVERSION_DEMO_H_DEF \n#define CONVERSION_DEMO_H_DEF \n \n']; %preprocessor constant, !!! MUST be a different name for each file you create !!!
hdecl{2}=['// File generated on ' date ', Basile.Graf@epfl.ch \n\n\n'];

%function for symExpr1:
varName = {'symExpr1'};
expr = {symExpr1};
[cfun, hdecl] = sym2c(varName, expr, 'cfunction1', cfun, hdecl);

%function for symExpr21 and symExpr22:
varName = {'symExpr21','symExpr22'};
expr = {symExpr21, symExpr22};
[cfun, hdecl] = sym2c(varName, expr, 'cfunction2', cfun, hdecl);


hdecl{length(hdecl)+1}=['#endif \n']; %#endif preprocessor line at end of .h

%write to .cpp:
fid = fopen('conversionDemo.cpp','wt');
for k = 1:length(cfun)
   fprintf(fid,cfun{k}); 
end
fclose(fid);

%write to .h
fid = fopen('conversionDemo.h','wt');
for k = 1:length(hdecl)
   fprintf(fid,hdecl{k}); 
end
fclose(fid);

toc
disp('C++ code generation finished') %be happy