function make(varargin)

ALL_PLUGINS = {
    'zx_brake', 'zx_strut', 'rack', 'mdi', 'zx_generic_brake_input', ...
    'zx_generic_steer_input','zx_generic_strut_osci_input', ...
    'zx_generic_strut_ramp_input', 'zx_IPGDriver', ...
    'zx_drive_from_file', 'zx_motor', 'zx_motor1', ...
    'edu_interface', 'zx_generic_tierod_failure', 'zxe7'};

if nargin > 1
    error('Unsupported number of arguments');
elseif nargin == 1
    if strcmp(varargin{1}, 'clean')
        make_clean;
        return;
    else
        if ~iscell(varargin{1})
            plugins = {varargin{1}};
        else
            plugins = varargin{1};
        end
    end
else
    plugins = ALL_PLUGINS;
end

% Unload any mex libraries from memory
evalin('base', 'clear mex')
base_dir = pwd;
mex src/sfun/sfun_trajectory_tracker.cpp -outdir src/sfun
mex src/sfun/sfun_drive_from_file.cpp -outdir src/sfun
run src/sfun/make_steering_conversions_wrapper


% Select the right template makefile based on OS
if ispc
    template_make_file = 'CarMaker_win64_zx.tmf';
elseif isunix
    template_make_file = 'CarMaker_unix64_zx.tmf';
else
    error('Unsupported development platform');
end

% If building all models, make sure the last one is the one that builds the
% exectuable and all others are just building static libraries
for i = 1:numel(plugins)
    load_system(plugins{i})
    set_param(plugins{i}, 'TemplateMakefile', template_make_file);
    set_param(plugins{i}, 'HilProjMake', 'off');
    set_param(plugins{i}, 'HilProjHookup', 'off')
    set_param(plugins{i}, 'HilVerboseMake', 'off');
end

% load parameters
evalin('base', 'vh6_base_params');

% Build CarMaker plugins
cd(fullfile(base_dir, 'src', 'plugins'));
for i = 1:numel(plugins)
    % cd(fileparts(which(plugins{i})))
    fprintf("Building %s...\n", plugins{i});
    rtwbuild(plugins{i})
end

% % Make CarMaker executable
% cd(fullfile(base_dir, 'src'));
% system('make');
%
% % Make CarMaker for Simulink mex
% cd(fullfile(base_dir, 'src_cm4sl'));
% system('make');

cd(base_dir);
%This will make sure we have the params loaded to make but then we can
%delete it do it does not get tracked in git
delete('src/plugins/generic_steer_tracker_params.mat')

end

function make_clean()
    % Remove generated code from src
    out = dir('src/*rtw');
    out = out([out.isdir]);
    for i = 1:numel(out)
        rmdir(fullfile(out(i).folder, out(i).name), 's');
    end

    % Remove generated code from src_cm4sl
    out = dir('src_cm4sl/*rtw');
    out = out([out.isdir]);
    for i = 1:numel(out)
        rmdir(fullfile(out(i).folder, out(i).name), 's');
    end

    % Remove linux executable from src
    out = dir('src/*.linux*');
    for i = 1:numel(out)
        delete(fullfile(out(i).folder, out(i).name));
    end

    % Remove mex lib from src_cm4sl
    out = dir('src_cm4sl/*.mex*');
    for i = 1:numel(out)
        delete(fullfile(out(i).folder, out(i).name));
    end
end
