function autoblkCIDynamometerStart(varargin)
% autoblkCIDynamometerStart
%
%   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 folder from CI prj and delete
prjobj = openProject(fullfile(prjroot,'CI'));
prjdir2rm = fullfile(prjroot,'CI','Plant','Calibrations');
prjref2rm = [];
rmprjdir
% Move Simple Engine file and add to CI prj
file2move = 'SimpleEngine.slx';
filefrom = fullfile(prjroot,'SI','Plant',file2move);
fileto = fullfile(prjroot,'CI','Plant',file2move);
if ~movefile(filefrom,fileto)
    warnstring = ['Exception moving SimpleEngine file. ', ...
        'Simple Engine variant will not be updated.'];
    warndlg(warnstring,'Dyno application launch exception','replace')
else
    addFile(prjobj,fileto);
end
% Delete unnecessary DDs
ddtokeep = {'CiEngineController.sldd','SiEngineController.sldd',...
    'CiEngineCore.sldd','SiEngineCore.sldd','CiMappedEngine.sldd', ...
    'EngineDynamometer.sldd','Environment.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);
saveChanges(vvtddobj)
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
% 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 = ['CI ',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'),'CI Engine')
    set_param(engplant,'LabelModeActiveChoice','CI Engine')
end
if ~strcmp(get_param(engcntrl,'ActiveVariant'),'CI Engine Controller')
    set_param(engcntrl,'LabelModeActiveChoice','CI Engine Controller')
end
if ~strcmp(get_param(dynocntrl,'ActiveVariant'),'CalCtrl')
    set_param(dynocntrl,'LabelModeActiveChoice','CalCtrl')
end
% Delete unnecessary button blocks and move to proper position
path2blk = strcat(modelname,'/');
blk2del = {'Recalibrate Engine'};
siblkh = getSimulinkBlockHandle(strcat(path2blk,blk2del));
ciblkh = ...
    getSimulinkBlockHandle(strcat(modelname,'/Recalibrate CI Engine'));
sublkh = getSimulinkBlockHandle(strcat(modelname,'/Subsystem3'));
helph = getSimulinkBlockHandle(strcat(modelname,'/Subsystem4'));
if siblkh ~= -1
    sipos = get_param(siblkh, 'Position');
    delblks
    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);
    set_param(ciblkh,'Position',sipos)
    set_param(sublkh,'Position',cipos)
    set_param(helph,'Position',...
        [subcntr-hlpwidth/2,subpos(2),subcntr+hlpwidth/2,subpos(4)])
else
    warnstring = ['Exception deleting Resize SI Engine button. ', ...
        'Use Resize CI 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 = {'SI Engine Controller'};
delblks
path2blk = strcat(modelname,'/Engine System',...
    '/Engine Plant/Engine/');
blk2del = {'SI Engine','SI Mapped Engine', 'SI DL Engine'};
delblks
% Set SiOrCi mask parameter to si or ci as appropriate
maskObj = get_param(helph, 'MaskObject');
if ~strcmp(maskObj.getParameter('SiOrCi').Value,'ci')
    maskObj.getParameter('SiOrCi').set('Value','ci');
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,'ci0')
    maskObj.getParameter('NoPlot').set('Value','ci0');
end
save_system(modelname,'SaveDirtyReferencedModels',true)
% Remove project reference to SI and delete
prjdir2rm = [];
prjref2rm = fullfile(prjroot,'SI');
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
