%--------------------------------------------------
% Tony Hyun Kim
% 6.003: PS #6, Matlab assignment
%--------------------------------------------------

%--------------------------------------------------
% From last week: Problem (a)
%--------------------------------------------------
n = [0:999];
d0 = sin(0.7217*n) + sin(1.0247*n);
d1 = sin(0.5346*n) + sin(0.9273*n);
d2 = sin(0.5346*n) + sin(1.0247*n);
d3 = sin(0.5346*n) + sin(1.1328*n);
d4 = sin(0.5906*n) + sin(0.9273*n);
d5 = sin(0.5906*n) + sin(1.0247*n);
d6 = sin(0.5906*n) + sin(1.1328*n);
d7 = sin(0.6535*n) + sin(0.9273*n);
d8 = sin(0.6535*n) + sin(1.0247*n);
d9 = sin(0.6535*n) + sin(1.1328*n);

%--------------------------------------------------
% Also from last week: Problem (c)
%--------------------------------------------------
space = zeros(1,100);
phone = [d7 space d4 space d5 space d5 space d5 space d0 space d2];

%--------------------------------------------------
% Problem (f)
%--------------------------------------------------
w0   = 2*pi/2048;
d0_k = round(1/w0*[0.7217 1.0247]); 
d1_k = round(1/w0*[0.5346 0.9273]);
d2_k = round(1/w0*[0.5346 1.0247]); 
d3_k = round(1/w0*[0.5346 1.1328]); 
d4_k = round(1/w0*[0.5906 0.9273]); 
d5_k = round(1/w0*[0.5906 1.0247]);
d6_k = round(1/w0*[0.5906 1.1328]); 
d7_k = round(1/w0*[0.6535 0.9273]); 
d8_k = round(1/w0*[0.6535 1.0247]); 
d9_k = round(1/w0*[0.6535 1.1328]);

d_k = [d0_k; d1_k; d2_k; d3_k; d4_k; d5_k; d6_k; d7_k; d8_k; d9_k];

%--------------------------------------------------
% Problem (g)
%--------------------------------------------------
D8 = fft(d8, 2048);
plot(w0*[0:2047], abs(D8).^2);

% The following loop searches for the two highest peaks
k1 = 0; max_1 = 0;
k2 = 0; max_2 = 0;
for k = 1:length(D8)/2 % We'll search only the lower half
                       % of the transform
    if(abs(D8(k)) > max_1)
        k2 = k1; max_2 = max_1;
        k1 = k;  max_1 = abs(D8(k));
    elseif(abs(D8(k)) > max_2)
        k2 = k;  max_2 = abs(D8(k));
    end
end

%--------------------------------------------------
% Results: [k1 k2] = [214 335]
%--------------------------------------------------
% This is consistent with d8_k = [213 334] once we  
% take into account the fact that Matlab's fft 
% results begins the index with 0.
%--------------------------------------------------