% Massless spring
clf
kk=50;
L = 300;
sx(L)=0;
sy(L)=0;
dx=0.1;
n=10;
A=10;
k=15;
wall_y = 1000;
for i = 1:L/dx
    sx(i)=i*dx;
    sy(i)=A+A*sin((i*dx)/(L/(n*2*pi)));
end
plot(sx,sy);hold on
axis([0 wall_y 0 (10*A)])
x = 2*L;
w = 250;
rectangle('Position',[x,0,w,2*A])
xx=[x x (x+w) (x+w)];
yy=[0 2*A 2*A 0];
fill(xx,yy,'ok')
m = 50;
t=0;
dt = 0.01;
t_end = 50;
v=-80;
vmax = -v;
x_rec(t_end/dt) = 0;
x_rec(1) = x;
v_rec(t_end/dt) = 0;
v_rec(1) = vmax;
tt_rec(t_end/dt) = 0;
flag = false;
for ii = 1:t_end/dt

    if x > L && (x+w) <= wall_y && flag == false
        x = x+v*dt;
        s_length = L;
    elseif x <= L && flag == false
        flag = true;
    elseif flag
        f = kk*abs(v);
        F = (L-x)*k;
        a = F/m-v/(abs(v))*abs(f)/m;
        x = x+v*dt;
        v = v + a*dt;
        s_length = x;
    end
tt(ii) = ii*dt;
x_rec(ii) =  x;
v_rec(ii) =-v;
    
clf
for i = 1:s_length/dx
    sx(i)=i*dx;
    sy(i)=A+A*sin((i*dx)/(s_length/(n*2*pi)));
end
subplot(3,1,1)
plot(sx(1:i),sy(1:i));hold on
title('Spring simulation')
axis([0 wall_y 0 (10*A)])
rectangle('Position',[x,0,w,2*A])
xx=[x x (x+w) (x+w)];
yy=[0 2*A 2*A 0];
fill(xx,yy,'ok')
subplot(3,1,2)
plot(tt(1:ii),x_rec(1:ii))
title('x-t graph')
axis([0 t_end 0 wall_y])
subplot(3,1,3)
plot(tt(1:ii),v_rec(1:ii))
title('v-t graph')
axis([0 t_end -vmax*2 vmax*2])
drawnow
if mod(ii,50) == 0
   saveas(gcf, ['movie1',sprintf('%03d',ii/50),'.png'])
end
end

