 % MKL library for Simulink compilation demo
 %
 % [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
 
 echo on
 close_system('dotsim',0)
 !find . -not -name dotmex.c -not -name mklld.m | xargs rm -Rf

 %% ld script for MKL
 !echo "SEARCH_DIR ( $MKLROOT/lib/intel64 )" > mklld.LIB
 !echo "GROUP      ( libmkl_intel_lp64.a libmkl_intel_thread.a libmkl_core.a )" >> mklld.LIB
 !echo "INPUT      ( libiomp5.so )" >> mklld.LIB

 %% MEX-file
 % Add compiler option to avoid warning messages in mkl.h
 !mex CFLAGS="$CFLAGS -fPIC -Wno-extra-tokens" dotmex.c mklld.LIB
 dotmex([1 2],[3 4])

 %% S-function created using Legacy Code Tool
 s = legacy_code('initialize');
 s.HostLibFiles = { 'mklld.LIB' };
 s.SFunctionName = 'dotcsf';
 s.OutputFcnSpec = 'void vdMul(int16 size(u1,1), double u1[], double u2[], double y1[size(u1,1)])';
 legacy_code('sfcn_cmex_generate',s)
 legacy_code('compile',s)

 %% Simulink model using S-function
 legacy_code('slblock_generate',s,'dotsim')
 add_block('built-in/Constant','dotsim/u')
 add_line('dotsim','u/1','dotcsf/1')
 add_line('dotsim','u/1','dotcsf/2')
 add_block('built-in/Outport','dotsim/out')
 add_line('dotsim','dotcsf/1','out/1')
 set_param('dotsim','SolverType','Fixed-step','Solver','FixedStepDiscrete','FixedStep','1')

 %% Simulink model using S-function run in "Normal" mode
 set_param('dotsim','SimulationMode','normal')
 sim('dotsim')

 %% Simulink model using S-function run in "Accelerator" mode
 % For accelerator mode, source C-code is generated by TLC, and executable
 % code is build with an automatically built make file for which libraries
 % are specified by rtwmakecfg.m. So both TLC file and rtwmakecfg.m must be
 % generated.
 s.Options.useTlcWithAccel = true; % that's the default
 legacy_code('sfcn_tlc_generate',s)
 legacy_code('rtwmakecfg_generate',s)
 set_param('dotsim','SimulationMode','accelerator','AccelVerboseBuild','on')
 sim('dotsim')

 %% Code generation to run as standalone
 % Libraries are specified as "TargetLibFiles", which may be different from
 % libraries local to the host. As for accelerator mode, source C-code is
 % generated by TLC, and executable code is build with an automatically
 % built make file for which libraries are specified by rtwmakecfg.m. So
 % both TLC file and rtwmakecfg.m must be generated.
 s.TargetLibFiles = { 'mklld.LIB' };
 legacy_code('rtwmakecfg_generate',s)
 rtwbuild('dotsim')
 !./dotsim

 close_system('dotsim',0)
