function varargout = Puretones(varargin)


%%%Dr. Ignacio Serrano-Pedraza 2018
%%%iserrano@ucm.es


% PURETONES MATLAB code for Puretones.fig
%      PURETONES, by itself, creates a new PURETONES or raises the existing
%      singleton*.
%
%      H = PURETONES returns the handle to a new PURETONES or the handle to
%      the existing singleton*.
%
%      PURETONES('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in PURETONES.M with the given input arguments.
%
%      PURETONES('Property','Value',...) creates a new PURETONES or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Puretones_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Puretones_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 Puretones

% Last Modified by GUIDE v2.5 14-Mar-2018 15:59:03

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @Puretones_OpeningFcn, ...
    'gui_OutputFcn',  @Puretones_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 Puretones is made visible.
function Puretones_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 Puretones (see VARARGIN)

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

% Play_sound handles structure
guidata(hObject, handles);
playsound=0;
Plot_figure(hObject, eventdata, handles,playsound)


function Plot_figure(hObject, eventdata, handles,playsound)
expt = getexpt(handles);

frecuenciamuestreo=expt.Framerate;
if expt.Duration<=0;expt.Duration=0.001;set(handles.Duration,'string',0.001);end
duracion=expt.Duration %seconds
t=[0:1/frecuenciamuestreo:duracion-(1/frecuenciamuestreo)]';
expt.Temporal_frequency=round(expt.freqslider);

if expt.Temporal_frequency==0;expt.Temporal_frequency=1;set(handles.Temporal_frequency,'string',1);end
if expt.amplitude<0;expt.amplitude=0;set(handles.Amplitude,'string',0);end


y=expt.amplitude*cos(2*pi*expt.Temporal_frequency*t+expt.PHASE);

axes(handles.Plot1);
cla;
plot(t,y,'b-');
title('Time plot')
xlabel('Time (msec)')
ylabel('Amplitude')
if expt.amplitude==0
axis([0 expt.ejeX -1 1])    
else
axis([0 expt.ejeX -(expt.amplitude+0.1*expt.amplitude) expt.amplitude+0.1*expt.amplitude])
end
if playsound==1
    sound(y,frecuenciamuestreo)
end

Y=fftshift(fft(y));
modulo=abs(Y)'*2*(1/length(y));
fase=angle(Y)';
n=length(y);
freq=(-fix(n/2):fix((n-1)/2))/duracion;

axes(handles.Plot2);
cla;

semilogx(freq([round(length(freq)/2+1):end]),modulo([round(length(freq)/2+1):end]),'b-');
title('Amplitude spectrum')
xlabel('Temporal frequency (Hz)')
ylabel('Amplitude')
if expt.amplitude==0
axis([20 15000 0 1])
else
axis([20 15000 0 expt.amplitude+0.2*expt.amplitude])
end
H=find(modulo==max(modulo));

axes(handles.Plot3);
cla;

if expt.PHASE==0
    semilogx([freq(H(2)) freq(H(2))],[fase(H(2)) fase(H(2))],'bo',[20 15000],[0 0],'b-');
else
    semilogx([freq(H(2)) freq(H(2))],[0 fase(H(2))],'b-',[20 15000],[0 0],'b-');
end

title('Phase spectrum')
xlabel('Temporal frequency (Hz)')
ylabel('Phase (rad)')
axis([20 15000 -2*pi 2*pi])


% --- Outputs from this function are returned to the command line.
function varargout = Puretones_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 button press in Play_sound.
function Play_sound_Callback(hObject, eventdata, handles)
% hObject    handle to Play_sound (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
playsound=1;
Plot_figure(hObject, eventdata, handles,playsound)



% --------------------------------------------------------------------
function OpenMenuItem_Callback(hObject, eventdata, handles)
% hObject    handle to OpenMenuItem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
file = uigetfile('*.fig');
if ~isequal(file, 0)
    open(file);
end


% --- Executes during object creation, after setting all properties.
function Amplitude_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Amplitude (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called
function Amplitude_Callback(hObject, eventdata, handles)
playsound=0;
Plot_figure(hObject, eventdata, handles,playsound)

function expt = getexpt(handles)
% Reads off key data from GUI
%expt = handles.expt;
A = get(handles.Amplitude,'string');
expt.amplitude = str2double(A);
TF = get(handles.Temporal_frequency,'string');
expt.Temporal_frequency = str2double(TF);
PHASE = get(handles.Phase,'string');
expt.PHASE = str2double(PHASE);
Duration = get(handles.Duration,'string');
expt.Duration = str2double(Duration);
Framerate = get(handles.Framerate,'string');
expt.Framerate = str2double(Framerate);
expt.ejeX = get(handles.axisX,'value');
expt.freqslider = get(handles.Freqslider,'value');



function Temporal_frequency_Callback(hObject, eventdata, handles)

expt = getexpt(handles);
set(handles.Freqslider,'Value',expt.Temporal_frequency);
playsound=0;
Plot_figure(hObject, eventdata, handles,playsound)
% --- Executes during object creation, after setting all properties.
function Temporal_frequency_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Temporal_frequency (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



function Phase_Callback(hObject, eventdata, handles)
% hObject    handle to Phase (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 Phase as text
%        str2double(get(hObject,'String')) returns contents of Phase as a double
playsound=0;
Plot_figure(hObject, eventdata, handles,playsound)


% --- Executes during object creation, after setting all properties.
function Phase_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Phase (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 Plot_figure.
function Plot_figure_Callback(hObject, eventdata, handles)
% hObject    handle to Plot_figure (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
playsound=0;
Plot_figure(hObject, eventdata, handles,playsound)



function Duration_Callback(hObject, eventdata, handles)
% hObject    handle to Duration (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 Duration as text
%        str2double(get(hObject,'String')) returns contents of Duration as a double
playsound=0;
Plot_figure(hObject, eventdata, handles,playsound)


% --- Executes during object creation, after setting all properties.
function Duration_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Duration (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



function Framerate_Callback(hObject, eventdata, handles)
% hObject    handle to Framerate (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 Framerate as text
%        str2double(get(hObject,'String')) returns contents of Framerate as a double
playsound=0;
Plot_figure(hObject, eventdata, handles,playsound)


% --- Executes during object creation, after setting all properties.
function Framerate_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Framerate (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
function CloseMenuItem_Callback(hObject, eventdata, handles)
% hObject    handle to CloseMenuItem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
selection = questdlg(['Close ' get(handles.axixX,'Name') '?'],...
    ['Close ' get(handles.axixX,'Name') '...'],...
    'Yes','No','Yes');
if strcmp(selection,'No')
    return;
end

delete(handles.axixX)
% --------------------------------------------------------------------
function PrintMenuItem_Callback(hObject, eventdata, handles)
% hObject    handle to PrintMenuItem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
printdlg(handles.axixX)

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


% --- Executes on button press in Reset.
function Reset_Callback(hObject, eventdata, handles)
% hObject    handle to Reset (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


set(handles.Amplitude, 'String', 1);
set(handles.Temporal_frequency,  'String', 1000);
set(handles.Phase, 'String', 0);
set(handles.Duration, 'String', 1);
set(handles.Framerate, 'String', 44100);
set(handles.axisX,'Value',0.002);
set(handles.Freqslider,'Value',1000);
playsound=0;
Plot_figure(hObject, eventdata, handles,playsound)






% --- Executes on slider movement.
function axisX_Callback(hObject, eventdata, handles)
% hObject    handle to axisX (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%get(hObject,'Value')
% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
playsound=0;
Plot_figure(hObject, eventdata, handles,playsound)


% --- Executes during object creation, after setting all properties.
function axisX_CreateFcn(hObject, eventdata, handles)
% hObject    handle to axisX (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


% --- Executes on slider movement.
function Freqslider_Callback(hObject, eventdata, handles)

expt = getexpt(handles);
set(handles.Temporal_frequency,'String',expt.freqslider);
playsound=0;
Plot_figure(hObject, eventdata, handles,playsound)


% --- Executes during object creation, after setting all properties.
function Freqslider_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Freqslider (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
