function varargout = sim_exp(varargin)
% SIM_EXP Application M-file for sim_exp.fig
%    FIG = SIM_EXP launch sim_exp GUI.
%    SIM_EXP('callback_name', ...) invoke the named callback.

% Last Modified by GUIDE v2.0 20-Sep-2001 10:43:58

if nargin == 0  % LAUNCH GUI

	fig = openfig(mfilename,'reuse');

	% Generate a structure of handles to pass to callbacks, and store it. 
	handles = guihandles(fig);
	guidata(fig, handles);

	if nargout > 0
		varargout{1} = fig;
	end

elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK

	try
		[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
	catch
		disp(lasterr);
	end

end


%| ABOUT CALLBACKS:
%| GUIDE automatically appends subfunction prototypes to this file, and 
%| sets objects' callback properties to call them through the FEVAL 
%| switchyard above. This comment describes that mechanism.
%|
%| Each callback subfunction declaration has the following form:
%| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)
%|
%| The subfunction name is composed using the object's Tag and the 
%| callback type separated by '_', e.g. 'slider2_Callback',
%| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.
%|
%| H is the callback object's handle (obtained using GCBO).
%|
%| EVENTDATA is empty, but reserved for future use.
%|
%| HANDLES is a structure containing handles of components in GUI using
%| tags as fieldnames, e.g. handles.figure1, handles.slider2. This
%| structure is created at GUI startup using GUIHANDLES and stored in
%| the figure's application data using GUIDATA. A copy of the structure
%| is passed to each callback.  You can store additional information in
%| this structure at GUI startup, and you can change the structure
%| during callbacks.  Call guidata(h, handles) after changing your
%| copy to replace the stored original so that subsequent callbacks see
%| the updates. Type "help guihandles" and "help guidata" for more
%| information.
%|
%| VARARGIN contains any extra arguments you have passed to the
%| callback. Specify the extra arguments by editing the callback
%| property in the inspector. By default, GUIDE sets the property to:
%| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo))
%| Add any extra arguments after the last argument, before the final
%| closing parenthesis.


% --------------------------------------------------------------------
function varargout = Force_Callback(h, eventdata, handles, iforce)
% Stub for Callback of the uicontrol Force buttons; handles.forcebox(6) is this one

for i=1:6
    set(handles.forcebox(i),'Value',0)
end
    set(handles.forcebox(iforce),'Value',1)

    
% --------------------------------------------------------------------
function varargout = Run_Callback(h, eventdata, handles, iforce)
%  

fs=str2num(get(handles.Sample_rate,'String'))
N=str2num(get(handles.Npts,'String'))
Tburst=str2num(get(handles.Burst,'String'))       
F=str2num(get(handles.Forcemag,'String'))
i_antialias=get(handles.Antialiasing,'Value')+1
i_handle=get(handles.window,'Value')
numbits=str2num(get(handles.Numbits,'String'))
ymax=str2num(get(handles.Range,'String'))

define_m_c_k;

% define parameters 

seed = 1;
dt = 1/fs;
T = N*dt;

% define antialiasing filters
[b,a] = ellip(16,.1,60,2*pi*fs/2,'s'); % input bandlimiter

n = 3; % order of system
clear num den
for i=1:n+1
    for j=1:n+1
        if i==j 
            num{i,i}=b;
            den{i,i}=a;
        else
            num{i,j}=0;
            den{i,j}=1;
        end
    end
end

% put everything in the workspace for simulink (there's got to be an ealier way)
assignin('base','fs',fs);
assignin('base','N',N);
assignin('base','Tburst',Tburst)
assignin('base','F',F);
assignin('base','i_antialias',i_antialias);
assignin('base','num',num);
assignin('base','den',den);
assignin('base','dt',dt);
assignin('base','T',T);
assignin('base','C',C);
assignin('base','K',K);
assignin('base','M',M);
assignin('base','numbits',numbits);
assignin('base','ymax',ymax);
assignin('base','a',a);
assignin('base','b',b);


sim('simulated_exp',[0,T])

iclip=find(yout>ymax);
yout(iclip)=ymax;
iclip=find(yout<-ymax);
yout(iclip)=-ymax;

% junk for output so we can see if this is working

%window the data
if i_handle==1
    w=hann(N);
else
    w=boxcar(N);
end

for i = 1:n
    x=yout(1:N,i);
    f=force(1:N);
    if iforce==1
      f(1)=F;
      force(1)=F;
    end
    xw=x.*w;
    fw=f.*w;
    FX=fft(xw);
    FF=fft(fw);
    SXF=FF.*conj(FX);
    SXX=FX.*conj(FX);
    SFF=FF.*conj(FF);
    SFX=FX.*conj(FF);
    TXF=SXX./SXF;
    TXF2=SFX./SFF;
    lTXF2=length(TXF)/2;
    freq(:,i)=[0 ((1:lTXF2-1)/lTXF2/2/dt)]';
    TXF_p=TXF(1:lTXF2);
    mag(:,i)=abs(TXF_p);
    ang(:,i)=angle(TXF_p)*180/pi;
end

% Alternative way to Get Frequency Response Functions
%[tf1,ff1]=tfe(force(1:65536),xddot(1:65536,1),1024,1000,hanning(1024),512, 'mean');
%[tf2,ff2]=tfe(force(1:65536),xddot(1:65536,2),1024,1000,hanning(1024),512, 'mean');
%[tf3,ff3]=tfe(force(1:65536),xddot(1:65536,3),1024,1000,hanning(1024),512, 'mean');
%[tf4,ff4]=tfe(force(1:65536),xddot(1:65536,4),1024,1000,hanning(1024),512, 'mean');
%[tf5,ff5]=tfe(force(1:65536),xddot(1:65536,5),1024,1000,hanning(1024),512, 'mean');


%figure

axes(handles.frf_output)
i = get(handles.pick_signal,'value');
semilogy(freq(:,i),mag(:,i))
xlabel('Frequency')
ylabel('FRF magnitude')

axes(handles.time_output)
i=get(handles.pick_time,'value');
plot(time,yout(:,i))
xlabel('Time')
ylabel('Acceleration output')

axes(handles.force_output)
plot(time,force)
xlabel('Time')
ylabel('Force input')

varargout={mag ang freq time yout};


% --------------------------------------------------------------------
function varargout = pick_signal_Callback(h, eventdata, handles,freq,mag)
% Stub for Callback of the uicontrol handles.pick_signal.

axes(handles.frf_output)
i = get(handles.pick_signal,'value')'
semilogy(freq(:,i),mag(:,i))


% --------------------------------------------------------------------
function varargout = pick_time_Callback(h, eventdata, handles, time,yout)
% Stub for Callback of the uicontrol handles.pick_time.

axes(handles.time_output)
i = get(handles.pick_time,'value')'
plot(time,yout(:,i))




% --------------------------------------------------------------------
function varargout = checkbox10_Callback(h, eventdata, handles, varargin)
% Stub for Callback of the uicontrol handles.checkbox10.
disp('checkbox10 Callback not implemented yet.')


% --------------------------------------------------------------------
function varargout = checkbox11_Callback(h, eventdata, handles, varargin)
% Stub for Callback of the uicontrol handles.checkbox11.
disp('checkbox11 Callback not implemented yet.')


% --------------------------------------------------------------------
function varargout = slider2_Callback(h, eventdata, handles, varargin)
% Stub for Callback of the uicontrol handles.slider2.
disp('slider2 Callback not implemented yet.')


% --------------------------------------------------------------------
function varargout = slider3_Callback(h, eventdata, handles, varargin)
% Stub for Callback of the uicontrol handles.slider3.
disp('slider3 Callback not implemented yet.')


% --------------------------------------------------------------------
function varargout = edit8_Callback(h, eventdata, handles, varargin)
% Stub for Callback of the uicontrol handles.edit8.
disp('edit8 Callback not implemented yet.')