function out = AnimateChain(t,state,x0,y0,xn,yn)

n = size(state,2)/4;
p0=plot(x0,y0,'rs','markersize',10,'MarkerFaceColor',[1 0 0]);
hold on
pn=plot(xn,yn,'rs','markersize',10,'MarkerFaceColor',[1 0 0]);
for i=1:n
    xi = i;
    yi = n+i;
    p(i)=plot(state(1,xi),state(1,yi),'bs','markersize',10,'MarkerFaceColor',[0 0 1]);
end
l(1) = line([x0,state(1,1)],[y0,state(1,n+1)],'color','b');
for i=2:n
    xi = i;
    yi = n+i;
    l(i) = line([state(1,xi),state(1,xi+2)],[state(1,yi),state(1,yi+2)],'color','b'); 
end
l(n+1) = line([xn,state(1,xi)],[yn,state(1,yi)],'color','b'); 
tl = title(sprintf('%.3', t(1)));
min_x = min([min(state(:,1:n)),x0,xn])-0.05;
max_x = max([max(state(:,1:n)),x0,xn])+0.05;
min_y = min([min(state(:,n+1:n*2)),y0,yn])-0.05;
max_y = max([max(state(:,n+1:n*2)),y0,yn])+0.05;
axis([min_x max_x min_y max_y])
axis square
drawnow
pause
for i=1:size(state,1)
    for j=1:n
        xj = j;
        yj = n+j;
        p(j).XData = state(i,xj); p(j).YData = state(i,yj);
    end
    l(1).XData = [x0,state(i,1)]; l(1).YData = [y0,state(i,n+1)];
    for j=2:n
        xj = j;
        yj = n+j;
        l(j).XData = [state(i,xj),state(i,xj-1)];
        l(j).YData = [state(i,yj),state(i,yj-1)];
    end
    l(n+1).XData = [xn,state(i,xj)];
    l(n+1).YData = [yn,state(i,yj)];
    tl.String = sprintf('%.3f', t(i));
    drawnow
end
end
