%========================================
%===== The Jack-In-The-Box Function =====
%========================================

clear
clc

Amplitude = 30;
Frequency = 1; %Oscillations Per Second
Decay = 1; %Decay = 0 For No Decay
Phase = 270;
Duration = 10;
SamplingRate = 40;
AngularFrequency = 2*pi*Frequency;
Time = 0:1/SamplingRate:Duration;
PeriodCounter = 0;

for i=1:length(Time)
display(i);
         
    JackInTheBoxMovement(i) = Amplitude * sin(AngularFrequency*Time(i) + Phase)./exp(Decay*Time(i));

    if (rem(i,2) == 0)
        PeriodCounter = PeriodCounter + 1;      
    end
     
    figure(1);
    axis([-20 20 (-Amplitude-10) (Amplitude+10)]);
    title('The "Jack-In-The-Box" Function');
    xlabel('Time (Sec)');
    ylabel('Amplitude');
    grid on

    circle = rsmak('circle');
    JackInTheBoxShape = fncmb((circle),[2 0;0 2]);
    Radious = 1/sqrt(2);
    JackInTheBox = fncmb(fncmb(JackInTheBoxShape,[-Radious Radious;Radious Radious]),[0;JackInTheBoxMovement(i)]);
    hold on
    
    if (PeriodCounter == 1)        
        fnplt(JackInTheBox,'r');
        PeriodCounter = 0;
    else
        fnplt(JackInTheBox);
    end
    
    hold off
end