% SNR állandóságára kiváló demo: music.wav elsõ 400ms-a, 5 bites lin és log
% kavtáló esetén->látható, hogy a log kvantáló itt is kevés zajt csinál,
% cserébe nagyobb a zaj ott, ahol teljesen kivezérelt a jel (ilet is találhatsz
% a music.wav vége felé,ott a lin kvantáló jobb)
function varargout = sin_kvant(varargin)
% SIN_KVANT M-file for sin_kvant.fig
%      SIN_KVANT, by itself, creates a new SIN_KVANT or raises the existing
%      singleton*.
%
%      H = SIN_KVANT returns the handle to a new SIN_KVANT or the handle to
%      the existing singleton*.
%
%      SIN_KVANT('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SIN_KVANT.M with the given input arguments.
%
%      SIN_KVANT('Property','Value',...) creates a new SIN_KVANT or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before sin_kvant_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to sin_kvant_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help sin_kvant

% Last Modified by GUIDE v2.5 23-Feb-2010 10:49:58

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @sin_kvant_OpeningFcn, ...
                   'gui_OutputFcn',  @sin_kvant_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT



% --- Executes just before sin_kvant is made visible.
function sin_kvant_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to sin_kvant (see VARARGIN)
global F % a szinusz frekvenciája
global T % a jel hossza (lejátszás miatt fontos
global fs % default mintavételi frekvencia
global fs_cont % ezzel a mintavétellel folytonosnak tekintjük
global quant_mod % a kavntálási mód változója
global n % a kvantálási bitszám változója
global sampled % a mintavett jel (vektor alakban)
global sampled_handle % a mintavett jel line plotjának handle-je
global quantized_handle % a kvantált jel line plotjának handle-je
global cont_handle % folyt. jel line plotjának handle-je
global player % a lejátszó
global nyquist_handle % a Nyquist frekvenciát jelölõ diracdelta
global sampledspec_handle % a mintavett jel spektruma plotjának handle-je
global quantizedspec_handle % a kvantált jel spektruma plotjának handle-je
global contspec_handle % folyt. jel spektruma plotjának handle-je
F = 1500;
T = 3; % a jel hossza (sec), predefined value
fs = 6000;
fs_cont = 44100; % ezzel a mintavételi frekkel tekintem folytonos jelnek
quant_mod = 'non';
n = 16;
signal = @(t) 1*sin(F*2*pi*t);
t = 0 : 1/fs : T;
t_cont = 0 : 1/fs_cont : T;
sampled = signal(t);
player = audioplayer(sampled,fs);

% ábrázolás
cont_handle = line(t_cont,signal(t_cont),'Parent',handles.axes1,'Color',[1 0 0],'LineStyle',':');
% set(handles.axes1,'xlim',[0 1/F*10],'ylim',[-.35 .35])
set(handles.axes1,'xlim',[0 1/F*5],'ylim',[-1.05 1.05])
sampled_handle = line(t,sampled,'Parent',handles.axes1,'Color',[0 1 0]);
quantized_handle = line(t,sampled,'Parent',handles.axes1); % nincs kvantálás->kvantált megegyezik a mintavettel
set(get(handles.axes1,'XLabel'),'String','Idõ [s]')

% folytonos spektrum
Xf=1/length(t_cont)*fft(signal(t_cont));
f=0:1/T:fs_cont;
contspec_handle = line(f(1:round(length(f)/2)),abs(Xf(1:round(length(f)/2))),'Parent',handles.axes_contspec);
set(handles.axes_contspec,'XLim',[0, f(round(length(f)/2))+f(round(length(f)/2))*0.05]);
set(get(handles.axes_contspec,'XLabel'),'String','Frekvencia [Hz]')

% mintavett spektrum
Xfm=1/length(sampled)*fft(sampled,length(sampled));
fm=0:1/T:fs;
quantizedspec_handle = stem(handles.axes_sampledspec,fm(1:end),2*abs(Xfm)); hold on
sampledspec_handle = stem(handles.axes_sampledspec,fm(1:end),2*abs(Xfm),'Color',[0 1 0]); 
set(get(handles.axes_sampledspec,'XLabel'),'String','Frekvencia [Hz]')
maxXfm=max(abs(Xfm));
nyquist_handle = line([fs/2,fs/2],[0,maxXfm],'Parent',handles.axes_sampledspec,'LineWidth',2,'Color',[0 0 0]);

set(handles.edit_sinfrek,'String',F)
set(handles.slider_fs,'Min',1)
set(handles.slider_fs,'Max',fs)
set(handles.slider_fs,'Value',fs)
set(handles.text_fs,'String',sprintf('fs = %0.1f Hz',fs))

% Choose default command line output for sin_kvant
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes sin_kvant wait for user response (see UIRESUME)
% uiwait(handles.main_figure);

function update_everything(handles)
% ez az eljárás mintavételez és kvantál az akutális paraméterek alapján.
% Minden egyes változás után ezt a függvénbyt kell meghívni!
global F % a szinusz frekvenciája
global T % a jel hossza (lejátszás miatt fontos
global fs_cont % ezzel a mintavétellel folytonosnak tekintjük
global fs % default mintavételi frekvencia
global quant_mod % a kavntálási mód változója
global n % a kvantálási bitszám változója
global sampled % a mintavett jel (vektor alakban)
global cont_handle % folyt. jel line plotjának handle-je
global sampled_handle % a mintavett jel line plotjának handle-je
global quantized_handle % a kvantált jel line plotjának handle-je
global player % a lejátszó
global nyquist_handle % a Nyquist frekvenciát jelölõ diracdelta
global contspec_handle % folyt. jel spektruma plotjának handle-je
global sampledspec_handle % a mintavett jel spektruma plotjának handle-je
global quantizedspec_handle % a kvantált jel spektruma plotjának handle-je

if get(handles.button_ps,'Value') == get(handles.button_ps,'Max')
	% lejátszás leállítása
    set(handles.button_ps,'Value',get(handles.button_ps,'Min'))
    set(handles.button_ps,'String','Lejátszás')
    stop(player)
end

% A FOLYTONOS JEL
t_cont = 0 : 1/fs_cont : T;
signal = @(t) 1*sin(F*2*pi*t);
% ábrázolás
set(cont_handle,'XData',t_cont,'YData',signal(t_cont))
% folytonos spektrum
Xf=1/length(t_cont)*fft(signal(t_cont),length(t_cont));
f=0:1/T:(fs_cont);
set(contspec_handle,'XData',f(1:round(length(f)/2)),'YData',abs(Xf(1:round(length(f)/2))))
set(handles.axes_contspec,'XLim',[0, f(round(length(f)/2))+f(round(length(f)/2))*0.05]);


% MINTAVÉTELEZÉS
t = 0 : 1/fs : T;
sampled = signal(t);
% ábrázolás
set(sampled_handle,'XData',t,'YData',sampled(1:numel(t)))
% mintavett spektrum (kiszámolás + ábrázolás)
Xfm=1/length(sampled)*fft(sampled,length(sampled));
fm=0:1/T:fs;
set(sampledspec_handle,'XData',fm(1:end),'YData',2*abs(Xfm))
maxXfm=max(abs(Xfm));
set(nyquist_handle,'XData',[fs/2,fs/2],'YData',[0,maxXfm])


% KVANTÁLÁS
switch quant_mod
    case 'linear'
        quantized = quantify2(sampled, n, 0, 'sym', 1);
    case 'log_A '
        quantized = quantify2(sampled, n, 1, 'sym', 1);
    case 'log_mu'
        quantized = quantify2(sampled, n, 2, 'sym', 1);
    otherwise
        quantized = sampled; % nincs kvantálás
end
% ábrázolás
set(quantized_handle,'XData',t,'YData',quantized(1:numel(t)))
% kvantált jel spektruma (kiszámolás + ábrázolás)
Xfk=1/length(quantized)*fft(quantized,length(quantized));
set(quantizedspec_handle,'XData',fm(1:end),'YData',2*abs(Xfk))

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% KVANTÁLÁSI JEL-ZAJ VISZONY MEGHATÁROZÁSA %%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


% mintavett jel energiája
jelenergia = 1;

% kvantáltási zaj energiája
zajenergia = 1;

estSNR = 1;

% kiszámolt értéket a handles.text_SNR szövegmezõn lehet megjeleníteni a
% következõ módon: 
set(handles.text_SNR,'String',sprintf('Becsült SNR:\n%0.3f dB',estSNR))
% ahol a kiszámolt értéknek a estSNR változóban kell lennie és az float
% formátumban, 3 tizedesjegy pontossággal kerül majd ábrázolásra


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% KVANTÁLÁSI JEL-ZAJ VISZONY MEGHATÁROZÁSA %%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VÉGE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


% LEJÁTSZÓ
player = audioplayer(quantized,fs);

% --- Outputs from this function are returned to the command line.
function varargout = sin_kvant_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;



% --- Executes on slider movement.
function slider_fs_Callback(hObject, eventdata, handles)
% hObject    handle to slider_fs (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
global fs
fs = get(hObject,'Value');
set(handles.text_fs,'String',sprintf('fs = %0.1f Hz',fs))
update_everything(handles);



% --- Executes during object creation, after setting all properties.
function slider_fs_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider_fs (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end



function edit_sinfrek_Callback(hObject, eventdata, handles)
% hObject    handle to edit_sinfrek (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_sinfrek as text
%        str2double(get(hObject,'String')) returns contents of edit_sinfrek as a double
global F
F = str2double(get(hObject,'String'));
update_everything(handles)



% --- Executes during object creation, after setting all properties.
function edit_sinfrek_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_sinfrek (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes on button press in button_ps.
function button_ps_Callback(hObject, eventdata, handles)
% hObject    handle to button_ps (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global player
button_state = get(hObject,'Value');
if button_state == get(hObject,'Max')
	% Toggle button is pressed-take approperiate action
    play(player)
    set(hObject,'String','Leállítás')
elseif button_state == get(hObject,'Min')
	% Toggle button is not pressed-take appropriate action
    stop(player)
    set(hObject,'String','Lejátszás')
end


% --- Executes on selection change in popupmenu_kvantmod.
function popupmenu_kvantmod_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_kvantmod (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu_kvantmod contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_kvantmod
global quant_mod
kvantmods = get(hObject,'String');
selected = get(hObject,'Value');
quant_mod = kvantmods(selected,:);
update_everything(handles)



% --- Executes during object creation, after setting all properties.
function popupmenu_kvantmod_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_kvantmod (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in popupmenu_n.
function popupmenu_n_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_n (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu_n contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_n
global n % a kvantálási bitszám változója
kvantbitnum = str2double(get(handles.popupmenu_n,'String'));
n = kvantbitnum(get(handles.popupmenu_n,'Value')); % kvantálási bitszám
update_everything(handles)


% --- Executes during object creation, after setting all properties.
function popupmenu_n_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_n (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


