function x0 = backcast_time(a,b,c,d,k,yu,x0sim,maxsize,sqrlam,linearSolver)
% Estimate x0 for backcast case. No specs are needed for estimation since
% all states are unconstrained.
%
%  yu: output/input data for predictor idss(a,b,c,d,k).
%  x0sim: initial state structure created using linsimstate. Passed as
%         input argument for performance reasons. Must contain required
%         delay lags.
%
%  maxsize: options.Advanced.MaxSize: size of largest matrix allowed to be
%           formed (default: 250e3)
%  sqrlam: sqrtm(OutputWeight)
%  linearSolver: function handle of function that solves J*x0 = e. See
%                x0estOptions.

% Copyright 2007-2015 The MathWorks, Inc.

% Old way:
% X01 = x0est(z,struc.a,struc.b,struc.c,struc.d,struc.k,ny,m,maxsize,sqrlam);

% Actual value of Ts is not important for time domain estimation.
% sys = ltipack.ssdata(a-k*c,[k,b-k*d],c,[zeros(size(d,1)),d],[],1);
% sys.a = a-k*c; sys.b = [k,b-k*d]; sys.c = c; sys.d = [zeros(size(d,1)),d];
% data.Nu = data.Nu+data.Ny;
% for kexp = 1:data.Ne
%    data.u{kexp} = [data.y{kexp}, data.u{kexp}];
% end

% data.InterSample = [repmat({'foh'},[data.Ny data.Ne]); data.InterSample];
% data.Period = [Inf(data.Ny,data.Ne); data.Period];
% x0 = x0est(sys, data, [], x0estOpt);

if length(x0sim.State)~=size(a,1)
   x0sim.State = zeros(size(a,1),1);
end

ny = size(c,1);
if norm(k,1)==0
   x0sim.Input = x0sim.Input(ny+1:end,:);
   [J, e] = x0estTimeErrorJacForDTModel(a,b,c,d,yu,x0sim,true(size(a,1),1),maxsize,sqrlam);
else
   yu = [yu(:,1:ny), yu]; % predictor's input channels are [y u]
   % x0sim.Input = [x0sim.Output; x0sim.Input];
   [J, e] = x0estTimeErrorJacForDTModel(a-k*c,[k,b-k*d],c,[zeros(size(d,1)),d],yu,x0sim,...
      true(size(a,1),1), maxsize, sqrlam);
end

if any(~isfinite(e(:))) || any(~isfinite(J(:)))
   x0 = zeros(size(a,1),1);
else
   x0 = linearSolver(J,e);
end
