%%% fft_engine.m
% This function is responsible for computing the spectrum (FFT algorithm),
% plotting the spectrum and assuring the realtimeness of the application

function fft_engine(rtlsdr,f_min,f_max,fs,nfft,fig)

freq_axis = 0; % initial values (doesn't plot without them)
X_normalized = 0; % initial values (doesn't plot without them)
% PLOT properties
plot_handle = plot(fliplr(freq_axis),fliplr(X_normalized),'Color',[1 1 0.2]); %color changes the color of the line
set(gca, 'color', [0.06 0.06 0.06]) %background color
set(gca,'GridColor',[1 1 1]); %grid color
set(gca,'Position',[0.08 0.36 0.913 0.63]); %setting the plot position
axis tight
xlabel('Frequency [MHz]','FontSize', 14,'FontWeight','Bold') %labelling x axis
grid on %activating grid
ylim([-130 -20]) %setting the limits of the y axis
set(gca,'xtick',f_min-223000:200000:f_max-223000) 
set(gca,'xticklabel',(f_min-200000)/1e6:0.2:(f_max-200000)/1e6)
set(gca,'xlim',[f_min f_max])
freq_axis = (0:1:nfft-1)*(fs)/nfft+f_min;
set(plot_handle,'XData',freq_axis)
zoom on %enabling zoom function

    while 1
        try
            WindowType=getappdata(fig,'WindowType'); %get information about the currently selected window function from the spectrum.m function
        catch
            break;
        end
        switch WindowType
            case 0
                data_complex = step(rtlsdr); %rectangular window
            case 1
                data_complex = hamming(nfft).*step(rtlsdr); %hamming window               
            case 2
                data_complex = blackmanharris(nfft).*step(rtlsdr); %blackman window
            case 3
                data_complex = hann(nfft).*step(rtlsdr); %hann window
            case 4
                data_complex = kaiser(nfft).*step(rtlsdr); %kaiser window
        end
        X_complex = fftshift(fft(data_complex)); %shifting the DC component into the center of the spectrum
        offset=getappdata(fig,'fftoffset'); %get value of the currently set Y axis offset (if any)
        X_normalized = 10*log10(((abs(X_complex)).^2/(nfft^2)./1))+offset-10; %computing the magnitude spectrum
        bin_width = fs/nfft;
        ylabel(['Power Spectral Density [dBm/',sprintf('%.0f',bin_width),' Hz]'],...
        'FontSize', 14,'FontWeight','Bold')
        try
            set(plot_handle,'YData',X_normalized);      %try/catch to prevent crashing when attempting to exit
            set(plot_handle,'XData',freq_axis);
        catch
            break;
        end        
        pause(0.01);
    end
end