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

% Last Modified by GUIDE v2.5 09-Apr-2014 11:43:16
% %%%%% Dr Richard Mitchell, latest version 09/04/2014
% (c) Richard Mitchell of University of Reading

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

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

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes FreqAsymPlot wait for user response (see UIRESUME)
% uiwait(handles.figure1);
set(handles.checkbox1,'Value', get(handles.checkbox1,'Max'));
                            % sets checkbox so by default use asymptotes
SetAsymText(handles);       % set text to that effect
setupsystem(handles);       % set up with default system - 1
set(handles.uitable2, 'visible', 'off');
                            % hide the table with results

% --- Outputs from this function are returned to the command line.
function varargout = FreqAsymPlot_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;



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (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 edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double
%   This is invoked when user changes system : to 1..n or 'u' or 'v'
setupsystem (handles);                      % get transfer function etc
set(handles.uitable2, 'visible', 'off');    % hide any results


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (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 edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (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 edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double

% Edit 2 is edit box where user enters min / max ang freqs
setshow(handles, 'on', 'on', 'on');
    % now set visible Edit box where enter data about asymptors/corner freqs


% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (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 edit4_Callback(hObject, eventdata, handles)
% hObject    handle to edit4 (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 edit4 as text
%        str2double(get(hObject,'String')) returns contents of edit4 as a double

% Edit4 is text box wher user enters data about teh next asymptote or corner freq
plotnext(handles);
    % As data just entered, replot asymptotes with latest data
    
% --- Executes during object creation, after setting all properties.
function edit4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit4 (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 pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (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 pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% user has specified 'undo'
[u, col] = getudata(handles);           % get data user entered
if col > 1                              % if at least one entered
    u(1, col-1) = 0;                    % mark the latest as empty
    set(handles.uipanel2, 'userdata', u);
    goplot(handles, u, col-1);          % now plot remaining asymptotes
    givehint(handles);
end


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

% User has pressed END button; so overlay asymptotes with actual Bode plot

[m, p, w] = bode(get(handles.text3, 'userdata'), get(handles.text4, 'userdata'));
        % get gain, phase and ang freq arrays
axes(handles.axes1);            % access Gain axes
hold on; ch = loglog(w,m, 'r'); set(ch, 'Linewidth', 2); hold off;
                                % and add actual gain plot
                                % Check if need to rescale graphs
yl = get(gca, 'ylim');                          % get current limits
if max(m) > max(yl), yl(2) = yl(2) * 10; end    % does actual have bigger gain
if min(m) < min(yl), yl(1) = yl(1) / 10; end    % or smaller
set(gca, 'ylim', yl);                           % set limits

axes(handles.axes2);            % access phase axes 
hold on; ch = semilogx(w,p, 'r'); set(ch, 'Linewidth', 2); hold off;
                                % superimpose actual phase
                                
setshow (handles, 'off', 'off', 'off');     % hide the data entry boxes/srings
[u, col] = getudata(handles);               % get  data user entered
set(handles.uitable2, 'Data', u(:,1:col)'); % copy into uitable2
set(handles.uitable2, 'visible', 'on');     % and show to user


function setupsystem (handles)
% Select system based on number in edit1; calling function in Freqystems.m
r = FreqSystems (2+round(str2num(get(handles.edit1, 'String'))), get(handles.edit8, 'String'));
setsys(handles, r.numstr, r.pnum, r.denstr, r.pden);
        % now add information into relevant GUI strings etc
uicontrol(handles.edit2);
        
function setsys (handles, nstr, npoly, dstr, dpoly)
% load the relevant messages/data into strings on the GUI
set(handles.text3, 'string', nstr);
set(handles.text3, 'userdata', npoly);
set(handles.text4, 'string', dstr);
set(handles.text4, 'userdata', dpoly);
axes(handles.axes1); cla;               % clear axes
axes(handles.axes2); cla;
setshow(handles, 'on', 'off', 'off')       % display/hide as appropriate
set(handles.uipanel2, 'userdata', zeros(3,10))  % zero data in the panel

function setshow(handles, offonwrange, offonwnext, offonbuttons)
% set visible/hidden for key text/edit boxes
set (handles.text5, 'visible', offonwrange) % message re range of w's
set (handles.edit2, 'visible', offonwrange) % edit box for ramnge of w's
set (handles.text7, 'visible', offonwnext)  % message for next w/asym
set (handles.edit4, 'visible', offonwnext)  % edit box for ditto
set (handles.text10, 'visible', offonwnext) % help for next input
set (handles.text13, 'visible', offonwnext) % hint message
if offonwnext, givehint(handles); uicontrol(handles.edit4); end
set (handles.pushbutton2, 'visible', offonbuttons)      % undo button
set (handles.pushbutton3, 'visible', offonbuttons)      % end button

function [u, col] = getudata(handles)
% scan matrix of user data in panel 2 for column which is empty
col = 1;
u = get(handles.uipanel2, 'userdata');
while u(1,col)>0
    col = col + 1;
end;

function givehint(handles)
% Give hint for adding next asymptote/corner freq
[u, col] = getudata(handles);
 if specifybyCFs(handles),      % if by corner freq
     if col == 1,               % first w is special ...
         hstr = 'Enter start freq, Asymptoptic Gain there, then 0 0';
     else
         hstr = 'Enter next corner freq (or the end freq), the gain, phase change and phase asym range there';
     end    
 else                           % if by asymptote
     if col == 1,
         hstr = 'Enter start freq and that for first corner freq, and the gain and slope of the asym';
     else
         hstr = ['Last asym ending at ', num2str(u(2, col-1)), ...
                  ' rad/s, was ', num2str(u(3, col-1)), ' * (jw)^', num2str(u(4, col-1))];
                  
     end
 end
set(handles.text13, 'string', hstr);        % display help string

function plotnext(handles)
% plot next asymptote ...
[u, col] = getudata(handles);                   % get data so far
newdata = str2num(get(handles.edit4, 'string'));
                % convert latest input from string to 4 element vector
if length(newdata) == 4
   u(1:4, col) = newdata';                  % add into u matrix
   set(handles.uipanel2, 'userdata', u);    % put back into panel user data
   goplot(handles, u, col);                 % plot latest asymptote
   set(handles.edit4, 'string', '');        % give hint for next one
   givehint(handles);
end   

function goplot(handles, u, col)
% u has data about the asymptotes ... use columns 1..col
wlim = str2num(get(handles.edit2, 'string'));   % get range of w's

if specifybyCFs(handles),                       % specify by corner freq
    % So each u is w, k, change in Phase, and Phase range
   if col==1, pchar = '*'; else pchar = '-'; end
        % for first one, just have data point so plot as *, else as line
        
   axes(handles.axes1);         % for gain graph
   ch = loglog(u(1, 1:col), u(2,1:col), pchar); set(ch, 'Linewidth', 2);
        % plot gain asymptotes from u matrix
   glim = log10([min(u(2, 1:col)), 1.05*max(u(2, 1:col))]);
        % calculate min/max values for setting x/y limits on graphs
   set(gca, 'xlim', wlim, 'ylim', 10.^[floor(glim(1)), ceil(glim(2))])

   axes(handles.axes2);         % for phase graph
   % for plotting these, as 'step' changes, need to duplicate values
   wp=u(1,1); pp=u(3,1);        % initial w and phase of asymptotes
   for ct = 2:col
     wp = [wp, u(1,ct), u(1, ct)];      % duplicate w
     pp = [pp, pp(end), pp(end)+u(3,ct)];   % add phase and phase+change
   end
   ch = semilogx(wp, pp, pchar); set(ch, 'Linewidth', 2);
                        % plot asymptotes
   if col > 1           % now look at adding RJM's extra phase asymptotes
       hold on
        for ct = 2:col
            if u(3,ct) ~= 0     % if change of phase at this CF 
                    % plot  w/sqrt(range)..w*sqrt(range), PH to PH+change
              ch = semilogx([u(1,ct) / sqrt(u(4,ct)), u(1,ct) * sqrt(u(4,ct))], ...
                       [pp(ct*2-2), pp(ct*2-1)], 'g');
              set(ch, 'Linewidth', 2);
            end  
        end
        hold off
   end    
else                        % if define by K*jw^n
                            % each u is w1 to w2, K, n
   axes(handles.axes1);             % for gain graph
   ws = [u(1,1), u(2, 1:col)];      % ws are first w1, remaining w2's
   gs = [u(3,1)*u(1,1)^u(4,1), u(3,1:col).*u(2, 1:col).^u(4, 1:col)];
                            % gains are w's raised to appropriate n * k
   ch = loglog(ws, gs); set(ch, 'Linewidth', 2);
                            % plot gain asymptotes then set ylims
   glim = log10([min(gs), 1.05*max(gs)]);
   set(gca, 'xlim', wlim, 'ylim', 10.^[floor(glim(1)), ceil(glim(2))])

   axes(handles.axes2);     % for phase graphs
   ws = reshape(u(1:2, 1:col), col*2, 1);
                            % need first w, middle ones duplicated, last w
   pp = 90*reshape([u(4, 1:col); u(4, 1:col)], col*2, 1);
                            % phase are the n's * 90
   ch = semilogx(ws, pp); set(ch, 'Linewidth', 2);
                            % plot phase asymptotes ...

end
if max(pp)-min(pp) < 180, yt = 45; else yt = 90; end
           % if phase overall 0..90, tick every 45deg, else every 90
set(gca, 'xlim', wlim, ...
         'ylim', [min(pp)-10, max(pp)+10], 'ytick', [min(pp):yt:max(pp)]);

function ans = specifybyCFs(handles)
ans = (get(handles.checkbox1,'Value') == get(handles.checkbox1,'Min'));

% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
axes(handles.axes1);
print -dmeta                % copy GUI to clip board

function edit7_Callback(hObject, eventdata, handles)
% hObject    handle to edit7 (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 edit7 as text
%        str2double(get(hObject,'String')) returns contents of edit7 as a double


% --- Executes during object creation, after setting all properties.
function edit7_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit7 (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 checkbox1.
function checkbox1_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox1
% this is checkbox wthether define by asymptote / corner freq
SetAsymText(handles);       % set help strings as appropriate

function SetAsymText(handles)
if specifybyCFs(handles),
    set (handles.text7, 'string', 'For each relevant w in turn, give w, asymptotic gain there, change in phase there,and range for extra phase asym');
    set (handles.uitable2, 'ColumnName', {'w', 'Gain', 'Phase', 'Range'});
else
    set (handles.text7, 'string', 'For each asym in turn, of form K*(jw)^n, give w start, w end, k and n');
    set (handles.uitable2, 'ColumnName', {'wstart', 'wend', 'k', 'n'});
end    

function edit8_Callback(hObject, eventdata, handles)
% hObject    handle to edit8 (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 edit8 as text
%        str2double(get(hObject,'String')) returns contents of edit8 as a double
setupsystem (handles);                      % get transfer function etc
set(handles.uitable2, 'visible', 'off');    % hide any results


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