function [mpcplanner,structname] = vppblock_utilExportDataStruct(blk,modelname,AllNames)
% Utility function of the "Vehicle Path Planner (VPP) System" block.
% Called when "Create VPP subsystem" button is clicked.

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


%   Author: Meng Xia, Rong Chen
%   Copyright 2022 The MathWorks, Inc.


%% get mask variables
vppmask = Simulink.Mask.get(blk);
% WS variable struct
maskwsvars = vppmask.getWorkspaceVariables;
% turn struct to cell
maskwsvarscell = struct2cell(maskwsvars);
% get variable values
blkDataType = getVarValue(maskwsvarscell,'blkDataType');
blkObsDim = getVarValue(maskwsvarscell,'blkObsDim');
egoParas = getVarValue(maskwsvarscell,'egoParas');
nlobj = getVarValue(maskwsvarscell,'nlobj');
numParas = getVarValue(maskwsvarscell,'numParas');
wheelbase = getVarValue(maskwsvarscell,'wheelbase');
numObs = getVarValue(maskwsvarscell,'numObs');
%% create mpcpathplanner struct 
mpcplanner = struct(...
                'Planner',nlobj,...
                'NumberOfObstacles',numObs,...
                'DataType',blkDataType,...
                'EgoWheelbase',wheelbase,...
                'EgoParameters',egoParas,...
                'ObstaclesMatrixDimensions',blkObsDim,...
                'NumberOfStageParameters',numParas...
                );
% optinal blocks/data            
if strcmp(get_param(blk,'obs_ext'),'off')
    blkObsMat = getVarValue(maskwsvarscell,'blkObsMat');
    mpcplanner.('ObstaclesMatrix') = blkObsMat;
end
if strcmp(get_param(blk,'v_ext'),'off')
    v_range = getVarValue(maskwsvarscell,'v_range');
    mpcplanner.('VelocityRange') = v_range;
end
if strcmp(get_param(blk,'steer_ext'),'off')
    steer_range = getVarValue(maskwsvarscell,'steer_range');
    mpcplanner.('SteeringRange') = steer_range;
end
% export to MATLAB workspace
structname = [modelname '_data'];
structname = matlab.lang.makeUniqueStrings(structname, AllNames);
assignin('base',structname,mpcplanner);

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