function outDataSet = restructureLoggedInputData(simOut,inputPortInfo,portCompieldInfo,loggedVar,simModel)
% This function returns a input timeseries mapped to the input ports of simModel
% This is typically called when a few of the input port of the model are
% bus element ports.

%   Copyright 2020 The MathWorks, Inc.

simStartTime = simOut.SimulationMetadata.ModelInfo.StartTime;
simStopTime = simOut.SimulationMetadata.ModelInfo.StopTime;

loggedBlockPaths = cell(length(inputPortInfo),1);
inDataSet = simOut.get(loggedVar);
% Logged Data cannot be empty
assert(~isempty(inDataSet));
outTimeseries = createDefaultTimeSeries(inputPortInfo,portCompieldInfo,simStartTime,simStopTime,simModel);

for jdx=1:inDataSet.getLength
    element = inDataSet.getElement(jdx);
    if isa(element, 'Stateflow.SimulationData.State')
        continue;
    end
    blkPathObject = inDataSet.getElement(jdx).BlockPath;
    simlulatedBlockH = get_param(blkPathObject.getBlock(blkPathObject.getLength()),'handle');
    portNumber = str2double(get_param(simlulatedBlockH,'Port'));
    if isempty(loggedBlockPaths{portNumber})
        loggedBlockPaths{portNumber} = blkPathObject;
    end
    blockElement = get_param(simlulatedBlockH,'Element');
    if isempty(blockElement)
        % For top level bus elements
        outTimeseries{portNumber} = inDataSet.getElement(jdx).Values;
    else
        eval(['outTimeseries{portNumber}.' blockElement '= inDataSet.getElement(jdx).Values;']);
    end
end

outDataSet = Simulink.SimulationData.Dataset();

%% Create struct from the structured time series signals
for idx = 1:length(inputPortInfo)
    in_idx_info = inputPortInfo{idx};
    if iscell(in_idx_info)
        in_idx_info = in_idx_info{1};
    end
    blockH = get_param(in_idx_info.BlockPath,'handle');
    portNumber = str2double(get_param(blockH,'port'));
    assert(idx == portNumber);
    signalToAdd = Simulink.SimulationData.Signal;
    signalToAdd.Values = outTimeseries{idx};
    signalToAdd.Name = ['dvInputSignalLogger_' num2str(idx)];
    signalToAdd.BlockPath = loggedBlockPaths{idx};
    outDataSet = outDataSet.addElement(signalToAdd);
end
end
