function [mpcacc,structname] = accblock_utilExportDataStruct(blk,modelname,AllNames)
% Utility function of the "Adaptive Cruise Control (ACC) System" block.
% Called when "Creste ACC subsystem" button is clicked.

% Inputs 
%   modelname: model name for the crated ACC subsystem
%   ALLNames: all names already exist in base workspace
% Outputs
%   mpcacc: data struct containing all data for ACC block
%   structname: name for the struct containing all data for ACC block


%   Author: Meng Xia, Rong Chen
%   Copyright 2017-2018 The MathWorks, Inc.


%% get mask variables
accmask = Simulink.Mask.get(blk);
% WS variable struct
maskwsvars = accmask.getWorkspaceVariables;
% turn struct to cell
maskwsvarscell = struct2cell(maskwsvars);
% get variable values
DataType = getVarValue(maskwsvarscell,'DataType');
L0 = getVarValue(maskwsvarscell,'DefaultSpacing');
mpcobj = getVarValue(maskwsvarscell,'mpcobj');
vmax = getVarValue(maskwsvarscell,'MaxVelocity');
vmin = getVarValue(maskwsvarscell,'MinVelocity');

%% create mpcacc struct 
mpcacc = struct('DefaultSpacing',L0,...
                'MaxVelocity',vmax,...
                'MinVelocity',vmin,...
                'DataType',DataType,...
                'Controller',mpcobj...
                );
% optinal blocks/data            
if strcmp(get_param(blk,'amin_ext'),'off')
    amin = getVarValue(maskwsvarscell,'MinAcceleration');
    mpcacc.('MinAcceleration') = amin;
end
if strcmp(get_param(blk,'amax_ext'),'off')
    amax = getVarValue(maskwsvarscell,'MaxAcceleration');
    mpcacc.('MaxAcceleration') = amax;
end
% export mpcacc to MATLAB workspace
structname = [modelname '_data'];
structname = matlab.lang.makeUniqueStrings(structname, AllNames);
assignin('base',structname,mpcacc);

%% local function
function value = getVarValue(maskwsvarscell,needvarname)
% locate needvarname
hasvar = ismember(maskwsvarscell(1,:),needvarname);
index = hasvar;
% get value out
value = maskwsvarscell{2,index};
