function [mpclka,structname] = lkablock_utilExportDataStruct(blk,modelname,AllNames)
% Utility function of the "Lane Keeping Assist (LKA) System" block. Called
% when "Creste LKA subsystem" button is clicked.

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


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


%% get mask variables
lkamask = Simulink.Mask.get(blk);
% WS variable struct
maskwsvars = lkamask.getWorkspaceVariables;
% turn struct to cell
maskwsvarscell = struct2cell(maskwsvars);
% get variable values
DataType = getVarValue(maskwsvarscell,'DataType');
mpcobj = getVarValue(maskwsvarscell,'mpcobj');
Ts = getVarValue(maskwsvarscell,'Ts');
NumEgoStates = getVarValue(maskwsvarscell,'NumEgoStates');
UseExternalModel = getVarValue(maskwsvarscell,'UseExternalModel');

m = getVarValue(maskwsvarscell,'VehicleMass');
Iz = getVarValue(maskwsvarscell,'VehicleYawInertia');
Cr = getVarValue(maskwsvarscell,'RearTireStiffness');
lr = getVarValue(maskwsvarscell,'LengthToRear');
lf = getVarValue(maskwsvarscell,'LengthToFront');
Cf = getVarValue(maskwsvarscell,'FrontTireStiffness');
lag = getVarValue(maskwsvarscell,'TransportLag');
hasLag = getVarValue(maskwsvarscell,'hasLag');

%% create mpcacc struct 
mpclka = struct('DataType',DataType,...
                'Controller',mpcobj,...
                'NumEgoStates',NumEgoStates,...
                'UseExternalModel',UseExternalModel,...
                'VehicleMass',m,...
                'VehicleYawInertia',Iz,...
                'RearTireStiffness',Cr,...
                'LengthToRear',lr,...
                'LengthToFront',lf,...
                'FrontTireStiffness',Cf,...
                'Ts',Ts,...
                'TransportLag',lag,...
                'hasLag',hasLag...
                );
% optinal blocks/data            
if strcmp(get_param(blk,'umin_ext'),'off')
    umin = getVarValue(maskwsvarscell,'MinSteering');
    mpclka.('MinSteering') = umin;
end
if strcmp(get_param(blk,'umax_ext'),'off')
    umax = getVarValue(maskwsvarscell,'MaxSteering');
    mpclka.('MaxSteering') = umax;
end
% export mpcacc to MATLAB workspace
structname = [modelname '_data'];
structname = matlab.lang.makeUniqueStrings(structname, AllNames);
assignin('base',structname,mpclka);

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