%{

                   Ultrafast Project Square Wave Transform

%}
clear
clc
%% Square Wave W/Carrier

%  t is The Time Array Over Which the Signal Exists
t=linspace(-50,50,2^13);

%  The Following Definitions are Given in Class
fmin = -1/(2*(t(2)-t(1)));
df = 1/(length(t)*(t(2)-t(1)));

%  Frequency Array for Plotting
f=fmin:df:-fmin-df;

%  Step Function for Time Signal
y=zeros(1,length(t));
for i=round(0.3*length(t)):round(0.7*length(t))
    y(i)=1;
end

%  Create the Carrier Wave and the Signal (funct)
carrier = sin(t);
funct = y.*carrier;


%  Calculate the FFT of the Step Function, the Carrier, and the Signal
%  fftshift is Used to Rearrange the Arrays So That 0-frequency Data Points
%  are In the Middle
carrier_fft = fftshift(fft(carrier));
y_fft = fftshift(fft(y));
funct_fft = fftshift(fft(funct));

%  Reconstruct the Original Signal From The FFTed Signal
%  ifftshift is Used Prior to ifft Because the ifft Command Requires the
%  Array to have 0-frequency data at the beginning of the array (instead of
%  the center)

carrier2 = ifft(ifftshift(carrier_fft));
y2 = ifft(ifftshift(y_fft));
funct2 =ifft(ifftshift(funct_fft));

%% Plotting


figure(1)
subplot(2,3,1)
plot(t,carrier); title('Carrier Wave'); ylim([-1.2 1.2])
xlabel('Time (s)')
ylabel('Amplitude')

subplot(2,3,2)
plot(t,y); title('Envelope'); ylim([-.2 1.2])
xlabel('Time (s)')
ylabel('Amplitude')

subplot(2,3,3)
plot(t,funct); title('Waveform'); ylim([-1.2 1.2])
xlabel('Time (s)')
ylabel('Amplitude')

subplot(2,3,4)
plot(f,real(carrier_fft)); title('Carrier Transform'); xlim([-0.7 0.7])
xlabel('Frequency (Hz)')
ylabel('Amplitude')

subplot(2,3,5)
plot(f,real(y_fft)); title('Envelope Transform'); xlim([-0.7 0.7])
xlabel('Frequency (Hz)')
ylabel('Amplitude')

subplot(2,3,6)
plot(f,real(funct_fft)); title('Waveform Transform'); xlim([-0.7 0.7])
xlabel('Frequency (Hz)')
ylabel('Amplitude')


figure(2)
subplot(2,3,1)
plot(t,carrier); title('Carrier Wave'); ylim([-1.2 1.2])
xlabel('Time (s)')
ylabel('Amplitude')

subplot(2,3,2)
plot(t,y); title('Envelope'); ylim([-.2 1.2])
xlabel('Time (s)')
ylabel('Amplitude')

subplot(2,3,3)
plot(t,funct); title('Waveform'); ylim([-1.2 1.2])
xlabel('Time (s)')
ylabel('Amplitude')

subplot(2,3,4)
plot(t,real(carrier2)); title('Carrier Wave Transform/Untransform'); ylim([-1.2 1.2])
xlabel('Time (s)')
ylabel('Amplitude')

subplot(2,3,5)
plot(t,real(y2)); title('Envelope Transform/Untransform'); ylim([-.2 1.2])
xlabel('Time (s)')
ylabel('Amplitude')

subplot(2,3,6)
plot(t,real(funct2)); title('Waveform Transform/Untransform'); ylim([-1.2 1.2])
xlabel('Time (s)')
ylabel('Amplitude')


