clear all 
clc
close all 

% SKRIPT PRO CTVERCOVE POLE
% HEVELKA 2019


%% vstupni hodnoty 
global N M f_vz c d 

Teplota = 20; %teplota v mistnosti 
c = 331.57 + (0.607*Teplota); % rychlost zvuku [m/s]
f_vz = 20e3; % vzorkovaci frekvence [Hz]
d = 0.2; % vzdalenost mikrofonu [m] 
T = 1.9; % sledovany cas [s]
%% umisteni mikrofonu + vizualizace 
M = 4; % pocet mikrofonu
Mikrofonni_pole_ctverec();

%%
%%% SIGNAL
load('Mik4_CTVEREC_02_EL0_AZ0.mat')
%%% SIGNAL


% vyber oblast, ktera se ma analyzovat
X = 1*f_vz;
Y = 1.9*f_vz;
N = (Y - X)+1;
[sig_celk,t_span] = Matice_signal_vyber(data,X,Y); % vytvori matici signalu NxM



%%%% NOISE SIGNAL %%%%
load('NOISE.mat')
%%%
[sig_noise,t_noise] = Matice_noise(noise_signal); % vytvori matici noise signalu NxM

%% KALIBRACE - nekolik vterin sleduje pouze sum z okoli, pote urci hranici
% detekce pro kazdy signal

[Maximum,Noise_max] = Hladina_Detekce(sig_noise');

Max_S = Maximum + (0*Maximum); % zde se muze ovladat, kde bude maximum - muzeme ho snizit i zvysit 

%% Detekce a filtrace peaku
[peak_s,oblast_s,ts_out,SNR] = Detekce(sig_celk,t_span,Max_S);

disp(SNR); %% vypise rozdil mezi maximem a hladinou detekce - signal to noise ratio

%% vykresleni signalu
Vizualizace_signalu(sig_celk,t_span,oblast_s,ts_out,peak_s);


%% CTVERCOVE MIKROFONNI POLE - 4 mikrofony
%% DAS  
fig3 = figure(3);
fig3.Position = [0 47 735 318];
subplot(2,1,1);

[A_B1h,alfa_h1,RMS1h] = Beam_DAS(peak_s(:,1:M/2));

plot(alfa_h1,RMS1h); % vysledny uhel :) 
title('VYSLEDEK');
xlabel('Angle [°]');
ylabel('RMS [-]');

[A_B2h,alfa_v1,RMS2h] = Beam_DAS(peak_s(:,(M/2)+1:M));
ANGLE_Beam_horizontalni = (A_B1h + A_B2h)/2;

subplot(2,1,2);
plot(alfa_v1,RMS1h); % vysledny uhel :) 
title('VYSLEDEK');
xlabel('Angle [°]');
ylabel('RMS [-]');

% zde musi byt signal serazen jako sig1,sig3,sig2,sig4
peak_ver = peak_s;
peak_ver(:,1) = peak_s(:,1);
peak_ver(:,2) = peak_s(:,3);
peak_ver(:,3) = peak_s(:,2);
peak_ver(:,4) = peak_s(:,4);

[A_B1v] = Beam_DAS(peak_ver(:,1:M/2));
[A_B2v] = Beam_DAS(peak_ver(:,3:M));

ANGLE_Beam_vertikalni = (A_B1v + A_B2v)/2;


%% XCORR
A_X1h = xcorr_update_linearni(peak_s(:,1:M/2));
A_X2h = xcorr_update_linearni(peak_s(:,(M/2)+1:(M)));

A_X1v = xcorr_update_linearni(peak_ver(:,1:M/2));
A_X2v = xcorr_update_linearni(peak_ver(:,3:M));

ANGLE_XCORR_h = (A_X1h + A_X2h)/2;
ANGLE_XCORR_v = (A_X1v + A_X2v)/2;

%% VYSLEDEK 

%fprintf('Vyhodnoceni uhlu metodou TDOA \n Tento uhel je: %0.5g \n \n ',ANGLE_TDOA);
fprintf('Horizontalni uhel BEAM: %0.5g \n',ANGLE_Beam_horizontalni);
%fprintf('Vertikalni uhel BEAM: %0.5g \n',ANGLE_Beam_vertikalni);

fprintf('Horizontalni uhel XCORR: %0.5g \n',round(ANGLE_XCORR_h));
%fprintf('Vertikalni uhel XCORR: %0.5g \n',ANGLE_XCORR_v);

