clear all, close all, clc

TotSeconds = 5; % Quanti secondi voglio registrare
SampleBits = 8;
NChannels = 1; % 1 for mono, 2 for stereo
Fs = 8000;
DBName = 'ProvaEqualizer2';
flagSave = 1;
flagRecord = 0;

flagReproduceInput = 1;
flagReproduceOutput = 1;
% flagReproduceNoisy = 1;
% flagReproduceNoisyFiltered = 1;

FilterOrder = 4;
flagPlotBands = 1;

SNRdB = 0; % 10*log10(SignalPower/NoisePower)

FrequencyBands = [100 200; 205 350; 360 500; 510 1000; 1020 2000; 2040 3300];%[85 3e3];%[2000 4e3];%[85 3e3];

Equalizer = [0.7;0.85;1;1;1;0.8]; % Correzione sui bassi e sugli alti
Equalizer = [1; 1; 0.6; 0.4; 0.3; 0.2]; % Enfasi sui bassi
% Equalizer = [0.4; 0.8; 1; 1; 0.9; 0.5]; % Enfasi sui Medi
Equalizer = [1; 1; 0; 0; 0; 0]; % Passa basso
Equalizer = [0;0;0;0.5;1;1]; % Passa Alto

if(flagPlotBands)
    
    figHandler = figure;
    
    for iBand = 1:size(FrequencyBands,1)
        
        semilogx(FrequencyBands(iBand,1)-5:1:FrequencyBands(iBand,2)+5, [zeros(1,5), Equalizer(iBand)*ones(1,FrequencyBands(iBand,2) - FrequencyBands(iBand,1) + 1) , zeros(1,5)]), hold on, grid on
        
    end
    
    xlabel('f [Hz]') % do it also with the figHandler!
    ylabel('H_k(f)')
    
    title('Different equalizer Bands')
    
    axis([min(FrequencyBands(:,1)) - 5, max(FrequencyBands(:,2)) + 5, -0.5, 1.2])
    
end

if(flagRecord)

    RecordObj = audiorecorder(Fs, SampleBits, NChannels);

    disp('Schiaccia quando vuoi partire a registrare')
    pause
    recordblocking(RecordObj, 3);
    disp('Registrato!!!')
    disp('Schiaccia per risentire')
    pause
    disp('Riproduzione in corso dell''originale')
    RecordObj.play;

    if(flagSave)
        
        save(DBName, 'RecordObj')
        
    end

else
    
    load(DBName)

end
if(flagReproduceInput)
    disp('Sto per riprodurre il Segnale di partenza!')
    pause
    disp('Riproduzione Segnale di partenza')
    RecordObj.play;
end

x = RecordObj.getaudiodata;

NormBandPass = FrequencyBands/Fs;
BandFilteredSignals = zeros(size(NormBandPass,1), numel(x));

for iBand = 1:size(NormBandPass,1)

    [Num, Den] = butter(FilterOrder, 2*NormBandPass(iBand, :));
    % Num = fir1(FilterOrder, NormBandPass);
    % Den = 1;
    temp = filter(Num, Den, x.');
    BandFilteredSignals(iBand, :) = temp(1:numel(x));
end

Equalized = sum(BandFilteredSignals.*repmat(Equalizer, 1, size(BandFilteredSignals,2)), 1);

if(flagReproduceOutput)
    disp('Sto per riprodurre il Segnale Equalizzato!')
    pause
    disp('Riproduzione del Segnale Equalizzato!')

    NoisyAudio = audioplayer(Equalized, Fs);
    NoisyAudio.play;
end