function [I,S,r,dt,It,St]=tswresid4text(In,Sn,N,sg)
[I,S]=tsw(In,Sn,N,sg); %Find the coefficients.
t=linspace(0,.5,256);
It=polyval(I(end:-1:1),t);
St=polyval(S(end:-1:1),t);
Std=polyval([N:-1:1].*S(end:-1:2),t);
Itd=polyval([N:-1:1].*I(end:-1:2),t);
r=[Itd+sg*St.*It.^2;Std+sg*St.^3.*It];
rsq = sqrt(r(1,:).^2+r(2,:).^2);
semilogy(t,abs(r(1,:)),'k-',t,abs(r(2,:)),'k-.')
%Find the numerical value dt at which the residual start to be bigger than the tolerance, here 1.0e-6, and evaluate the Taylor polynomial at this point to have new initial values.
ii=find(abs(rsq)>1.0e-6);
if numel((ii))>0,
    ig=ii(1)-1;
    if ig==0,
        error('failure',rsq(1))
    end
    dt = t(ig);
    It = It(ig);
    St = St(ig);
else
    dt = 1.0;
    It = It(end);
    St = St(end);
end
end

