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

% Setup variables
modelname = 'EngineDynamometer';
titlend = 'Engine Dynamometer';
passcarxlsx = fullfile(matlabroot,'toolbox','autoblks',...
    'autoblksreference','PassengerCar.xlsx');
% Demo setup
autoblkSIDynamometerStart
% Customize title
titleh = find_system(modelname, 'RegExp', 'on', 'FindAll', 'on', ...
    'SearchDepth', 1, 'Type', 'annotation',  'Text', titlend);
titletxt = get_param(titleh,'PlainText');
titlenew = ['SI H2 ',titlend];
titlepos = get_param(titleh, 'Position');
if ~strcmp(titletxt,titlenew)
    delete(titleh)
    Simulink.Annotation(strcat(modelname,'/',titlenew),'Position', ...
        titlepos,'FontSize',36);
end
save_system(modelname,'SaveDirtyReferencedModels',true)
% Read and update H2 data
opts = spreadsheetImportOptions;
opts.Sheet = 'Engine';
opts.VariableNames = 'DataSource';
opts.DataRange = 'J66:J126';
datasource = table2cell(readtable(passcarxlsx,opts));
opts.VariableNames = 'ParameterName';
opts.DataRange = 'K66:K126';
parametername = table2cell(readtable(passcarxlsx,opts));
opts.VariableNames = 'DefaultValue'; 
opts.DataRange = 'F66:F126';
defaultvalue = table2cell(readtable(passcarxlsx,opts));
cellfun(@setdds,datasource,parametername,defaultvalue);
cellfun(@savedd, unique(datasource));
end

function setdds(x,y,z)
ddobj = Simulink.data.dictionary.open(x);
secobj = getSection(ddobj,'Design Data');
ddentry = getEntry(secobj,y);
entryval = getValue(ddentry);
if isa(entryval,'Simulink.Parameter')
    entryval.Value = str2num(z);
else
    entryval = str2num(z);
end
setValue(ddentry,entryval);
end

function savedd(ddname)
ddobj = Simulink.data.dictionary.open(ddname);
saveChanges(ddobj)
end
