%%
% Author: Bojan Lorber
% Date: 22.06.2023
% Version: 1.0
% Description: Use the Fourier Analysis for a given function y(t) to
% determine the dominant frequency of the function

%% Prep workspace
clear;
close all;

%% (a)
% Loading the csv and saving its value
[ fileName, filePath ] = uigetfile('*.csv','Select the file.');
fullFilePath = fullfile(filePath, fileName);

table = readtable(fullFilePath);
t = table.t;
yt = table.y;
fs = 1500;

%% (b)
% Creating half spectrum 
[HalfSpec, fVals] = realFFT(yt,fs);
% Creating variable for computing
absSpec = abs(HalfSpec);
%% (c)
% Generating a figure for given data
fig1 = figure();
subplot(2,1,1);
plot(t,yt,'k');

% Limiting and labeling axis and title
xlim([0,0.1]);
ylim([-0.6,0.6]);
xlabel('$Time$ $t[s]$','Interpreter','latex');
ylabel('$y(t)$ $[-]$','Interpreter','latex');
title('$Sampling$ $Frequency$ $fs = 1500 Hz$','Interpreter','latex');

box on;
grid on;

% Generating a figure for half spectrum 
subplot(2,1,2);
stem(fVals,absSpec);

% Limiting and labeling axis 
xlim([30,55]);
ylim([0,0.4]);
xlabel('$Frequency$ $f[Hz]$','Interpreter','latex');
ylabel('$Magnitude$','Interpreter','latex');

box on;
grid minor;
hold on;
%% (d)

% get the max Magnitude and Frequency of the half spectrum
[maxValue, maxIndex] = max(absSpec); 

% Create the x & y points for the polynomial
yPolyPoins = absSpec([maxIndex-1 maxIndex maxIndex+1]); 
xPolyPoints = fVals([maxIndex-1 maxIndex maxIndex+1]);

% create the coefficants for the polynomial based on the x&y points
cfs = polyfit(xPolyPoints,yPolyPoins,2);

% generate the x range for then poly
xRangePoly = linspace (xPolyPoints(1), xPolyPoints(end),150);

% generate the polynomial
yEval = polyval(cfs,xRangePoly);

% calculate the derivative and its roots for the max x-value of the poly
k = polyder(cfs);
maxF = roots(k);

% calculate the max y-value of the poly
[maxPoly, egal] = max(yEval); 

% Visualize the polynomial and interessting points
plot(xRangePoly,yEval,'r');
plot(xPolyPoints,yPolyPoins,'ro','MarkerFaceColor','r');
plot(maxF,maxPoly,'bo','MarkerFaceColor','b');

% Round values for text
textF = round (maxF*100) /100;
textMag = round (maxPoly*100) /100;

% Positioning and in string %.2 to fill text with values and two decimal places
text (maxF+2,0.3,sprintf('$fmax =%.2fHz$',textF),'Interpreter','latex');
text (maxF+2,0.25,sprintf('$a(fmax) =%.2f$',textMag),'Interpreter','latex');
