function [seq,first,next_t] = mpcblock_preview(type,data,steps,t)

% data is a matrix of [N-by-ny/nmd] with first row corresponding to time 0.
% steps is the number of steps that previewing is available.
% t is current time, initialized to 0.
% for 'ref', seq is a matrix of [steps-by-ny] with first row at time 1.
% for 'md', seq is a matrix of [steps+1-by-nmd] with first row at time 0.
% first is the current sample at t=0.

% Authors:  A. Bemporad, N.L. Ricker, R. Chen
% Copyright 1994-2020 The MathWorks, Inc.

%#codegen

%% Initialize
ismd = double(strcmp(type,'md'));
isref = 1-ismd;
seq = zeros(steps+ismd,size(data,2));
N = size(data,1);
%% Previewing sequence
for ct = 1:steps+ismd
    if t+ct+isref>N
        % data running out, use the last sample
        seq(ct,:) = data(N,:);
    else
        % add previewing reference (sequence )
        seq(ct,:) = data(t+ct+isref,:);
    end
end
%% Current sample
if t+1>N
    first = data(N,:)';  
else
    first = data(t+1,:)';
end
%% Update step counter for next sample time
next_t = t+1;