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

% Copyright 2002-2003 The MathWorks, Inc.

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

% Last Modified by GUIDE v2.5 07-Dec-2007 09:40:52

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

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

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Robust_sys wait for user response (see UIRESUME)
% uiwait(handles.figure1);

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

% --- 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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
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

% --- 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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit3 (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
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

% --- 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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function edit5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit5 (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function edit6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit6 (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
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

% --- 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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function edit9_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit9 (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function edit10_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit10 (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function edit11_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit11 (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function edit12_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit12 (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
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)

x1 = str2double(get(handles.edit1,'String'));
x2= str2double(get(handles.edit2,'String'));
x3= str2double(get(handles.edit3,'String'));
x4= str2double(get(handles.edit4,'String'));

x5 = str2double(get(handles.edit5,'String'));
x6 = str2double(get(handles.edit6,'String'));
x7 = str2double(get(handles.edit7,'String'));
x8 = str2double(get(handles.edit8,'String'));

x9 = str2double(get(handles.edit9,'String'));
x10 = str2double(get(handles.edit10,'String'));
x11 = str2double(get(handles.edit11,'String'));
x12 = str2double(get(handles.edit12,'String'));

A=[x1,x2;x3,x4];
B=[x5,x6;x7,x8];
C=[x9,x10;x11,x12];
D=0;
[h2n] = normh2(A,B,C,D);

set(handles.text3,'String',num2str(h2n))
% --- 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)
x1 = str2double(get(handles.edit1,'String'));
x2= str2double(get(handles.edit2,'String'));
x3= str2double(get(handles.edit3,'String'));
x4= str2double(get(handles.edit4,'String'));

x5 = str2double(get(handles.edit5,'String'));
x6 = str2double(get(handles.edit6,'String'));
x7 = str2double(get(handles.edit7,'String'));
x8 = str2double(get(handles.edit8,'String'));

x9 = str2double(get(handles.edit9,'String'));
x10 = str2double(get(handles.edit10,'String'));
x11 = str2double(get(handles.edit11,'String'));
x12 = str2double(get(handles.edit12,'String'));

A=[x1,x2;x3,x4]
B=[x5,x6;x7,x8]
C=[x9,x10;x11,x12]
D=0;
[hinfn] = normhinf(A,B,C,D);
set(handles.text4,'String',num2str(hinfn))


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

% Last Modified by GUIDE v2.5 30-Oct-2014 21:31:32

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

% Choose default command line output for ma_AerobrakingCdCalcGUI
handles.output = hObject;
handles.ma_MainGUI = varargin{1};

%GUI setup
populateBodiesCombo(getappdata(handles.ma_MainGUI,'celBodyData'), handles.bodiesCombo);
dragModelCombo_Callback(handles.dragModelCombo, [], handles);

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = ma_AerobrakingCdCalcGUI_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 selection change in bodiesCombo.
function bodiesCombo_Callback(hObject, eventdata, handles)
% hObject    handle to bodiesCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns bodiesCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from bodiesCombo

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

function preAeroRpText_Callback(hObject, eventdata, handles)
% hObject    handle to preAeroSmaText (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 preAeroSmaText as text
%        str2double(get(hObject,'String')) returns contents of preAeroSmaText as a double
newInput = get(hObject,'String');
newInput = attemptStrEval(newInput);
set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function preAeroRpText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to preAeroSmaText (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 preAeroSmaText_Callback(hObject, eventdata, handles)
% hObject    handle to preAeroSmaText (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 preAeroSmaText as text
%        str2double(get(hObject,'String')) returns contents of preAeroSmaText as a double
newInput = get(hObject,'String');
newInput = attemptStrEval(newInput);
set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function preAeroSmaText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to preAeroSmaText (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 postAeroSmaText_Callback(hObject, eventdata, handles)
% hObject    handle to postAeroSmaText (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 postAeroSmaText as text
%        str2double(get(hObject,'String')) returns contents of postAeroSmaText as a double
newInput = get(hObject,'String');
newInput = attemptStrEval(newInput);
set(hObject,'String', newInput);

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

% --- Executes during object creation, after setting all properties.
function dragCoeffAnsText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to dragCoeffAnsText (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 calcCdButton.
function calcCdButton_Callback(hObject, eventdata, handles)
% hObject    handle to calcCdButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    set(handles.dragCoeffAnsText,'String','<Computing>'); drawnow;

    errMsg = validateInputs(handles);

    if(isempty(errMsg))
        computeDragCoefficient(handles);
    else
        set(handles.dragCoeffAnsText,'String','');
        msgbox(errMsg,'Errors were found while computing the drag coefficient.','error');
    end

function errMsg = validateInputs(handles)
    errMsg = {};

    rawDouble = str2double(get(handles.preAeroRpText,'String'));
    enteredStr = get(handles.preAeroSmaText,'String');
    numberName = 'Pre-Aerobrake Periapsis Altitude';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(rawDouble, numberName, lb, ub, isInt, errMsg, enteredStr);

    rawDouble = str2double(get(handles.preAeroSmaText,'String'));
    enteredStr = get(handles.preAeroSmaText,'String');
    numberName = 'Pre-Aerobrake Semi-major Axis';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(rawDouble, numberName, lb, ub, isInt, errMsg, enteredStr);

    rawDouble = str2double(get(handles.postAeroSmaText,'String'));
    enteredStr = get(handles.postAeroSmaText,'String');
    numberName = 'Post-Aerobrake Semi-major Axis';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(rawDouble, numberName, lb, ub, isInt, errMsg, enteredStr);

    rawDouble = str2double(get(handles.incText,'String'));
    enteredStr = get(handles.incText,'String');
    numberName = 'Orbital Inclination';
    lb = 0;
    ub = 180;
    isInt = false;
    errMsg = validateNumber(rawDouble, numberName, lb, ub, isInt, errMsg, enteredStr);

	contents = cellstr(get(handles.dragModelCombo,'String'));
	dragModel = contents{get(handles.dragModelCombo,'Value')};

    if(~strcmpi(dragModel,'Stock'))
        rawDouble = str2double(get(handles.preAeroMass,'String'));
        enteredStr = get(handles.preAeroMass,'String');
        numberName = 'Pre-Aerobraking Mass';
        lb = eps;
        ub = Inf;
        isInt = false;
        errMsg = validateNumber(rawDouble, numberName, lb, ub, isInt, errMsg, enteredStr);
    end

    celBodyData = getappdata(handles.ma_MainGUI,'celBodyData');

    contents = cellstr(get(handles.bodiesCombo,'String'));
	selBody = contents{get(handles.bodiesCombo,'Value')};
    bodyInfo = celBodyData.(strtrim(lower(selBody)));

    preSMA = str2double(get(handles.preAeroSmaText,'String'));
    postSMA = str2double(get(handles.postAeroSmaText,'String'));

    preEnergy = -bodyInfo.gm/(2*preSMA);
    postEnergy = -bodyInfo.gm/(2*postSMA);
    if(postEnergy >= preEnergy)
        errMsg{end+1} = 'The entered post-aerobrake SMA does not represent a loss in orbital energy w.r.t. the pre-aerobrake SMA.  Your orbital energy must decrease through the aerobrake.';
    end

    preRpAlt = str2double(get(handles.preAeroRpText,'String'));
    if(preRpAlt >= bodyInfo.atmohgt)
        errMsg{end+1} = sprintf('Pre-Aerobrake Periapsis is located outside the atmosphere (%f km).  Lower the  pre-aerobrake periapsis altitude to below %f km and above 0 km.', bodyInfo.atmohgt, bodyInfo.atmohgt);
    end

function computeDragCoefficient(handles)
    celBodyData = getappdata(handles.ma_MainGUI,'celBodyData');

    contents = cellstr(get(handles.dragModelCombo,'String'));
	dragModel = contents{get(handles.dragModelCombo,'Value')};

    contents = cellstr(get(handles.bodiesCombo,'String'));
	selBody = contents{get(handles.bodiesCombo,'Value')};
    bodyInfo = celBodyData.(strtrim(lower(selBody)));

    preRp = str2double(get(handles.preAeroRpText,'String')) + bodyInfo.radius;
    preSMA = str2double(get(handles.preAeroSmaText,'String'));
    postSMA = str2double(get(handles.postAeroSmaText,'String'));
    inc = deg2rad(str2double(get(handles.incText,'String')));
    mass = str2double(get(handles.preAeroMass,'String'));

    preEcc = getEccFromRpAndSma(preSMA, preRp);   %we assume that Rp remains constant

    raan = 0; %arbitary here
    arg = 0;  %arbitary here
    tru = -computeTrueAFromRadiusEcc(bodyInfo.radius+bodyInfo.atmohgt, preSMA, preEcc)-0.001;  %NOT ARBITRARY, SET JUST OUTSIDE ATMOSPHERE

    [rVect,vVectPre]=getStatefromKepler(preSMA, preEcc, inc, raan, arg, tru, bodyInfo.gm);
%     [~,vVectPost]=getStatefromKepler(postSMA, postEcc, inc, raan, arg, tru, bodyInfo.gm);
    %%%
    initialState = buildInitialState(rVect, vVectPre, mass, bodyInfo.id);
    aeroFun = @(dragCoeff) aerobrakeFunc(dragCoeff, initialState, dragModel, postSMA, bodyInfo.gm, celBodyData);

    if(strcmpi(dragModel,'Stock'))
        x0 = 10;
    else
        x0 = 10;
    end

    options = optimset('Display','iter');
    set(handles.dragCoeffAnsText,'Enable','off');
    [Cd, ~, exitflag, ~] = fzero(aeroFun, x0, options);
    Cd = abs(Cd);

    if(exitflag < 0)
        set(handles.dragCoeffAnsText,'String', '<Error>');
        set(handles.dragCoeffAnsText,'Enable','on');
    else
        set(handles.dragCoeffAnsText,'String', num2str(Cd, 10));
        set(handles.dragCoeffAnsText,'Enable','on');
    end

function dEnergy = aerobrakeFunc(dragCoeff, initialState, dragModel, postSMADesired, gmu, celBodyData)
    dragCoeff = abs(dragCoeff);

    aerobrake = ma_createAerobrake('NA', dragCoeff, dragModel, 'r', '-', 1.5);
    eventLog = ma_executeAerobrake(initialState, -1, aerobrake, celBodyData);

    newRVect = eventLog(end,2:4);
    newVVect = eventLog(end,5:7);
    [postSMAActual, ~, ~, ~, ~, ~] = getKeplerFromState(newRVect,newVVect,gmu);

    desiredEnergy = getSpecOrbitEnergyFromSma(postSMADesired, gmu);
    actEnergy = getSpecOrbitEnergyFromSma(postSMAActual, gmu);

    dEnergy = actEnergy - desiredEnergy;

function initialState = buildInitialState(rVect, vVect, mass, bodyId)
    rVect = reshape(rVect,1,3);
    vVect = reshape(vVect,1,3);

    initialState = zeros(1,13);
    initialState(1,:) = [0 rVect vVect bodyId mass 0 0 0 1];

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

% --- Executes on key press with focus on ma_AerobrakingCdCalcGUI or any of its controls.
function ma_AerobrakingCdCalcGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to ma_AerobrakingCdCalcGUI (see GCBO)
% eventdata  structure with the following fields (see FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'return'
            calcCdButton_Callback(handles.calcCdButton, [], handles);
        case 'enter'
            calcCdButton_Callback(handles.calcCdButton, [], handles);
        case 'escape'
            close(handles.ma_AerobrakingCdCalcGUI);
    end

function incText_Callback(hObject, eventdata, handles)
% hObject    handle to incText (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 incText as text
%        str2double(get(hObject,'String')) returns contents of incText as a double
newInput = get(hObject,'String');
newInput = attemptStrEval(newInput);
set(hObject,'String', newInput);

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

% Hints: contents = cellstr(get(hObject,'String')) returns dragModelCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from dragModelCombo
    contents = cellstr(get(hObject,'String'));
    dragModel = contents{get(hObject,'Value')};

    if(strcmpi(dragModel,'Stock'))
%         set(handles.preAeroMass,'Enable','off');
%         set(handles.cdLabel,'String','');
        set(handles.preAeroMass,'Enable','on');
        set(handles.cdLabel,'String','m^2');
    elseif(strcmpi(dragModel,'FAR'))
        set(handles.preAeroMass,'Enable','on');
        set(handles.cdLabel,'String','m^2');
    elseif(strcmpi(dragModel,'NEAR'))
        set(handles.preAeroMass,'Enable','on');
        set(handles.cdLabel,'String','m^2');
    else
        error(['Invalid drag model in aerobraking DV calculations: ', dragModel]);
    end

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

function preAeroMass_Callback(hObject, eventdata, handles)
% hObject    handle to preAeroMass (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 preAeroMass as text
%        str2double(get(hObject,'String')) returns contents of preAeroMass as a double
newInput = get(hObject,'String');
newInput = attemptStrEval(newInput);
set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function preAeroMass_CreateFcn(hObject, eventdata, handles)
% hObject    handle to preAeroMass (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 Callbacks_glottal_pulse_GUI25(f,C)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x=C{1,1};
y=C{1,2};
a=C{1,3};
b=C{1,4};
u=C{1,5};
v=C{1,6};
m=C{1,7};
n=C{1,8};
lengthbutton=C{1,9};
widthbutton=C{1,10};
enterType=C{1,11};
enterString=C{1,12};
enterLabel=C{1,13};
noPanels=C{1,14};
noGraphicPanels=C{1,15};
noButtons=C{1,16};
labelDist=C{1,17};%distance that the label is below the button
noTitles=C{1,18};
buttonTextSize=C{1,19};
labelTextSize=C{1,20};
textboxFont=C{1,21};
textboxString=C{1,22};
textboxWeight=C{1,23};
textboxAngle=C{1,24};
labelHeight=C{1,25};
fileName=C{1,26};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%PANELS
for j=0:noPanels-1
uipanel('Parent',f,...
'Units','Normalized',...
'Position',[x(1+4*j) y(1+4*j) x(2+4*j)-x(1+4*j) y(3+4*j)-y(2+4*j)]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%GRAPHIC PANELS
for i=0:noGraphicPanels-1
switch (i+1)
case 1
graphicPanel1 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 2
graphicPanel2 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 3
graphicPanel3 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 4
graphicPanel4 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 5
graphicPanel5 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%TITLE BOXES
for k=0:noTitles-1
switch (k+1)
case 1
titleBox1 = uicontrol('parent',f,...
'Units','Normalized',...
'Position',[u(1+4*k) v(1+4*k) u(2+4*k)-u(1+4*k) v(3+4*k)-v(2+4*k)],...
'Style','text',...
'FontSize',textboxFont{k+1},...
'String',textboxString(k+1),...
'FontWeight',textboxWeight{k+1},...
'FontAngle',textboxAngle{k+1});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%BUTTONS
for i=0:(noButtons-1)
enterColor='w';
if strcmp(enterType{i+1},'pushbutton')==1 ||strcmp(enterType{i+1},'text')==1
enterColor='default';
end
if (strcmp(enterLabel{1,(i+1)},'')==0 &&...
        strcmp(enterLabel{1,(i+1)},'...')==0) %i.e. there is a label
%creating a label for some buttons
uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i)-labelDist-labelHeight(i+1) ...
(m(2+2*i)-m(1+2*i)) labelHeight(i+1)],...
'Style','text',...
'String',enterLabel{i+1},...
'FontSize', labelTextSize(i+1),...
'HorizontalAlignment','center');
end
switch (i+1)
case 1
button1=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button1Callback);
case 2
button2=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button2Callback);
case 3
button3=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button3Callback);
case 4
button4=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button4Callback);
case 5
button5=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button5Callback);
case 6
button6=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button6Callback);
case 7
button7=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button7Callback);
case 8
button8=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button8Callback);
case 9
button9=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button9Callback);
end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%USER CODE FOR THE VARIABLES AND CALLBACKS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize Variables
alpha1=25;
alpha2=10;
period=100;
nfft=1024;
fs=10000;
ivowel=1;
fsd=10000;
imp_train=[];
pulse_train=[];
zout=[];
g=[];
vowels='IY';

% Name the GUI
    set(f,'Name','glottal_pulse_GUI');

% CALLBACKS
% Callback for button1 -- alpha1, editable button value for glottal pulse
% opening cycle (in %)
 function button1Callback(h,eventdata)
     alpha1=str2num(get(button1,'string'))/100;
     if alpha1 < 0
         waitfor(msgbox('alpha1 must lie between 0 and 100'));
     elseif alpha1 > 1
         waitfor(msgbox('alpha1 must lie between 0 and 100'));
     end
 end

% Callback for button2 -- alpha2, editable button value for glottal pulse
% closing cycle (in %)
 function button2Callback(h,eventdata)
     alpha2=str2num(get(button2,'string'))/100;
     if alpha2 < 0
         waitfor(msgbox('alpha2 must lie between 0 and 100'));
     elseif (alpha2 > 1)
         waitfor(msgbox('alpha2 must lie between 0 and 100'));
     end
 end

% Callback for button3 -- period, editable button duration of pitch
% period (in samples) at fs=10000 Hz
 function button3Callback(h,eventdata)
     period=str2num(get(button3,'string'));
     if period < 10
         waitfor(msgbox('pitch period must lie between 10 and 250 samples'));
     elseif period > 250
         waitfor(msgbox('pitch period must lie between 10 and 250 samples'));
     end
 end

% Callback for button4 -- ivowel: editable button for vowel sound impulse
% response to be convolved with glottal pulse
 function button4Callback(h,eventdata)
     ivowel=get(button4,'val');
 end

% Callback for button9 -- Generate Excitation -- both Rosenberg pulse and
% periodic extension at designated pitch period
    function button9Callback(h,eventdata)
        button3Callback(h,eventdata);
        button4Callback(h,eventdata);

     alpha1=str2num(get(button1,'string'))/100;
     alpha2=str2num(get(button2,'string'))/100;

% form rosenberg glottal pulse, g
    n1=round(period*alpha1);
    n2=round(period*alpha2);
    g=[];
    x1=0:n1;
    g=[g 0.5*(1-cos(pi*x1/n1))];
    x2=1:n2;
    g=[g cos(pi*x2/(2*n2))];
    g=[g zeros(1,period-length(g))];

% plot g as a time domain signal over a single period in graphics Panel 1
    reset(graphicPanel2);
    axes(graphicPanel2);

    x=0:length(g)-1;
    plot(x,g,'b','LineWidth',2);
    xpp=['Time in Samples; fs=',num2str(fs),' samples/second'];
    xlabel(xpp);
    ylabel('Pulse Amplitude');axis tight; grid on;
    s1=sprintf('Rosenberg pulse -- period: %d,',period);
    s2=sprintf(' alpha1, alpha2: %6.3f, %6.3f ',alpha1,alpha2);
    stitle=strcat(s1,s2);
    legend('Rosenberg Pulse');

% display glottal pulse parameters in titleBox1
    set(titleBox1,'String',stitle);
    set(titleBox1,'FontSize',25);

% plot log magnitude spectrum of glottal pulse, g, in graphics Panel 1
    ge=[g zeros(1,nfft-length(g))];
    gs=20*log10(abs(fft(ge)));
    freq=0:fs/nfft:fs/2;
    x2=[0 fs/2];
    s2=[0 0];

    reset(graphicPanel1);
    axes(graphicPanel1);
    plot(freq,gs(1:nfft/2+1),'r','LineWidth',2);
    hold on;
    plot(x2,s2,'g','LineWidth',2);
    xlabel('Frequency in Hz'),ylabel('Log Magnitude (dB)');
    axis tight; grid on;legend('Rosenberg Pulse Spectrum');

% play out periodic pulse train of impulses spaced period samples apart,
% and of total length of fsd=10000 samples (fsd defined in list of
% variables at beginning of Callbacks)
    imp_train=zeros(1,fsd);
    imp_train(1:period:fsd)=1;

 % display impulse train for 1000 samples on Graphics Panel 5
    reset(graphicPanel5);
    axes(graphicPanel5);
    plot(0:1000,imp_train(1:1001),'r','LineWidth',2);
    xpp=['Time in Samples; fs=',num2str(fs),' samples/second'];
    xlabel(xpp),ylabel('Value'),axis tight, grid on; legend('Periodic Impulses');

% generate excitation pulses using Rosenberg pulse
    pulse_train=conv(g,imp_train);

% display glottal pulse train for 1000 samples on Graphics Panel 4
    reset(graphicPanel4);
    axes(graphicPanel4);
    plot(0:1000,pulse_train(1:1001),'b','LineWidth',2);
    xpp=['Time in Samples; fs=',num2str(fs),' samples/second'];
    xlabel(xpp),ylabel('Value'),axis tight, grid on; legend('Glottal Pulses');

% load vowel info (formants and bandwidths)
% load 'vowels_fmts_bw.mat'
    str=load('vowels_fmts_bw.mat');
    vowels=str.vowels;
    formants=str.formants;
    bandwidths=str.bandwidths;

% generate vowel impulse response
    fmts=formants(ivowel,:);
    fmts=[fmts 4500];
    yout=vowel_ir(fmts,bandwidths,fsd);

% convolve vowel impulse response with excitation
    zout=conv(yout,pulse_train);

% display periodic vowel sequence for 1000 samples on Graphics Panel 3
    reset(graphicPanel3);
    axes(graphicPanel3);
    plot(0:1000,zout(1:1001),'k','LineWidth',2);
    xpp=['Time in Samples; fs=',num2str(fs),' samples/second'];
    xlabel(xpp),ylabel('Value'),axis tight, grid on;

    xleg=['Vowel Response:',vowels(ivowel,:),'  Period:',num2str(period)];
    legend(xleg);
    end

% Callback for button5 -- Play Periodic Impulses
    function button5Callback(h,eventdata)
    soundsc(imp_train,fsd);
    end

% Callback for button6 -- Play Glottal Pulses
    function button6Callback(h,eventdata)
    soundsc(pulse_train,fsd);
    end

% Callback for button7 -- Play Vowel Excited by Glottal Pulses
    function button7Callback(h,eventdata)
    soundsc(zout,fsd);
    end

% Callback for button8 -- close GUI
 function button8Callback(h,eventdata)
     close(gcf);
 end
end


%%%
%{
Copyright (c) 2010, Jake Hughey
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
%}
%%%

function [sortedStruct index] = nestedSortStruct(aStruct, fieldNamesCell, directions)
% [sortedStruct index] = nestedSortStruct(aStruct, fieldNamesCell, directions)
% nestedSortStruct returns a nested sort of a (one-dimensional) struct array
% (aStruct), and can also return an index vector. The fields by which to sort are
% specified in a cell array of strings fieldNamesCell. Fields must be single numbers or
% logicals, or chars (usually simple strings).
%
% fieldNamesCell can also be a simple string of one fieldname, in which case
% nestedSortStruct will simply call sortStruct. This will be faster than putting the
% single fieldname in a cell array.
%
% directions is an optional argument to specify whether the struct array should be sorted
% in ascending or descending order for the fields. By default, the struct array will be
% sorted in ascending order for each field. If supplied, directions must be
%       1) a single 1 to sort in ascending order for all fields, or
%       2) a single -1 to sort in descending order for all fields, or
%       3) a vector of 1's and -1's, the same length as fieldNamesCell, where the struct
%          array will be sorted in the order specified by directions(ii) for
%          fieldNamesCell(ii).
%
% nestedSortStruct basically converts the struct array to a cell array, then converts
% relevants parts of the cell array to a matrix, on which sortrows is run.
%
% nestedSortStruct will usually be faster than nestedSortStruct2. For nestedSortStruct,
% the speed of sorting is mostly independent of the order of the fieldnames in fieldNamesCell.
%
% For nestedSortStruct2, the order of the fields in fieldNamesCell affects the speed. The
% sooner a field for which most entries in the struct array have unique values will be
% used to sort the struct array (i.e., the earlier that field's location in
% fieldNamesCell), the faster nestedSortStruct2 will be. If a field with mostly unique
% entries is the first field by which the struct array will be sorted, nestedSortStruct2
% could be faster than nestedSortStruct.

%% check struct
if ~isstruct(aStruct)
    error('first input supplied is not a struct.')
end % if

if sum(size(aStruct)>1)>1 % if more than one non-singleton dimension
    error('I don''t want to sort your multidimensional struct array.')
end % if

%% check fieldnames
if ~iscell(fieldNamesCell)
    if isfield(aStruct, fieldNamesCell) % if fieldNamesCell is a simple string of a valid fieldname
        [sortedStruct index] = sortStruct(aStruct, fieldNamesCell);
        return
    else
        error('second input supplied is not a cell array or simple string of a fieldname.')
    end % if isfield
end % if ~iscell

if ~isfield(aStruct, fieldNamesCell)
    for ii=find(~isfield(aStruct, fieldNamesCell))
        fprintf('%s is not a fieldname in the struct.\n', fieldNamesCell{ii})
    end % for
    error('at least one entry in fieldNamesCell is not a fieldname in the struct.')
end % if

%% check classes of fieldnames
fieldFlag = 0;
for ii=1:length(fieldNamesCell)
    fieldEntry = aStruct(1).(fieldNamesCell{ii});
    if ~( ((isnumeric(fieldEntry) || islogical(fieldEntry)) && numel(fieldEntry)==1) || ischar(fieldEntry) )
        fprintf('%s is not a valid fieldname by which to sort.\n', fieldNamesCell{ii})
        fieldFlag = 1;
    end % if
end % for ii

if fieldFlag
    error('at least one fieldname is not a valid one by which to sort.')
end

%% check directions, create if necessary (1 for ascending, -1 for descending)
if nargin < 3 % if directions doesn't exist
    directions = ones(1, length(fieldNamesCell));
else % check directions if it does exist
    if ~(isnumeric(directions) && all(ismember(directions, [-1 1])))
        error('directions, if given, must be a single number or a vector with 1 (ascending) and -1 (descending).')
    end % if ~(...

    if numel(directions)==1
        directions = directions * ones(1, length(fieldNamesCell)); % create vector from single element
    elseif length(fieldNamesCell)~=length(directions)
        error('fieldNamesCell and directions vector are different lengths.')
    end % if numel...
end % if exist...

%% fieldNamesIdx is a vector of the indices of the fields by which to sort
[dummy fieldNamesIdx] = ismember(fieldNamesCell, fieldnames(aStruct));

%% convert the struct to a cell, squeeze makes sure both row and column arrays are sorted properly, transpose for sortrows
aCell = squeeze(struct2cell(aStruct))';

%% sortrows of aCell, using indices from fieldNamesIdx and directions
[sortedCell index] = sortrows(aCell, fieldNamesIdx .* directions);

sortedStruct = aStruct(index); % apply the index to the struct array


function Callbacks_ideal_vocal_tract_GUI25(f,C)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x=C{1,1};
y=C{1,2};
a=C{1,3};
b=C{1,4};
u=C{1,5};
v=C{1,6};
m=C{1,7};
n=C{1,8};
lengthbutton=C{1,9};
widthbutton=C{1,10};
enterType=C{1,11};
enterString=C{1,12};
enterLabel=C{1,13};
noPanels=C{1,14};
noGraphicPanels=C{1,15};
noButtons=C{1,16};
labelDist=C{1,17};%distance that the label is below the button
noTitles=C{1,18};
buttonTextSize=C{1,19};
labelTextSize=C{1,20};
textboxFont=C{1,21};
textboxString=C{1,22};
textboxWeight=C{1,23};
textboxAngle=C{1,24};
labelHeight=C{1,25};
fileName=C{1,26};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%PANELS
for j=0:noPanels-1
uipanel('Parent',f,...
'Units','Normalized',...
'Position',[x(1+4*j) y(1+4*j) x(2+4*j)-x(1+4*j) y(3+4*j)-y(2+4*j)]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%GRAPHIC PANELS
for i=0:noGraphicPanels-1
switch (i+1)
case 1
graphicPanel1 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 2
graphicPanel2 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 3
graphicPanel3 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 4
graphicPanel4 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 5
graphicPanel5 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
case 6
graphicPanel6 = axes('parent',f,...
'Units','Normalized',...
'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...
'GridLineStyle','--');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%TITLE BOXES
for k=0:noTitles-1
switch (k+1)
case 1
titleBox1 = uicontrol('parent',f,...
'Units','Normalized',...
'Position',[u(1+4*k) v(1+4*k) u(2+4*k)-u(1+4*k) v(3+4*k)-v(2+4*k)],...
'Style','text',...
'FontSize',textboxFont{k+1},...
'String',textboxString(k+1),...
'FontWeight',textboxWeight{k+1},...
'FontAngle',textboxAngle{k+1});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%BUTTONS
for i=0:(noButtons-1)
enterColor='w';
if strcmp(enterType{i+1},'pushbutton')==1 ||strcmp(enterType{i+1},'text')==1
enterColor='default';
end
if (strcmp(enterLabel{1,(i+1)},'')==0 &&...
        strcmp(enterLabel{1,(i+1)},'...')==0) %i.e. there is a label
%creating a label for some buttons
uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i)-labelDist-labelHeight(i+1) ...
(m(2+2*i)-m(1+2*i)) labelHeight(i+1)],...
'Style','text',...
'String',enterLabel{i+1},...
'FontSize', labelTextSize(i+1),...
'HorizontalAlignment','center');
end
switch (i+1)
case 1
button1=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button1Callback);
case 2
button2=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button2Callback);
case 3
button3=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button3Callback);
case 4
button4=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button4Callback);
case 5
button5=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button5Callback);
case 6
button6=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button6Callback);
case 7
button7=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button7Callback);
case 8
button8=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button8Callback);
case 9
button9=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button9Callback);
case 10
button10=uicontrol('Parent',f,...
'Units','Normalized',...
'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...
'Style',enterType{i+1},...
'String',enterString{i+1},...
'FontSize', buttonTextSize(1+i),...
'BackgroundColor',enterColor,...
'HorizontalAlignment','center',...
'Callback',@button10Callback);
end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%USER CODE FOR THE VARIABLES AND CALLBACKS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize Variables
vowel_index=1;
ipd=100;
Lm=40;
L=400;
ilog=1;
ftable=[270 2290 3010; 390 1990 2550; 530 1840 2480; 660 1720 2410;...
    520 1190 2390; 730 1090 2390; 570 840 2410; 490 1350 1690;...
    440 1020 2240; 300 870 2240; 300 870 2240; 500 1500 2500];
btable=[40 60 75];
fk=[270 2290 3010];
bk=[40 60 75];
M=3;
fs=10000;
hn=[];
g=[];
iglottal=0;
vowels=['IY'; 'IH'; 'EH'; 'AE'; 'AH'; 'AA'; 'AO'; 'ER'; 'UH'; 'UW'; 'OO'; 'Ne'];
filename=vowels(1,:);
alpha1=40;
alpha2=20;

% nfft: size of fft and ifft for conversion from time to frequency or
% frequency to time domain
    nfft=1000;

% Name GUI
    set(f,'Name','ideal_vocal_tract_GUI');

% CALLBACKS
% Callback for button1 -- vowel choice from popuplist
 function button1Callback(h,eventdata)
     vowel_index=get(button1,'val');
     fk=ftable(vowel_index,:);
     bk=btable;
     filename=vowels(vowel_index,:);
 end

% Callback for button2 -- ipd: pitch period in msec
 function button2Callback(h,eventdata)
     ipd=str2num(get(button2,'string'));
     if ipd < 2
         waitfor(msgbox('pitch period must lie between 2 and 15 msec'));
     elseif ipd > 15
         waitfor(msgbox('pitch period must lie between 2 and 15 msec'));
     end
     ipd=ipd*fs/1000;
 end

% Callback for button3 -- Lm: frame duration in msec, (editable)
 function button3Callback(h,eventdata)
     Lm=str2num(get(button3,'string'));
      if Lm < 0
         waitfor(msgbox('The frame duration cannot be negative'));
     end
     L=round(Lm*fs/1000);
 end

% Callback for button4 -- log/linear popuplist (1=log, 2=linear); option
% for plotting vowel and ideal frequency responses
 function button4Callback(h,eventdata)
     ilog=get(button4,'val');
 end

% Callback for button10 -- iglottal: use glottal puse (1) or skip glottal
% pulse (0)
    function button10Callback(h,eventdata)
        iglottal=get(button10,'val');
    end

% Callback for button8 -- alpha1 for glottal pulse
    function button8Callback(h,eventdata)
        alpha1=str2num(get(button8,'string'))/100;
        if alpha1 < 0
            waitfor(msgbox('alpha1 must lie between 0 and 100'));
        elseif alpha1 > 1
            waitfor(msgbox('alpha1 must lie between 0 and 100'));
        end
    end

% Callback for button9 -- alpha2 for glottal pulse
    function button9Callback(h,eventdata)
        alpha2=str2num(get(button9,'string'))/100;
    if alpha2 < 0
        waitfor(msgbox('alpha2 must lie between 0 and 100'));
    elseif alpha2 > 1
        waitfor(msgbox('alpha2 must lie between 0 and 100'));
     end
    end

% Callback for button5 -- Run ideal vocal tract responses
 function button5Callback(h,eventdata)

% eps: smallest spectral magnitude for plotting log magnitude spectra
    eps=1.e-3;

% form rosenberg glottal pulse, g; rise % from alpha1; fall % from alpha2
    button8Callback(h,eventdata);
    button9Callback(h,eventdata);
    button10Callback(h,eventdata);
    button2Callback(h,eventdata);
    button3Callback(h,eventdata);
    button4Callback(h,eventdata);

    n1=round(ipd*alpha1);
    n2=round(ipd*alpha2);
    g=[];
    x1=0:n1;
    g=[g 0.5*(1-cos(pi*x1/n1))];
    x2=1:n2;
    g=[g cos(pi*x2/(2*n2))];
    g=[g zeros(1,ipd-length(g))];

% create periodic voiced excitation
    e=zeros(1,nfft);
    e(1:ipd:nfft)=1;
    EM=zeros(1,nfft);
    EM(1:round(nfft/ipd):nfft)=1;

% glottal_pulse excitation based on iglottal (1: use glottal pulse, 0 skip
% glottal pulse
if (iglottal == 1)
    eg=conv(e,g);
else
    eg=e;
end
    ege(1:nfft)=0;
    ege(1:nfft)=eg(1:nfft);
    EGM=abs(fft(ege,nfft));

% convert to second order system format
    zk=exp(-2*pi*bk/fs);
    fkn=cos(2*pi*fk/fs);

% transform into frequency domain
    HR=[];
    HT=zeros(1,nfft);
    HP=(complex(ones(1,nfft),zeros(1,nfft)))';
    for k=1:M
        B=1-2*zk(k)*fkn(k)+zk(k)*zk(k);
        A=[1 -2*zk(k)*fkn(k) zk(k)*zk(k)];
        [H,W]=freqz(B,A,nfft,'whole',fs);
        HP=HP.*H;
        HL=(abs(H));
        HT=HT.*HL';
    end

% inverse transform to give vocal tract impulse response
    hn=ifft(HP,nfft);
    hmax=max(max(hn),-min(hn));
    for index=1:nfft
        if (max(max(hn(index:nfft)),-min(hn(index:nfft)))) < hmax/50
            nl=index;
            break;
        end
    end

% plot elements of composite response in the 6 graphics Panels
% plot ideal impulse excitation signal in graphics Panel 5 (top left panel)
    reset(graphicPanel5);
    axes(graphicPanel5);

    if (iglottal == 0)
        stem(0:nfft-1,e(1:nfft),'b','LineWidth',2),axis tight;
    else
        plot(0:nfft-1,eg(1:nfft),'b','LineWidth',2),axis tight;
    end
    xpp=['Time in Samples; fs=',num2str(fs),' samples/second'];
    xlabel(xpp),ylabel('Amplitude');grid on;legend('Excitation Pulses');

% plot vowel impulse response in graphics Panel 3 (middle left panel)
    reset(graphicPanel3);
    axes(graphicPanel3);

    plot(0:nl,hn(1:nl+1),'r','LineWidth',2);
    xlabel(xpp),ylabel('Amplitude');
    axis tight, grid on;legend('Vowel Vocal Tract Impulse Response');

% plot linear or log magnitude frequency response of ideal impulse
% excitation signal in graphics Panel 6 (top right panel); use lin/log
% option to decide whether to plot linear or log magnitude responses
    if (ilog == 1)
        reset(graphicPanel6);
        axes(graphicPanel6);
        plot(W(1:nfft/2+1),20*log10(EGM(1:nfft/2+1)+eps),'b','LineWidth',2);
        axis tight,xlabel('Frequency in Hz'),ylabel('Log Magnitude (dB)');
        legend('Excitation Pulses Log Spectrum');

% plot linear or log magnitude frequency response of ideal vocal tract
% impulse response in graphics Panel 4 (middle right panel); use lin/log
% option to decide whether to plot linear or log magnitude response
        reset(graphicPanel4);
        axes(graphicPanel4);
        plot(W(1:nfft/2+1),20*log10(abs(HP(1:nfft/2+1))),'r','LineWidth',2);
        axis tight,grid on, xlabel('Frequency in Hz');
        ylabel('Log Magnitude (dB)');legend('Vocal Tract Log Spectrum');
    else
        reset(graphicPanel6);
        axes(graphicPanel6);
        plot(W(1:nfft/2+1),EGM(1:nfft/2+1),'b','LineWidth',2);
        axis tight,xlabel('Frequency in Hz'),ylabel('Magnitude');
        legend('Excitation Pulses Linear Spectrum');

        reset(graphicPanel4);
        axes(graphicPanel4);
        plot(W(1:nfft/2+1),abs(HP(1:nfft/2+1)),'r','LineWidth',2);
        xlabel('Frequency in Hz'),ylabel('Magnitude'),axis tight,grid on;
        legend('Vocal Tract Linear Spectrum');
    end
    axis tight;

% take product of magnitudes, convolve time responses
    he=zeros(1,L+nfft-1);
    for index=1:ipd:L
        he(index:index+nfft-1)=he(index:index+nfft-1)+hn(1:nfft)';
    end
    EMV=EGM(1:nfft/2+1).*abs(HP(1:nfft/2+1))';

% plot ideal periodic vowel impulse response in graphics Panel 1 (lower
% left panel); note: no glottal pulse used in this simple ideal vocal tract
% model
    reset(graphicPanel1);
    axes(graphicPanel1);
    plot(0:L-1,he(1:L),'b','LineWidth',2);
    xlabel(xpp),ylabel('Amplitude');
    axis tight,grid on;legend('Vowel Waveform');

% plot linear or log magnitude frequency response of ideal synthetic vowel
% impulse response in graphics Panel 2 (bottom right panel); use lin/log
% option to decide whether to plot linear or log magnitude response
    if (ilog == 1)
        reset(graphicPanel2);
        axes(graphicPanel2);
        plot(W(1:nfft/2+1),20*log10(EMV(1:nfft/2+1)+eps),'r','LineWidth',2);
        xlabel('Frequency in Hz'),ylabel('Log Magnitude (dB)');
        axis tight,grid on;legend('Vowel Log Spectrum');
    else
        reset(graphicPanel2);
        axes(graphicPanel2);
        plot(W(1:nfft/2+1),EMV(1:nfft/2+1),'r','LineWidth',2);
        xlabel('Frequency in Hz'),ylabel('Magnitude');
        axis tight, grid on;legend('Vowel Linear Spectrum');
    end

% set titleBox1 information for display
    stitle=sprintf('Ideal Vocal Tract -- Vowel:%s, ipd:%d, L:%d, fs:%d, eps:%6.3f',filename,ipd,L,fs,eps);
    set(titleBox1,'String',stitle);
    set(titleBox1,'FontSize',20);
 end

% Callback for button7 -- Play Synthetic Vowel
    function button7Callback(h,eventdata)
% play back synthetic speech output
    e=zeros(1,fs);
    e(1:ipd:fs)=1;
    if (iglottal == 1)
        y1=conv(e,g);
        yout=conv(y1,hn);
    else
        yout=conv(e,hn);
    end
    % uiwait(msgbox('Play out synthetic speech','speech out'));
    soundsc(yout,fs);
    end

% Callback for button6 -- Close GUI
 function button6Callback(h,eventdata)
     close(gcf);
 end
end


function annModel = annotateGEM(model,annPath,annType,addMiriams,addFields,overwrite)
% Add reaction, metabolite, and/or gene annotation to a model.
%
% Input:
%
%   model        Model structure.
%
%   annPath      Path to the annotation files, which suppose to be named as
%                'reactions.tsv', 'metabolites.tsv', and 'genes.tsv'。
%
%   annType      String or cell array of strings specifying the type(s) of
%                annotation data to add: 'rxn', 'met', and/or 'gene'. To
%                add all annotation types, use 'all'.
%                For example, annType={'rxn','gene'} will add reaction and
%                gene annotation information, but not metabolite.
%                (Opt, default 'all')
%
%   addMiriams   If TRUE, annotation information will be added to the
%                metMiriams field. If the metMiriams field does not exist,
%                it will be created.
%                (Opt, default TRUE)
%
%   addFields    If TRUE, separate model fields will be added for each
%                added ID type, e.g., reaction KEGG IDs will be added to a
%                rxnKEGGID field.
%                (Opt, default TRUE)
%
%   overwrite    If TRUE, any existing metMiriam or model ID field entries
%                will be overwritten. If FALSE, they will be appended with
%                the new data.
%                (Opt, default TRUE)
%
%
% Output:
%
%   annModel     Model structure with added annotation information.
%
%
% Usage:
%
%   annModel = annotateGEM(model,annPath,annType,addMiriams,addFields,overwrite);
%

%% Inputs and setup

if nargin < 2
    [ST, I] = dbstack('-completenames');
    annPath = strcat(fileparts(ST(I).file),'/../model');
end

if nargin < 3 || isempty(annType) || isequal(annType,'all')
    annType = {'rxn','met','gene'};
elseif ~all(ismember(annType,{'rxn','met','gene','reaction','metabolite'}))
    error('annType input(s) not recognized. Valid options are "rxn", "met", and/or "gene", or "all"');
end

if nargin < 4 || isempty(addMiriams)
    addMiriams = true;
end

if nargin < 5 || isempty(addFields)
    addFields = true;
end

if nargin < 6
    overwrite = true;
end

if (~addMiriams) && (~addFields)
    error('addMiriams and addFields are both FALSE - no annotation will be added.')
end

% map field names to those on identifiers.org (used for building Miriams)
id2miriam = {%reactions
             'rxnKEGGID'        'kegg.reaction'
             'rxnBiGGID'        'bigg.reaction'
             'rxnREACTOMEID'    'reactome'
             'rxnRecon3DID'     'vmhreaction'
             'rxnMetaNetXID'    'metanetx.reaction'
             'rxnTCDBID'        'tcdb'
             'rxnRheaID'        'rhea'
             'rxnRheaMasterID'  'rhea'
             % metabolites
             'metBiGGID'        'bigg.metabolite'
             'metKEGGID'        'kegg.compound'
             'metHMDBID'        'hmdb'
             'metChEBIID'       'chebi'
             'metPubChemID'     'pubchem.compound'
             'metLipidMapsID'   'lipidmaps'
             'metRecon3DID'     'vmhmetabolite'
             'metMetaNetXID'    'metanetx.chemical'
             % genes
             'genes'            'ensembl'
             'geneENSTID'       'ensembl'
             'geneENSPID'       'ensembl'
             'geneUniProtID'    'uniprot'
             'geneSymbols'      'hgnc.symbol'
             'geneEntrezID'     'ncbigene'
             };

%% Load and organize annotation data

% load reaction annotation data
if any(ismember({'rxn','reaction'},lower(annType)))
    tmpfile = fullfile(annPath,'reactions.tsv');
    rxnAssoc = importTsvFile(tmpfile);

    % strip "RHEA:" prefix from Rhea IDs since it should not be included in
    % the identifiers.org URL
    rxnAssoc.rxnRheaID = regexprep(rxnAssoc.rxnRheaID, 'RHEA:', '');
    rxnAssoc.rxnRheaMasterID = regexprep(rxnAssoc.rxnRheaMasterID, 'RHEA:', '');

    rxnAssocArray = struct2cell(rxnAssoc);
    numericFields = find(cellfun(@isnumeric, rxnAssocArray));
    for i = 1:numel(numericFields)
        % numeric fields must be converted to text for miriams
        rxnAssocArray{numericFields(i)} = arrayfun(@num2str, rxnAssocArray{numericFields(i)}, 'UniformOutput', false);
    end
    rxnAssocArray = horzcat(rxnAssocArray{:});
else
    rxnAssoc = [];
end

% load metabolite annotation data
if any(ismember({'met','metabolite'},lower(annType)))
    tmpfile = fullfile(annPath,'metabolites.tsv');
    metAssoc = importTsvFile(tmpfile);

    % ChEBI IDs should be of the form "CHEBI:#####"
    metAssoc.metChEBIID = regexprep(metAssoc.metChEBIID,'(^)(\d+)|(;\s*)(\d+)','$1CHEBI:$2');

    metAssocArray = struct2cell(metAssoc);
    numericFields = find(cellfun(@isnumeric, metAssocArray));
    for i = 1:numel(numericFields)
        % numeric fields need to be converted to text for miriams
        metAssocArray{numericFields(i)} = arrayfun(@num2str, metAssocArray{numericFields(i)}, 'UniformOutput', false);
    end
    metAssocArray = horzcat(metAssocArray{:});
else
    metAssoc = [];
end

% load and organize gene annotation data
if ismember('gene',lower(annType))
    tmpfile = fullfile(annPath,'genes.tsv');
    geneAssoc = importTsvFile(tmpfile);

    % add geneEnsemblID field if missing
    if ~isfield(geneAssoc, 'geneEnsemblID')
        geneAssoc.geneEnsemblID = geneAssoc.genes;
    end

    geneAssocArray = struct2cell(geneAssoc);
    geneAssocArray = horzcat(geneAssocArray{:});
else
    geneAssoc = [];
end

%% Add annotation data to model MIRIAM fields

if ( addMiriams )

    % Reactions
    if ~isempty(rxnAssoc)
        % map model rxns to those in the association structures
        [hasRxn,rxnInd] = ismember(model.rxns,rxnAssoc.rxns);

        % add rxnMiriams field if it does not exist or if overwrite is TRUE
        if ~isfield(model,'rxnMiriams') || overwrite
            model.rxnMiriams = repmat({''},size(model.rxns));
        end

        % map rxn ID fields to the proper identifiers.org terms
        [hasRxnField,rxnFieldInd] = ismember(fieldnames(rxnAssoc),id2miriam(:,1));
        miriamNames = id2miriam(rxnFieldInd(hasRxnField),2);
        miriamValues = rxnAssocArray(:,hasRxnField);

        % assign SBO terms to model reactions
        rxnSBO = repmat({'SBO:0000176'},size(model.rxns));  % default is "biochemical reaction"

        biomass_rxn = contains(lower(model.rxns),'biomass');
        biomass_met = ismember(lower(model.metNames),'biomass') & ismember(model.comps(model.metComps),'c');
        biomass_rxn = biomass_rxn | (model.S(biomass_met,:) > 0)';
        rxnSBO(biomass_rxn) = {'SBO:0000629'};  % "biomass production"

        transport_rxn = getTransportRxns(model);
        rxnSBO(transport_rxn) = {'SBO:0000185'};  % "translocation reaction"

        [~,exchange_rxn] = getExchangeRxns(model);
        rxnSBO(exchange_rxn) = {'SBO:0000627'};  % "exchange reaction"

        % add new data to the rxnMiriams field
        for i = 1:numel(model.rxns)
            if hasRxn(i)
                % add annotation
                model.rxnMiriams{i} = appendMiriamData(model.rxnMiriams{i}, miriamNames, miriamValues(rxnInd(i),:)');
            end
            % add SBO terms
            model.rxnMiriams{i} = appendMiriamData(model.rxnMiriams{i}, {'sbo'}, rxnSBO(i));
        end
    end

    % Metabolites
    if ~isempty(metAssoc)
        % map model mets to those in the association structures
        [hasMet,metInd] = ismember(model.mets,metAssoc.mets);

        % add metMiriams field if it does not exist or if overwrite is TRUE
        if ~isfield(model,'metMiriams') || overwrite
            model.metMiriams = repmat({''},size(model.mets));
        end

        % map met ID fields to the proper identifiers.org terms
        [hasMetField,metFieldInd] = ismember(fieldnames(metAssoc),id2miriam(:,1));
        miriamNames = id2miriam(metFieldInd(hasMetField),2);
        miriamValues = metAssocArray(:,hasMetField);

        % add new data to the metMiriams field
        for i = 1:numel(model.mets)
            if hasMet(i)
                % add annotation
                model.metMiriams{i} = appendMiriamData(model.metMiriams{i}, miriamNames, miriamValues(metInd(i),:)');
            end
            % add SBO term (SBO:0000247, "simple chemical" for all mets)
            model.metMiriams{i} = appendMiriamData(model.metMiriams{i}, {'sbo'}, {'SBO:0000247'});
        end
    end

    % Genes
    if ~isempty(geneAssoc)
        % Note: because geneAssoc was built using geneIDs directly from the
        %       model, we do not need to map model.genes to the geneAssoc
        %       structure - the indexing should be identical.

        % map model genes to those in the association structures
        [hasGene,geneInd] = ismember(model.genes,geneAssoc.genes);

        % add geneMiriams field if it does not exist or if overwrite is TRUE
        if ~isfield(model,'geneMiriams') || overwrite
            model.geneMiriams = repmat({''},size(model.genes));
        end

        % map gene ID fields to the proper identifiers.org terms
        [hasGeneField,geneFieldInd] = ismember(fieldnames(geneAssoc),id2miriam(:,1));
        miriamNames = id2miriam(geneFieldInd(hasGeneField),2);
        miriamValues = geneAssocArray(:,hasGeneField);

        % add new data to the geneMiriams field
        for i = 1:numel(model.genes)
            if hasGene(i)
                % add annotation
                model.geneMiriams{i} = appendMiriamData(model.geneMiriams{i}, miriamNames, miriamValues(geneInd(i),:)');
            end
            % add SBO term (SBO:0000243, "gene" for all genes)
            model.geneMiriams{i} = appendMiriamData(model.geneMiriams{i}, {'sbo'}, {'SBO:0000243'});
        end
    end

end

%% Add annotation data to individual model fields

if ( addFields )

    % merge association structures
    allAssoc = mergeStructures({rxnAssoc,metAssoc,geneAssoc});

    % some fields should not be added to the model
    remFields = {'rxns','mets','metsNoComp','genes'};
    allAssoc = rmfield(allAssoc, intersect(fieldnames(allAssoc),remFields));

    % get fields and their types
    f = fieldnames(allAssoc);

    if ~isempty(rxnAssoc)
        fieldType = repmat({'rxn'}, numel(f), 1);
    end

    if ~isempty(metAssoc)
        fieldType(ismember(f, fieldnames(metAssoc))) = {'met'};
    end

    if ~isempty(geneAssoc)
        fieldType(ismember(f, fieldnames(geneAssoc))) = {'gene'};
    end

    % add individual ID fields to the model
    for i = 1:numel(f)

        switch fieldType{i}
            case 'rxn'
                [hasRxn,rxnInd] = ismember(model.rxns,rxnAssoc.rxns);
                if isnumeric(allAssoc.(f{i}))
                    ids = NaN(size(model.rxns));
                else
                    ids = repmat({''},size(model.rxns));
                end
                ids(hasRxn) = allAssoc.(f{i})(rxnInd(hasRxn));
            case 'met'
                [hasMet,metInd] = ismember(model.mets,metAssoc.mets);
                if isnumeric(allAssoc.(f{i}))
                    ids = NaN(size(model.mets));
                else
                    ids = repmat({''},size(model.mets));
                end
                ids(hasMet) = allAssoc.(f{i})(metInd(hasMet));
            case 'gene'
                [hasGene,geneInd] = ismember(model.genes,geneAssoc.genes);
                if isnumeric(allAssoc.(f{i}))
                    ids = NaN(size(model.genes));
                else
                    ids = repmat({''},size(model.genes));
                end
                ids(hasGene) = allAssoc.(f{i})(geneInd(hasGene));
            otherwise
                continue
        end

        if ~isfield(model,f{i}) || overwrite
            model.(f{i}) = ids;
        else
            % merge new IDs with existing IDs
            merged_ids = join([model.(f{i}), ids],';');
            merged_ids = arrayfun(@(id) strjoin(unique(split(id,';')),';'), merged_ids, 'UniformOutput', false);
            model.(f{i}) = regexprep(merged_ids,'^;\s*','');  % remove any preceding semicolons
        end

    end

end

%%

% assign output
annModel = model;

end

%% Additional functions

function miriam_new = appendMiriamData(miriam,names,values)
% Append new entries to an existing miriam structure.

% ignore empty entries
remove = cellfun(@isempty,values);
names(remove) = [];
values(remove) = [];
if isempty(names)
    miriam_new = miriam;
    return
end

% convert existing miriam entry to cell array
if ~isempty(miriam)
    miriam = [miriam.name(:), miriam.value(:)];
end

% append miriam entry with new data
for i = 1:numel(names)
    if contains(values{i},';')
        % handle multiple values separated by semicolon (;)
        val = strtrim(split(values{i},';'));
        name = repmat(names(i),numel(val),1);
        miriam = [miriam; [name, val]];
    else
        miriam = [miriam; [names(i), values(i)]];
    end
end

% remove any repeated entries
[~,miriam_num] = ismember(miriam,miriam);
[~,uniq_ind] = unique(miriam_num,'rows');
miriam = miriam(uniq_ind,:);

% convert back to structure
miriam_new.name = miriam(:,1);
miriam_new.value = miriam(:,2);

end

function mergedStruct = mergeStructures(structs)
% Merge multiple structures into a single structure.

mergedStruct = {};
for i = 1:numel(structs)

    s = structs{i};

    if isempty(s)
        continue
    end

    f = fieldnames(s);
    for j = 1:numel(f)
        mergedStruct.(f{j}) = s.(f{j});
    end

end

end


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

% Last Modified by GUIDE v2.5 28-Nov-2012 12:06:59

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

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

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes FAULT wait for user response (see UIRESUME)
% uiwait(handles.figure1);

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

% --- 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

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

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

% --- 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

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

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

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

% --- 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

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

% --- Executes during object creation, after setting all properties.
function edit9_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit9 (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)
a=(get(handles.popupmenu1,'value'));
real=str2num(get(handles.edit1,'string'));
img=str2num(get(handles.edit2,'string'));
Z0= real+img*i;
real1=str2num(get(handles.edit3,'string'));
img1=str2num(get(handles.edit4,'string'));
Z1=real1+img1*i;
real2=str2num(get(handles.edit5,'string'));
img2=str2num(get(handles.edit6,'string'));
Z2=real2+img2*i;
line_voltage=str2num(get(handles.edit9,'string'));
phase_voltage=line_voltage/(sqrt(3));
kva=str2num(get(handles.edit8,'string'));
% for popup menu commond
a=(get(handles.popupmenu1,'value'));switch a
    case 1
       %LINE TO GROUND FAULT
Io=(phase_voltage)/(Z0+Z1+Z2);
fault_current=(3*(phase_voltage)/(Z0+Z1+Z2));
set(handles.edit10,'string',imag(fault_current));
    case 2
   %LINE TO LINE FAULT
fault_current2=(-i*sqrt(3)*phase_voltage)/(Z1+Z1);
set(handles.edit10,'string',(fault_current2));
end

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

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

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

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1

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