%CHORD ANALYZER PROGRAM version 1 - Storing Data

%%%%%%%%%%%%%%%%%%%%%%%get filename%%%%%%%%%%%%%%%%%%%%%
chord = input('Input name of file for importing wrapped in single quotes: ');

%read in sound
[x, Fs] = wavread(chord);
%test: sound(x,Fs);
l = length(x);

%%%%%%%%%%%%%%%%%%%%take fft%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
NFFT = 2^nextpow2(l); % Next power of 2 from length of x
X = abs(fft(x,NFFT)); 
%plot spectrum
f=Fs/2*linspace(0,1,NFFT/2);
%figure;
%plot(f,X(1:NFFT/2));
%title('Amplitude Spectrum of chord');
%xlabel('Frequency (Hz)');
%ylabel('|X(f)|');

%plot dB spectrum
XdB = 20*log10(X);
len = length(XdB);
%figure;
%plot(f,XdB(1:NFFT/2));
%title('Amplitude Spectrum of chord in dB');
%xlabel('Frequency (Hz)');
%ylabel('|X(f)| (dB)');
%legend(chord);

%%%%%%%%%%%%%%%FINDING PEAKS AND CORRESPONDING FREQUENCIES%%%%%%%%%%%%%%%%%%%%%%
%find largest peak
[val, idx] = max(XdB(floor(100*len/Fs):floor(len/2)));  %search from 100 Hz on
idx=idx+100*len/Fs - 1; %idx is in units of length(XdB)/sample
idx=idx*Fs/len;

%%%searching for top 5 peaks
%store all local max's
peaks = 0;
indices = 0;
j=1;
for i = floor(100*len/Fs):floor(len/2),  %search every sample in first half, starting at 100 Hz
    if(XdB(i)>(val-20)) %only look at points within 20 dB of max
        if(XdB(i)>XdB(i-1) & XdB(i)>=XdB(i+1))  %if a local max
            peaks(j)=XdB(i);
            tmp=find(XdB==XdB(i));
            indices(j)=(tmp(1)-1)*Fs/len;
            j=j+1;
        end
    end
end

%find(XdB> val-15)
%eliminating close frequency peaks (part 1)
pks=0;
inds=0;
j=1;
i=1;
while(i<=length(peaks)),
    k=i+1;
    while(k<length(peaks) & (indices(k)-indices(i))<5) %if within 5 Hz of each other
        k=k+1;
    end
    s=max(peaks(i:k-1));
    pks(j)=s;
    tmp=find(XdB==s);
    inds(j)=(tmp(1)-1)*Fs/len;
    j=j+1;
    i=k;
end
%pks
%inds

%choosing max 5 peaks
final_freq=[idx]; %#1
[sorted,j]=sort(pks); %sort peaks from lowest to highest
for i=1:length(sorted)-1,
    if(abs(inds(j(end-i)) - final_freq) > 5) %removing anything within 5 Hz
        final_freq(i+1)=inds(j(end-i));
    else
        tmp=find(not((abs(inds(j(end-i)) - final_freq)>5)));
        if(pks(j(end-i)>pks(tmp)))
            final_freq(i+1)=inds(j(end-i));
        end
    end
end
final_freq(final_freq==0)=[]; %remove any zeros due to removing anything within 5 Hz
%final_freq

%%%%exporting data
%append name of chord
%dlmwrite('Dmaj.txt', final_freq(1:5), 'delimiter', '\t', '-append');

%data = dlmread('G7.txt');

%close all files
ST = fclose('all');