function autoblkSIDynamometerStart(varargin)
% autoblkSIDynamometerStart
%
%   Copyright 2016-2024 The MathWorks, Inc.

% Demo setup
[~, ~, topLevelProjectRoot] = ...
    matlab.internal.project.example.projectDemoSetUp( ...
    fullfile(matlabroot,'toolbox','autoblks','autoblksreference',...
    'EngDynamometer.zip'),char(varargin), false);
prjroot = eraseBetween(topLevelProjectRoot,...
        numel(topLevelProjectRoot)-...
        numel(strcat(filesep,'EngDynamometer'))+1,...
        numel(topLevelProjectRoot));
% Remove Calibrations and FMUs folders from SI prj and delete
prjobj = openProject(fullfile(prjroot,'SI'));
prjdir2rm = fullfile(prjroot,'SI','Plant','Calibrations');
prjref2rm = [];
rmprjdir
prjdir2rm = fullfile(prjroot,'SI','Plant','FMUs');
rmprjdir
% Delete unnecesary files from SI folder
path2files = fullfile(prjroot,'SI','Plant');
files2del = {'FMUEngine.slx','FMUEngineSSC.slx','MotoMappedEngine.slx', ...
    'MotoSimpleEngine.slx','NoEngine.slx','SimpleEngineSSC.slx'};
delfiles
path2files = fullfile(prjroot,'SI','Controller');
files2del = {'MotoNoEngineController.slx','MotoSimpleECU.slx', ...
    'NoEngineController.slx','SimpleECU.slx'};
delfiles
% Delete unnecessary DDs
ddtokeep = {'SiEngineController.sldd','SiEngineCore.sldd',...
    'SiEngineCoreNA.sldd','SiEngineCoreV.sldd','SiMappedEngine.sldd', ...
    'EngineDynamometer.sldd','Environment.sldd','SiDLEngine.sldd', ...
    'SiEngine.sldd','SimpleEngine.sldd','VirtualDynoConfig.sldd',...
    'VirtualDynoTemplate.sldd'};
prjobj = openProject(fullfile(prjroot,'EngineData'));
vvtddobj = ...
    Simulink.data.dictionary.open('VirtualDynoTemplate.sldd');
ddreftodel = vvtddobj.DataSources';
ddreftodel = ddreftodel(~ismember(ddreftodel,ddtokeep));
cellfun(@(x) removeDataSource(vvtddobj,x),ddreftodel);
path2files = fullfile(prjroot,'EngineData','Dictionaries');
files2del = dir(path2files);
files2del = {files2del.name};
files2del = ...
    files2del(cellfun(@(x) ~strcmp(x,'.') && ~strcmp(x,'..'),files2del));
files2del = files2del(~ismember(files2del,ddtokeep));
delfiles
% Copy data dictionary with crank-angle resolved data
crkddname = 'SiEngineCoreCrk.sldd';
crkresdd = fullfile(matlabroot,'toolbox','autoblks','autoblksreference',...
    'refappgen','EngDynamometer','CrkDataEngine',crkddname);
crkresdd2 = fullfile(path2files,crkddname);
try
    if exist(crkresdd2,'file') == 0
        copyfile(crkresdd,crkresdd2);
        if ispc
            fileattrib(crkresdd2,'+w')
        else
            fileattrib(crkresdd2,'+w','u')
        end
    end
    addFile(prjobj,crkresdd2);
    addDataSource(vvtddobj,crkddname)
catch
    warning(['Exception copying crank resolved data dictionary. ' ...
        'Engine Dynamometer may still work.']);
end
saveChanges(vvtddobj)
% Open top level project and model
prjobj = openProject(topLevelProjectRoot);
modelname = 'EngineDynamometer';
titlend = 'Engine Dynamometer';
open_system(modelname);
% Customize title
titleh = find_system(modelname, 'RegExp', 'on', 'FindAll', 'on', ...
    'SearchDepth', 1, 'Type', 'annotation',  'Text', titlend);
titletxt = get_param(titleh,'PlainText');
titlenew = ['SI ',titlend];
titlepos = get_param(titleh, 'Position');
if ~strcmp(titletxt,titlenew)
    delete(titleh)
    Simulink.Annotation(strcat(modelname,'/',titlenew),'Position', ...
        titlepos,'FontSize',36);
end
% Set correct variants
engplant = strcat(modelname,'/Engine System/Engine Plant/Engine');
engcntrl = ...
    strcat(modelname,'/Engine System/Engine Controller/Engine Control');
dynocntrl = strcat(modelname,'/Dynamometer Control');
if ~strcmp(get_param(engplant,'ActiveVariant'),'SI Engine')
    set_param(engplant,'LabelModeActiveChoice','SI Engine')
end
if ~strcmp(get_param(engcntrl,'ActiveVariant'),'SI Engine Controller')
    set_param(engcntrl,'LabelModeActiveChoice','SI Engine Controller')
end
if ~strcmp(get_param(dynocntrl,'ActiveVariant'),'CalThrWg')
    set_param(dynocntrl,'LabelModeActiveChoice','CalThrWg')
end
% Delete unnecessary button blocks and move to proper position
path2blk = strcat(modelname,'/');
blk2del = {'Recalibrate CI Engine'};
ciblkh = getSimulinkBlockHandle(strcat(path2blk,blk2del));
sublkh = getSimulinkBlockHandle(strcat(modelname,'/Subsystem3'));
helph = getSimulinkBlockHandle(strcat(modelname,'/Subsystem4'));
if ciblkh ~= -1
    cipos = get_param(ciblkh, 'Position');
    subpos = get_param(sublkh, 'Position');
    subcntr = (subpos(1)+subpos(3))/2;
    hlppos = get_param(helph, 'Position');
    hlpwidth = hlppos(3)-hlppos(1);
    delblks
    set_param(sublkh,'Position',cipos)
    set_param(helph,'Position',...
        [subcntr-hlpwidth/2,subpos(2),subcntr+hlpwidth/2,subpos(4)])
else
    warnstring = ['Exception deleting Resize CI Engine button. ', ...
        'Use Resize SI Engine button.'];
    warndlg(warnstring,'Dyno application launch exception','replace')
end
% Delete unnecesary engine and controller variant blocks
path2blk = strcat(modelname,'/Engine System',...
    '/Engine Controller/Engine Control/');
blk2del = {'CI Engine Controller'};
delblks
path2blk = strcat(modelname,'/Engine System',...
    '/Engine Plant/Engine/');
blk2del = {'CI Engine','CI Mapped Engine'};
delblks
% Set SiOrCi mask parameter to si or ci as appropriate
maskObj = get_param(helph, 'MaskObject');
if ~strcmp(maskObj.getParameter('SiOrCi').Value,'si')
    maskObj.getParameter('SiOrCi').set('Value','si');
end
% Set NoPlot mask parameter to si0 or ci0 as appropriate
maskObj = get_param(strcat(modelname,'/Performance Monitor'), 'MaskObject');
if ~strcmp(maskObj.getParameter('NoPlot').Value,'si0')
    maskObj.getParameter('NoPlot').set('Value','si0');
end
save_system(modelname,'SaveDirtyReferencedModels',true)
% Remove project reference to CI and delete
prjdir2rm = [];
prjref2rm = fullfile(prjroot,'CI');
rmprjdir
% Nested functions
    function delblks
        fullp2del = cellfun(@(x) strcat(path2blk,x),blk2del, ...
            'UniformOutput',false);
        blkhs = cellfun(@getSimulinkBlockHandle,fullp2del);
        if any(blkhs == -1)
            warning(['Exception deleting blocks in: ', ...
                path2blk, ...
                '. Engine Dynamometer may still work.']);
        else
            arrayfun(@delete_block,blkhs)
        end
    end
    function rmprjdir
        try
            if ~isempty(prjref2rm)
                removeReference(prjobj,prjref2rm)
                rmdir(prjref2rm,'s')
            end
            if ~isempty(prjdir2rm)
                removeFile(prjobj,prjdir2rm)
                rmdir(prjdir2rm,'s')
            end
        catch
            warning(['Exception deleting prj folder or reference. ' ...
                'Engine Dynamometer may still work.']);
        end
    end
    function delfiles
        try
            cellfun(@(x) ...
                removeFile(prjobj,fullfile(path2files,x)),files2del);
            if strcmp(recycle,'on')
                recycle('off');
            end
            cellfun(@(x) delete(fullfile(path2files,x)),files2del);
        catch
            warning(['Exception deleting unnecesary files in: ' ...
                path2files, ...
                '. Engine Dynamometer may still work.']);
        end
    end
end
