function parrec = spm_cfg_parrec
% SPM Configuration file for Philips PAR/REC Import
%__________________________________________________________________________
% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging

% Guillaume Flandin
% $Id: spm_cfg_parrec.m 6315 2015-01-23 17:09:06Z guillaume $

%--------------------------------------------------------------------------
% data PAR files
%--------------------------------------------------------------------------
data         = cfg_files;
data.tag     = 'data';
data.name    = 'PAR files';
data.help    = {'Select the PAR files to convert.'};
data.filter  = 'any';
data.ufilter = '.*(par|PAR)';
data.num     = [1 Inf];

%--------------------------------------------------------------------------
% outdir Output directory
%--------------------------------------------------------------------------
outdir         = cfg_files;
outdir.tag     = 'outdir';
outdir.name    = 'Output directory';
outdir.help    = {'Select a directory where files are written.'};
outdir.filter  = 'dir';
outdir.ufilter = '.*';
outdir.num     = [1 1];

%--------------------------------------------------------------------------
% ext Output image format
%--------------------------------------------------------------------------
ext         = cfg_menu;
ext.tag     = 'ext';
ext.name    = 'Output image format';
ext.help    = {'Output files can be written as .img + .hdr, or the two can be combined into a .nii file.'};
ext.labels = {
              'Two file (img+hdr) NIfTI'
              'Single file (nii) NIfTI'
}';
ext.values = {'img', 'nii'};
ext.def    = @(val)spm_get_defaults('images.format', val{:});

%--------------------------------------------------------------------------
% opts Options
%--------------------------------------------------------------------------
opts         = cfg_branch;
opts.tag     = 'opts';
opts.name    = 'Options';
opts.val     = {outdir ext};
opts.help    = {'Conversion options'};

%--------------------------------------------------------------------------
% parrec ECAT Import
%--------------------------------------------------------------------------
parrec         = cfg_exbranch;
parrec.tag     = 'parrec';
parrec.name    = 'PAR/REC Import';
parrec.val     = {data opts};
parrec.help    = {'Philips PAR/REC Import.'};
parrec.prog    = @convert_parrec;
parrec.vout    = @vout;

%==========================================================================
function out = convert_parrec(job)
for i=1:numel(job.data)
    spm_parrec2nifti(job.data{i},job.opts);
end

out.files = cell(size(job.data));
for i=1:numel(job.data)
    out.files{i} = spm_file(job.data{i}, 'path',pwd, 'ext',job.opts.ext);
end

%==========================================================================
function dep = vout(job)
dep            = cfg_dep;
dep.sname      = 'Converted Images';
dep.src_output = substruct('.','files');
dep.tgt_spec   = cfg_findspec({{'filter','image','strtype','e'}});


function id=satno2id(sat)

global glc

[sys,prn]=satsys(sat);

switch sys
    case glc.SYS_GPS,id=sprintf('G%02d',prn-glc.MINPRNGPS+1);return;
    case glc.SYS_GLO,id=sprintf('R%02d',prn-glc.MINPRNGLO+1);return;
    case glc.SYS_GAL,id=sprintf('E%02d',prn-glc.MINPRNGAL+1);return;
    case glc.SYS_BDS,id=sprintf('C%02d',prn-glc.MINPRNBDS+1);return;
    case glc.SYS_QZS,id=sprintf('J%02d',prn-glc.MINPRNQZS+1);return;
end

id='';

return


function name = dfgetfitname()

% $Revision: 1.1.6.2 $  $Date: 2004/01/24 09:35:38 $
% Copyright 2003-2004 The MathWorks, Inc.

count=dfgetset('fitcount');
if isempty(count)
    count = 1;
end
taken = 1;
while taken
    name=sprintf('fit %i', count);
    if isempty(find(getfitdb,'name',name))
        taken = 0;
    else
        count=count+1;
    end
end
dfgetset('fitcount',count+1);


function   y = sigmoid(x)
% legacy code
s = warning ('on');
warning ('*** The function `sigmoid` is now deprecated. Please see `VBA_sigmoid` for an alternative.')
warning (s);

% fallback
y = VBA_sigmoid (x);


function sF = vertcat(varargin)
% overloads vertcat

sF = cat(1,varargin{:});

end


function Data = findRxnMatch(cRxn, nMatch, scoreTotal)
% Finds the highest scoring matches for a given reaction.
% Called by `reactionCompareGUI`.
%
% USAGE:
%
%    Data = findRxnMatch(cRxn, nMatch, scoreTotal)
%
% INPUTS:
%    cRxn:          Number of the compared rxn.
%    nMatch:        Number of matches to return.
%    scoreTotal:    summed SCORE of reactions vs reactions.
%    CMODEL:        global input
%    TMODEL:        global input
%
% OUTPUTS:
%    Data:          Structure containing comparison information.
%
% Please cite:
% `Sauls, J. T., & Buescher, J. M. (2014). Assimilating genome-scale
% metabolic reconstructions with modelBorgifier. Bioinformatics
% (Oxford, England), 30(7), 1036?8`. http://doi.org/10.1093/bioinformatics/btt747
%
% ..
%    Edit the above text to modify the response to help addMetInfo
%    Last Modified by GUIDE v2.5 06-Dec-2013 14:19:28
%    This file is published under Creative Commons BY-NC-SA.
%
%    Correspondance:
%    johntsauls@gmail.com
%
%    Developed at:
%    BRAIN Aktiengesellschaft
%    Microbial Production Technologies Unit
%    Quantitative Biology and Sequencing Platform
%    Darmstaeter Str. 34-36
%    64673 Zwingenberg, Germany
%    www.brain-biotech.de

global CMODEL TMODEL % Declare variables.

% Structure comtaining comparison information
Data = ([]);

%% cRxn Reaction Info
Data.cRxnTable = cell(8,1) ;
Data.cRxnTable(:) = {''} ;
Data.cRxnTable{1} = num2str(cRxn) ;
Data.cRxnTable{2} = CMODEL.rxns{cRxn} ;
Data.cRxnTable{3} = CMODEL.rxnNames{cRxn} ;
Data.cRxnTable{4} = CMODEL.rxnEquations{cRxn} ;
Data.cRxnTable{5} = CMODEL.rxnECNumbers{cRxn} ;
Data.cRxnTable{6} = CMODEL.rxnKEGGID{cRxn} ;
Data.cRxnTable{7} = CMODEL.rxnSEEDID{cRxn} ;
Data.cRxnTable{8} = CMODEL.subSystems{cRxn} ;

%% cRxn Metabolite Info
Data.cMetTable = cell(14, 1);
Data.cMetTable(:) = {''};

% Reactants from model
Data.cMetTable{1} = num2str(CMODEL.metNums(cRxn, 3)); % # of reactants

metPos = find(CMODEL.S(:, cRxn) < 0) ; % find reactants
if ~isempty(metPos)
    metlist = CMODEL.mets{metPos(1)} ; % add in first metabolite Id
    names = CMODEL.metNames{metPos(1)} ;
    stoics = num2str(abs(CMODEL.S(metPos(1), cRxn))) ; % add in first stoic
    forms = CMODEL.metFormulas{metPos(1)} ; % first formula
    charges = num2str(CMODEL.metCharge(metPos(1))) ; % first charge
    keggs = CMODEL.metKEGGID{metPos(1)} ; % first charge

    % If there are more than one mets, add additional info.
    if length(metPos) > 1
        for j = 2:length(metPos)
            metlist = strcat(metlist, '; ', CMODEL.mets{metPos(j)});
            names = strcat(names, '; ', CMODEL.metNames{metPos(j)});
            stoics = strcat(stoics, '; ', ...
                            num2str(abs(CMODEL.S(metPos(j), cRxn))));
            forms = strcat(forms, '; ', CMODEL.metFormulas{metPos(j)});
            charges = strcat(charges, '; ', ...
                             num2str(CMODEL.metCharge(metPos(j))));
            keggs = strcat(keggs, '; ', CMODEL.metKEGGID{metPos(j)});
        end
    end

    % Assign to table.
    Data.cMetTable{2} = metlist ;
    Data.cMetTable{3} = names ;
    Data.cMetTable{4} = stoics ;
    Data.cMetTable{5} = forms ;
    Data.cMetTable{6} = charges ;
    Data.cMetTable{7} = keggs ;
end

% Products from crxn.
% Number of products.
Data.cMetTable{8} = num2str(CMODEL.metNums(cRxn, 5));

% Find product position.
metPos = find(CMODEL.S(:, cRxn) > 0) ;

if ~isempty(metPos)
    % First product.
    metlist = CMODEL.mets{metPos(1)};
    names = CMODEL.metNames{metPos(1)} ;
    stoics = num2str(abs(CMODEL.S(metPos(1), cRxn)));
    forms = CMODEL.metFormulas{metPos(1)};
    charges = num2str(CMODEL.metCharge(metPos(1)));
    keggs = CMODEL.metKEGGID{metPos(1)};

    % Additional products.
    if length(metPos) > 1
        for j = 2:length(metPos)
            metlist = strcat(metlist, '; ', CMODEL.mets{metPos(j)});
            names = strcat(names, '; ', CMODEL.metNames{metPos(j)});
            stoics = strcat(stoics, '; ', ...
                            num2str(abs(CMODEL.S(metPos(j), cRxn))));
            forms = strcat(forms, '; ', CMODEL.metFormulas{metPos(j)});
            charges = strcat(charges, '; ', ...
                             num2str(CMODEL.metCharge(metPos(j))));
            keggs = strcat(keggs, '; ', CMODEL.metKEGGID{metPos(j)});
        end
    end

    % Assign data.
    Data.cMetTable{9} = metlist ;
    Data.cMetTable{10} = names ;
    Data.cMetTable{11} = stoics ;
    Data.cMetTable{12} = forms ;
    Data.cMetTable{13} = charges ;
    Data.cMetTable{14} = keggs ;
    clear metlist; clear stoics; clear forms; clear charges; clear keggs
end

%% Match Reaction(s) Info
% Allocate match reaction table.
Data.tRxnTable = cell(8, nMatch);
Data.tRxnTable(:) = {''};

% Sort scores, I is the original index.
[y, I] = sort(scoreTotal(cRxn, :), 'descend');

for i = 1:nMatch
    Data.tRxnTable{1, i} = strcat(num2str(y(i)), '; ', num2str(I(i)));
    Data.tRxnTable{2, i} = TMODEL.rxns{I(i)} ;
    Data.tRxnTable{3, i} = TMODEL.rxnNames{I(i)} ;
    Data.tRxnTable{4, i} = TMODEL.rxnEquations{I(i)} ;
    Data.tRxnTable{5, i} = TMODEL.rxnECNumbers{I(i)} ;
    Data.tRxnTable{6, i} = TMODEL.rxnKEGGID{I(i)} ;
    Data.tRxnTable{7, i} = TMODEL.rxnSEEDID{I(i)} ;
    Data.tRxnTable{8, i} = TMODEL.subSystems{I(i)} ;
end

%% Match Metabolite Info
Data.tMetTable = cell(14, nMatch);
Data.tMetTable(:) = {''};

for i = 1:nMatch
    % Reactants from model.
    Data.tMetTable{1,i} = num2str(TMODEL.metNums(I(i),3));

    % First reactant.
    metPos = find(TMODEL.S(:,I(i)) < 0) ;

    if ~isempty(metPos)
        metlist = TMODEL.mets{metPos(1)};
        names = TMODEL.metNames{metPos(1)} ;
        stoics = num2str(abs(TMODEL.S(metPos(1),I(i))));
        forms = TMODEL.metFormulas{metPos(1)};
        charges = num2str(TMODEL.metCharge(metPos(1)));
        keggs = TMODEL.metKEGGID{metPos(1)};

        % Additioanl Reactants.
        if length(metPos) > 1
            for j = 2:length(metPos)
                metlist = strcat(metlist, '; ', TMODEL.mets{metPos(j)});
                names = strcat(names, '; ', TMODEL.metNames{metPos(j)});
                stoics = strcat(stoics, '; ', ...
                                num2str(abs(TMODEL.S(metPos(j), I(i)))));
                forms = strcat(forms, '; ', TMODEL.metFormulas{metPos(j)});
                charges = strcat(charges, '; ', ...
                                 num2str(TMODEL.metCharge(metPos(j))));
                keggs = strcat(keggs, '; ', TMODEL.metKEGGID{metPos(j)});
            end
        end

        Data.tMetTable{2, i} = metlist ;
        Data.tMetTable{3, i} = names ;
        Data.tMetTable{4, i} = stoics ;
        Data.tMetTable{5, i} = forms ;
        Data.tMetTable{6, i} = charges ;
        Data.tMetTable{7, i} = keggs ;
    end

    % Products from model.
    if TMODEL.metNums(I(i), 5) ~= 0
        Data.tMetTable{8, i} = num2str(TMODEL.metNums(I(i), 5));

        % Find product indexes.
        metPos = find(TMODEL.S(:, I(i)) > 0) ;

        % First product
        metlist = TMODEL.mets{metPos(1)};
        names = TMODEL.metNames{metPos(1)} ;
        stoics = num2str(abs(TMODEL.S(metPos(1), I(i))));
        forms = TMODEL.metFormulas{metPos(1)};
        charges = num2str(TMODEL.metCharge(metPos(1)));
        keggs = TMODEL.metKEGGID{metPos(1)};

        % Additional products.
        if length(metPos) > 1
            for j = 2:length(metPos)
                metlist = strcat(metlist, '; ', TMODEL.mets{metPos(j)});
                names = strcat(names, '; ', TMODEL.metNames{metPos(j)});
                stoics = strcat(stoics, '; ', ...
                                num2str(abs(TMODEL.S(metPos(j), I(i)))));
                forms = strcat(forms, '; ', TMODEL.metFormulas{metPos(j)});
                charges = strcat(charges, '; ', ...
                                 num2str(TMODEL.metCharge(metPos(j))));
                keggs = strcat(keggs, '; ', TMODEL.metKEGGID{metPos(j)});
            end
        end

        % Assign to table.
        Data.tMetTable{9, i} = metlist ;
        Data.tMetTable{10, i} = names ;
        Data.tMetTable{11, i} = stoics ;
        Data.tMetTable{12, i} = forms ;
        Data.tMetTable{13, i} = charges ;
        Data.tMetTable{14, i} = keggs ;
    end
end


function p = emptyNumericalModel
p.F_struc = [];
p.K.f = 0;
p.K.l = 0;
p.K.q = [];
p.K.p = [];
p.K.e = 0;
p.K.s = 0;


classdef NamingManager < handle

    properties (Access = private)
        costFuncNames
        costWeights
        constraintNames
        convVarsNames
    end

    methods (Access = public)

        function obj = NamingManager(cParams)
            obj.costFuncNames   = cParams.costFuncNames;
            obj.costWeights     = cParams.costWeights;
            obj.constraintNames = cParams.constraintFuncs;
            obj.convVarsNames   = ConvergenceVarsDispatcher.dispatchNames(cParams.optimizerNames);
        end

        function name = getCostFuncFigureTitle(obj,i)
            name = obj.costFuncNames{i};
            weight = obj.costWeights(i);

            if isempty(weight)
                weightDesc = '(wt. 1.0)';
            else
                weightDesc = sprintf('(wt. %.2f)',weight);
            end

            name = [obj.setCase(name) ' ' weightDesc];
        end

        function name = getConstraintFigureTitle(obj,i)
            name = obj.constraintNames{i};
            name = ['Cstr ' num2str(i) ': ' obj.setCase(name)];
        end

        function name = getLambdaFigureTitle(obj,i)
            name = obj.constraintNames{i};
            name = ['\lambda' obj.subindex(obj.setCase(name))];
        end

        function name = getConvVarFigureTitle(obj,i)
            name = obj.convVarsNames{i};
            name = ['Conv Criteria ' num2str(i) ': ' name];
        end

        function n = getNumberOfConvergenceVariables(obj)
            n = numel(obj.convVarsNames);
        end

        function name = getConvVarNames(obj,i)
            name = obj.convVarsNames{i};
        end

    end

    methods (Access = public, Static)

        function name = getFrameTitle(iStep,nStep,it)
            name = sprintf('Monitoring - Inc. Step: %.0f/%.0f Iteration: %.0f',iStep,nStep,it);
        end

    end

    methods (Access = private,Static)

        function str = setCase(str)
            str = [upper(str(1)) str(2:end)];
        end

        function str = subindex(str_)
            str = [];
            for i = 1:length(str_)
                str(end+1:end+2) = ['_' str_(i)];
            end
        end
    end

end


function flatten_hmm(hmm,filename)

K = hmm.K;
train = hmm.train;
prior = hmm.prior;
Dir_alpha = hmm.Dir_alpha;
Pi = hmm.Pi;
Dir2d_alpha = hmm.Dir2d_alpha;
P = hmm.P;

for k = 1:K
    if isfield(hmm.state(k),'W') && isfield(hmm.state(k).W,'Mu_W') && ~isempty(hmm.state(k).W.Mu_W)
        eval(['state_' num2str(k-1) '_Mu_W = hmm.state(k).W.Mu_W;']);
        eval(['state_' num2str(k-1) '_S_W = hmm.state(k).W.S_W;']);
        if isfield(hmm.state(k).W,'iS_W')
            eval(['state_' num2str(k-1) '_iS_W = hmm.state(k).W.iS_W;']);
        end
    end
    if isfield(hmm.state(k),'Omega') && isfield(hmm.state(k).Omega,'Gam_rate')
        eval(['state_' num2str(k-1) '_Omega_Gam_rate = hmm.state(k).Omega.Gam_rate;']);
        eval(['state_' num2str(k-1) '_Omega_Gam_shape = hmm.state(k).Omega.Gam_shape;']);
        if isfield(hmm.state(k).Omega,'Gam_irate')
            eval(['state_' num2str(k-1) '_Omega_Gam_irate = hmm.state(k).Omega.Gam_irate;']);
        end
        eval(['state_' num2str(k-1) '_prior_Omega_Gam_rate = hmm.state(k).prior.Omega.Gam_rate;']);
        eval(['state_' num2str(k-1) '_prior_Omega_Gam_shape = hmm.state(k).prior.Omega.Gam_shape;']);
    end
end

if isfield(hmm,'Omega') && isfield(hmm.Omega,'Gam_rate')
    Omega_Gam_rate = hmm.Omega.Gam_rate;
    Omega_Gam_shape = hmm.Omega.Gam_shape;
    if isfield(hmm.Omega,'Gam_irate')
        Omega_Gam_irate = hmm.Omega.Gam_irate;
    end
    prior_Omega_Gam_rate = hmm.prior.Omega.Gam_rate;
    prior_Omega_Gam_shape = hmm.prior.Omega.Gam_shape;
end

save_string = strcat("save('",filename,"','K','train','Dir_alpha','Pi','Dir2d_alpha','P'");

for k = 1:K
    if isfield(hmm.state(k),'W') && isfield(hmm.state(k).W,'Mu_W') && ~isempty(hmm.state(k).W.Mu_W)
        save_string = strcat(save_string,",'state_",num2str(k-1),"_Mu_W'");
        save_string = strcat(save_string,",'state_",num2str(k-1),"_S_W'");
        if isfield(hmm.state(k).W,'iS_W')
            save_string = strcat(save_string,",'state_",num2str(k-1),"_iS_W'");
        end
    end
    if isfield(hmm.state(k),'Omega') && isfield(hmm.state(k).Omega,'Gam_rate')
        save_string = strcat(save_string,",'state_",num2str(k-1),"_Omega_Gam_rate'");
        save_string = strcat(save_string,",'state_",num2str(k-1),"_Omega_Gam_shape'");
        if isfield(hmm.state(k).Omega,'Gam_irate')
            save_string = strcat(save_string,",'state_",num2str(k-1),"_Omega_Gam_irate'");
        end
        save_string = strcat(save_string,",'state_",num2str(k-1),"_prior_Omega_Gam_rate'");
        save_string = strcat(save_string,",'state_",num2str(k-1),"_prior_Omega_Gam_shape'");
    end
end

if isfield(hmm,'Omega') && isfield(hmm.Omega,'Gam_rate')
    save_string = strcat(save_string,",'Omega_Gam_rate'");
    save_string = strcat(save_string,",'Omega_Gam_shape'");
    if isfield(hmm.Omega,'Gam_irate')
        save_string = strcat(save_string,",'Omega_Gam_irate'");
    end
    save_string = strcat(save_string,",'prior_Omega_Gam_rate'");
    save_string = strcat(save_string,",'prior_Omega_Gam_shape'");
end
save_string = strcat(save_string,")");

eval(save_string)

end


% std_readitc()  - load ITC measures for data channels or
%                  for all components of a specified cluster.
% Usage:
%         >> [STUDY, itcdata, times, freqs] = ...
%                   std_readitc(STUDY, ALLEEG, varargin);
%
% Note: this function is a helper function that contains a call to the
% std_readersp function that reads all 2-D data matrices for EEGLAB STUDY.
% See the std_readersp help message for more information.
%
% Author: Arnaud Delorme, CERCO, 2006-

% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 2004, arno@sccn.ucsd.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function [STUDY, erspdata, alltimes, allfreqs, erspbase] = std_readersp(STUDY, ALLEEG, varargin);

[STUDY, erspdata, alltimes, allfreqs] = std_readersp(STUDY, ALLEEG, 'infotype','itc', varargin{:});


function obj = coef_Jacob2_qt_pnp_func_new(in1)
coef_J2 = in1(:,2);
coef_J5 = in1(:,5);
coef_J6 = in1(:,6);
coef_J7 = in1(:,7);
coef_J20 = in1(:,20);
coef_J21 = in1(:,21);
coef_J22 = in1(:,22);
coef_J40 = in1(:,40);
coef_J14 = in1(:,14);
coef_J41 = in1(:,41);
coef_J50 = in1(:,50);
coef_J15 = in1(:,15);
coef_J33 = in1(:,33);
coef_J42 = in1(:,42);
coef_J51 = in1(:,51);
coef_J16 = in1(:,16);
coef_J34 = in1(:,34);
coef_J43 = in1(:,43);
coef_J17 = in1(:,17);
coef_J35 = in1(:,35);
coef_J44 = in1(:,44);
coef_J18 = in1(:,18);
coef_J36 = in1(:,36);
coef_J45 = in1(:,45);
coef_J19 = in1(:,19);
coef_J37 = in1(:,37);
coef_J46 = in1(:,46);
coef_J38 = in1(:,38);
coef_J47 = in1(:,47);
coef_J39 = in1(:,39);
coef_J48 = in1(:,48);
coef_J49 = in1(:,49);
obj = [-coef_J2+coef_J14.*3.0,coef_J15.*2.0,coef_J16.*2.0,-coef_J2+coef_J17,coef_J18,-coef_J2+coef_J19,coef_J20,coef_J21,coef_J22,coef_J2,coef_J5.*-2.0+coef_J33.*4.0,-coef_J6+coef_J34.*3.0,-coef_J7+coef_J35.*3.0,coef_J5.*-2.0+coef_J36.*2.0,coef_J37.*2.0,coef_J5.*-2.0+coef_J38.*2.0,coef_J39.*2.0,coef_J40.*2.0,coef_J41.*2.0,coef_J5.*2.0,-coef_J6+coef_J42,-coef_J7+coef_J43,-coef_J6+coef_J44,coef_J45,coef_J46,coef_J47,coef_J6,-coef_J7+coef_J48,coef_J49,coef_J50,coef_J51,coef_J7];


function termimpl(term_typ,term_opr,term_loc)
%
% Utility Function: TERMIMPL
%
% The purpose of this function is to implement the add, edit, or iterate
% operations

% Author: Craig Borghesani
% Date: 8/8/94
% Revised:
% Copyright (c) 1999, Prentice-Hall

% obtain handle information
f = gcf;
ui_data = get(f,'userdata');
ui_han = ui_data{1};
ui_obj = ui_data{2};
%popup      = ui_han(1);
%txt_top    = ui_han(2);
%txt_btm    = ui_han(3);
%edt_top    = ui_han(4);
%edt_btm    = ui_han(5);
%sld_top    = ui_han(6);
%sld_btm    = ui_han(7);
%lft_btn    = ui_han(8);
%rht_btn    = ui_han(9);
popup = ui_obj.SysUI(5);
txt_top = ui_obj.SysUI(6);
txt_btm = ui_obj.SysUI(9);
edt_top = ui_obj.SysUI(7);
edt_btm = ui_obj.SysUI(10);
sld_top = ui_obj.SysUI(8);
sld_btm = ui_obj.SysUI(11);
lft_btn = ui_obj.SysUI(12);
rht_btn = ui_obj.SysUI(13);
plant      = ui_han(30);
for_cont   = ui_han(31);
bac_cont   = ui_han(32);
set_to_one1= ui_han(33);
set_to_one2= ui_han(34);

% file modification
set(ui_han(47),'userdata',1);

cur_sys = get(ui_han(30),'userdata');
cur_page = get(ui_han(31),'userdata');
sys_state = get(ui_han(33),'userdata');
page_setup = get(ui_han(34),'userdata');

temp1_mat = [1,0,NaN,1;0,NaN,NaN,2];

% variable term_mat alternates as either the current controller matrix or
% current plant matrix
if strcmp(get(plant,'checked'),'on'),
 term_mat = get(ui_han(3+cur_sys),'userdata');
elseif strcmp(get(for_cont,'checked'),'on'),
 term_mat = get(ui_han(6+cur_sys),'userdata');
else
 term_mat = get(ui_han(9+cur_sys),'userdata');
end

% get data from ADD/UPDATE and ITERATE uicontrols
if any(term_opr == [1,2]), % Add/Update operation
 val1 = str2num(get(edt_top,'string'));
 val2 = str2num(get(edt_btm,'string'));

 if ~length(val1) & any(term_typ==[1,2,4,5,9,10]),
  katcherr(2,term_typ); return;
 elseif (~length(val1) | (~length(val2))) & any(term_typ == [6,7,8,9,11]),
  katcherr(2,term_typ); return;
 elseif any(term_typ==[1:5,11]),
  if (length(val1) & val1==0 & any(term_typ==[1:3])) | (length(val2) & val2==0 & any(term_typ==[6,7,11])),
   katcherr(4,term_typ); return;
  end
 elseif term_typ == 8,
  if abs(val1) > 88,
   katcherr(5,8); return;
  elseif val2 == 0,
   katcherr(6,8); return;
  end
 end

 if ~length(val2), val2 = NaN; end

% update top and bottom sliders
 if term_opr == 2,
  if term_typ ~= 9,
   set(sld_top,'min',0.5*val1,'max',1.5*val1,'value',val1);
   if ~isnan(val2),
    set(sld_btm,'min',0.5*val2,'max',1.5*val2,'value',val2);
   end
  end
 end

elseif term_opr == 3, % Iterate operation

 val1 = get(sld_top,'value');
 set(edt_top,'string',num2str(val1));
 min1 = get(sld_top,'min'); max1 = get(sld_top,'max');
 if abs(val1) <= abs(min1) | abs(val1) >= abs(max1),
  set(sld_top,'min',0.5*val1,'max',1.5*val1,'value',val1);
 end

 val2 = get(sld_btm,'value');
 if strcmp(get(sld_btm,'enable'),'off'),
  val2 = NaN;
 else
  set(edt_btm,'string',num2str(val2));
  min2 = get(sld_btm,'min'); max2 = get(sld_btm,'max');
  if abs(val2) <= abs(min2) | abs(val2) >= abs(max2),
   set(sld_btm,'min',0.5*val2,'max',1.5*val2,'value',val2);
  end
 end

elseif term_opr == 4, % Delete operation
 val1 = term_mat(term_loc,1);
 val2 = term_mat(term_loc,2);

end

if any(term_typ == [1,4:8]), % standard elements
 if term_typ == 1,
  new_term = [val1,term_mat(1,2),NaN,1];
 else
  if imag(val1)~=0,
   zeta = -cos(atan2(imag(-val1),real(-val1)));
   wn = abs(val1);
   term_typ = term_typ + 2;
   val1 = zeta;
   val2 = wn;
  end
  new_term = [val1,val2,NaN,term_typ];
 end

elseif any(term_typ==[2,3]), % integrators/differentiators
 new_term = [val1*((term_typ==2)-(term_typ==3)),val2,NaN,2];

elseif term_typ == 9, % num/den
 new_term = termpars(val1,val2);

elseif term_typ == 10, % delay time
 new_term = [term_mat(1,1),val1,NaN,1];

elseif term_typ == 15, % setting = 1

 set_to_one = get(f,'currentmenu');
 if set_to_one == set_to_one1,
  loc1 = cur_sys*2 - 1;
  loc2 = 4;
 else
  loc1 = cur_sys*2;
  loc2 = 5;
 end

 set_label = get(set_to_one,'label');
 if length(find(set_label=='P')), sel = 3;
 elseif length(find(set_label=='G')), sel = 6;
 else sel = 9; end

 if strcmp(get(ui_han(29+sel/3),'enable'),'off'), % retrieving
  new_term = get(ui_han(12+loc1),'userdata');
  set(ui_han(12+loc1),'userdata',temp1_mat);
  set(ui_han(sel+cur_sys),'userdata',new_term);
  set(set_to_one,'checked','off');
  term_opr = 1;
  set(ui_han(29+sel/3),'enable','on');
  sys_state(loc2,cur_sys) = 0;
 else % storing
  new_term = get(ui_han(sel+cur_sys),'userdata');
  set(ui_han(12+loc1),'userdata',new_term);
  set(ui_han(sel+cur_sys),'userdata',temp1_mat);
  set(set_to_one,'checked','on');
  term_opr = 4;
  set(ui_han(29+sel/3),'enable','off');
  sys_state(loc2,cur_sys) = 1;
 end
end
set(ui_han(33),'userdata',sys_state);

% reset root locus storage
if (term_typ ~= 1) | (term_typ == 1 & sign(val1) ~= sign(term_mat(1,1))),
 set(ui_han(37),'userdata',[]);
end

if term_opr == 1, % Add

 if any(term_typ == [1,4:8]), % standard elements
  term_mat = [term_mat;new_term];
  term_loc = length(term_mat(:,1));

 elseif any(term_typ == [2,3]), % integrator/differentiator
  term_mat(2,:) = [term_mat(2,1)+new_term(1),new_term(2:4)];
  term_loc=2;

 elseif term_typ == 9, % num/den
  term_mat(1,1) = term_mat(1,1)*new_term(1,1);
  term_mat(2,1) = term_mat(2,1)+new_term(2,1);
  term_mat = [term_mat;new_term(3:length(new_term(:,1)),:)];

 elseif term_typ == 10, % delay time
  term_mat(1,2) = new_term(1,2);

 end

elseif any(term_opr == [2,3]), % Update/Iterate

 old_term = term_mat(term_loc,:);
 term_mat(term_loc,:) = new_term;

else % Delete

 if term_typ == 2,
  term_mat(2,1)=0;
 elseif any(term_typ == [1,4:8]),
  term_mat(term_loc,:)=[];
 end

end

if strcmp(get(plant,'checked'),'on'),
 set(ui_han(3+cur_sys),'userdata',term_mat);
elseif strcmp(get(for_cont,'checked'),'on'),
 set(ui_han(6+cur_sys),'userdata',term_mat);
else
 set(ui_han(9+cur_sys),'userdata',term_mat);
end

term_res = get(ui_han(cur_sys),'userdata');
w = term_res(1,:);

new_res = termcplx(new_term,w);

if term_opr == 1, % Add
 old_res = ones(1,length(w));
% if term_typ < 9,
%  set(lft_btn,'string','Update',...
%      'callback',['termimpl(',int2str(term_typ),',2,',int2str(term_loc),')']);
% end

elseif any(term_opr == [2,3]), % Edit/Iterate
 old_res = termcplx(old_term,w);

else % delete
 old_res = new_res;
 new_res = ones(1,length(w));

end

term_res(2,:) = term_res(2,:).*(new_res./old_res);
set(ui_han(cur_sys),'userdata',term_res);

% display laplacian transfer function
if term_loc >= 0,
 dispfrac
end

pageplot(0,[]);

if term_typ < 10,
 if term_opr == 1,
%  termmang(term_typ,2,term_loc);
  set(rht_btn,'callback',['termimpl(',int2str(term_typ),',4,',int2str(term_loc),')']);
 elseif term_opr == 4,
  termmang(term_typ,1,0);
 end
end