
sampleRate = 44100;
recordBits = 16;

normalNoise = 0.2 * 10^-2;

recordTime = 1;

%Meassure the noise
recObject = audiorecorder(sampleRate, recordBits, 1);

fprintf('Meassuring noise\n');
recordblocking(recObject, recordTime);
noiseRecording = getaudiodata(recObject);

flatNoise = abs(noiseRecording);
avgNoise = mean(flatNoise);

if(avgNoise > normalNoise)
    fprintf('Unusually high noise level\n');
    fprintf('Did you move the pipe or table it is on?\n');

    figure(1);
    plot(noiseRecording);
    title('recorded noise');

    error('Too much noise');
elseif(avgNoise == 0)
    fprintf('No sound recorded. Make sure the microphone is plugged\n');

    error('No sound recorded.');
else
    fprintf('Noise is normal\n');
end

%Testing speakers
fprintf('Testing speaker\n');

amplitude = 2;
soundFreq = 1000;
playTime = 1;

[fftMagnitude, soundPart, filteredPart, audioData, ampFiltered, amplitudeResult, amplitudeResult2] = testFrequency(recObject, amplitude, soundFreq, playTime, sampleRate);


figure(1);
subplot(1,1,1);
plot(audioData);
title('Recorded sound');


if(amplitudeResult2 < normalNoise * 2)
    fprintf('No sound recorded or recorded amplitude to low\n');
    fprintf('Make sure the speaker and microphone are plugged into the correct ports and that the system volume is high enough/n');
    fprintf('Look at the raw sound plot to help find the problem\n');


    error('Only noise recorded');
else
    fprintf('Speaker works\n');
end

%{
fprintf('Testing byte transmission\n');
%Testing data transmission
transResult = encoding([2756, 5512], 2, 0);

%if more than 5% of symbols failed to transmit
if(transResult >= 5)
    fprintf('More than 5 percent errors when transmitting data\n');
    
    error('Not enough data arrived');
else
    fprintf('Data transmision works\n');
end
%}

fprintf('Tests done, everything works\n');
