% function to show limo results - deprecated

% Copyright (C) 2016 Ramon Martinez
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. 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 HOLDER 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.

classdef pop_limoresults < handle

    %class properties - access is private so nothing else can access these
    properties (Access = public)
        gui_h;
        study;
        limofiles_path;
        limofiles_level1;
        limofiles_level2;
        regnames;
        catvarnames;
        datorica_indx;
        reg_indx;
        cat_indx;
        string_mplot;
        limostruct_indx
    end

    methods
        % =================================================================
        function obj = pop_limoresults(STUDY,analysis)

            if ~ismember(analysis,{'dat','ica'}), return; end

            % Check if STUDY.design.limo
            %--------------------------------------------------------------
            datorica_list = {'dat','ica'};
            obj.datorica_indx = find(strcmp(analysis,datorica_list));

            [obj.gui_h,STUDY] = guibuilder(STUDY,analysis);
            obj.string_mplot  = get(obj.gui_h.popupmenu_measure2plot,'String');
            obj.gui_h         = guihandles(obj.gui_h.fig);
            obj.study         = STUDY;

            level_tmp       = get(obj.gui_h.popupmenu_level         ,'Value');
            m2plot_tmp      = get(obj.gui_h.popupmenu_measure2plot  ,'Value');
            var2plot_indx   = get(obj.gui_h.popupmenu_modelvar2plot ,'Value');
            [var2plot,filespath] = getmeasures2plot(obj.study,level_tmp-1,m2plot_tmp,obj.datorica_indx);

            % Detecting Measure and updating limofiles_path and
            %--------------------------------------------------------------
            obj.limofiles_path            = filespath;
            obj.limofiles_level1.index    = var2plot_indx;
            obj.limofiles_level1.guiname  = var2plot.guiname;
            obj.limofiles_level1.pathname = var2plot.pathname;
            % Updating Electrode list
            %--------------------------------------------------------------
            try
                load(fullfile(filespath,'LIMO.mat'),'LIMO');
                electoplot_list = ['All Channels';{LIMO.data.chanlocs.labels}'];
                electoplot_indx = 1;
                set(obj.gui_h.listbox_elect2plot,'String',electoplot_list);
                set(obj.gui_h.listbox_elect2plot,'Value',electoplot_indx);
            catch
            end

            % Creating Name of Regressors
            %--------------------------------------------------------------
            try
                % --
                % Getting the Names of the variables
                tmpregnames  = {};
                vartype_tmp  = {};
                reg_indx     = {};
                for i = 1: length(STUDY.design(STUDY.currentdesign).variable)
                    if strcmp(STUDY.design(STUDY.currentdesign).variable(i).vartype,'categorical')
                        if isempty(tmpregnames)
                            for j = 1: length(STUDY.design(STUDY.currentdesign).variable(i).value)
                                if  ~iscell(STUDY.design(STUDY.currentdesign).variable(i).value{1})
                                    tmpregnames{j} = [STUDY.design(STUDY.currentdesign).variable(i).label '_' STUDY.design(STUDY.currentdesign).variable(i).value{j}];
                                else
                                    for jvars = 1:length(STUDY.design(STUDY.currentdesign).variable(i).value{j})
                                        if jvars == 1
                                            jointtmp = STUDY.design(STUDY.currentdesign).variable(i).value{j}{jvars};
                                        else
                                            jointtmp = strcat (jointtmp, '&',  STUDY.design(STUDY.currentdesign).variable(i).value{j}{jvars});
                                        end
                                    end
                                    tmpregnames{j} = [STUDY.design(STUDY.currentdesign).variable(i).label '_' jointtmp{:}];
                                end
                            end
                            [vartype_tmp{1:length(tmpregnames)}] = deal(STUDY.design(STUDY.currentdesign).variable(i).vartype);
                        else
                            for j = 1:length(STUDY.design(STUDY.currentdesign).variable(i).value)
                                if  ~iscell(STUDY.design(STUDY.currentdesign).variable(i).value{1})
                                    tmpregnames{end+1} = [STUDY.design(STUDY.currentdesign).variable(i).label '_' STUDY.design(STUDY.currentdesign).variable(i).value{j}];
                                else
                                    for jvars = 1:length(STUDY.design(STUDY.currentdesign).variable(i).value{j})
                                        if jvars == 1
                                            jointtmp = STUDY.design(STUDY.currentdesign).variable(i).value{j}{jvars};
                                        else
                                            jointtmp = strcat (jointtmp, '&',  STUDY.design(STUDY.currentdesign).variable(i).value{j}{jvars});
                                        end
                                    end
                                    tmpregnames{end+1} = [STUDY.design(STUDY.currentdesign).variable(i).label '_' jointtmp];
                                end

                                %
                                vartype_tmp{end+1} = STUDY.design(STUDY.currentdesign).variable(i).vartype;
                            end
                        end
                    else
                        if isempty(tmpregnames)
                            tmpregnames{1} = STUDY.design(STUDY.currentdesign).variable(i).label;
                            vartype_tmp{1} = STUDY.design(STUDY.currentdesign).variable(i).vartype;

                        else
                            tmpregnames{end+1} = STUDY.design(STUDY.currentdesign).variable(i).label;
                            vartype_tmp{end+1} = STUDY.design(STUDY.currentdesign).variable(i).vartype;
                        end
                    end
                end

                % Set regressors order as LIMO assumes it (first all categorical, then all continuous)
                %----------------------------------------------------------------------------------
                cont_indx   = find(strcmp('continuous',vartype_tmp));
                cat_indx    = find(strcmp('categorical',vartype_tmp));
                tmpregnames = tmpregnames([cat_indx cont_indx]);

                % Adding Baseline
                %----------------------------------------------------------
                tmpregnames{end+1} = 'Baseline';
                % --
                limo = load(fullfile(obj.limofiles_path,'LIMO.mat' ));
                Nreg = size(limo.LIMO.design.X,2);

                 % Rgressors names in case of split continuous ones
                 %---------------------------------------------------------
                if ~isempty(cont_indx) && (Nreg ~= length(tmpregnames))
                    display('Split regressor detected. Giving generic names to continuous regressors ...' );
                    if ~isempty(cat_indx), inintcont = length(cat_indx)+1; else inintcont = 1 ; end

                    for i = inintcont:(Nreg-1)
                        tmpregnames{i} = ['Cont_' num2str(i - (inintcont - 1))];
                        display(['Naming Regressor: ' tmpregnames{i}]);
                    end
                end

                %---------------------------------------------------------
                cat_comb = [];
                if ~isempty(cat_indx) && size(cat_indx,2) > 1
                    cat_comb = nchoosek(1:length(cat_indx),2);
                end

                % Generating cat index
                %---------------------------------------------------------
                if ~isempty(cat_indx)
                    allcat_indx  = [1: length(cat_indx),(length(tmpregnames) + 1):(length(tmpregnames) + size(cat_comb,1))];
                end

                % Adding Regressor to names
                %---------------------------------------------------------
                for i = 1:length(tmpregnames)
                    %tmpregnames{i} = ['Regressor_' tmpregnames{i}];
                    reg_indx{i}    = ['[' num2str(i) ']'];
                end

                % Adding Combinations of cat regressors
                %----------------------------------------------------------
                if ~isempty(cat_comb)
                    for j =1:size(cat_comb,1)
                        strtmp = tmpregnames(cat_comb(j,:));
                        tmpregnames{end+1} = [strtmp{1} sprintf(' - %s', strtmp{2:end})];
                        clear strtmp;
                        reg_indx{end+1}    = ['[' num2str(cat_comb(j,:) ) ']'];
                    end
                end

                % Retrieving list of independent variables
                if ~isempty(cat_indx)
                    tmpregnames2 = tmpregnames(allcat_indx);
                    cat_indx     =  reg_indx(allcat_indx);
                else
                    tmpregnames2 = [];
                end

                % Adding 'Regressor' to names
                %---------------------------------------------------------
                for i = 1:length(tmpregnames)
                    tmpregnames{i} = ['Regressor_' tmpregnames{i}];
                    plusindx = strfind(tmpregnames{i},' - ');
                    if ~isempty(plusindx)
                        tmpregnames{i} = [tmpregnames{i}(1:plusindx+2) 'Regressor_' tmpregnames{i}(plusindx+3:end)];
                    end
                end

                % Updating fields
                %----------------------------------------------------------
                obj.regnames    = tmpregnames;
                obj.catvarnames = tmpregnames2;
                obj.reg_indx    = reg_indx;
                obj.cat_indx    = cat_indx;

            catch
                % Case where model is not computed
                %----------------------------------------------------------
                display(['File LIMO.mat not founded in :'  fullfile(obj.limofiles_path,'LIMO.mat')]);
                set(obj.gui_h.popupmenu_modelvar2plot,'Enable','off');
                set(obj.gui_h.popupmenu_plottype     ,'Enable','off');
                set(obj.gui_h.pushbutton_plot        ,'Enable','off');
                eeglab_warning('Make sure to compute the model for this measure');
            end

            % CALLBACKS
            %--------------------------------------------------------------
            %set the callback function for button_plot
            set(obj.gui_h.pushbutton_plot, 'Callback', @obj.callback_plot);

            %set the callback function for popupmenu_level
            set(obj.gui_h.popupmenu_level,'Callback', @obj.callback_popupmenu_level);

            %set the callback function for popupmenu_measure2plot
            set(obj.gui_h.popupmenu_measure2plot,'Callback', @obj.callback_popupmenu_level);

            %set the callback function for popupmenu_plottype
            set(obj.gui_h.popupmenu_plottype,'Callback', @obj.callback_popupmenu_plottype);

            %set the callback function for popupmenu_dataorresult
            set(obj.gui_h.popupmenu_dataorresult,'Callback', @obj.callback_popupmenu_dataorresult);

            %set the callback function for popupmenu_modelvar2plot
            set(obj.gui_h.popupmenu_modelvar2plot,'Callback', @obj.callback_popupmenu_modelvar2plot);

            %set the callback function for checkbox_stats
            set(obj.gui_h.checkbox_stats,'Callback', @obj.callback_checkbox_stats);

            %set the callback function for checkbox_stats
            set(obj.gui_h.listbox_elect2plot,'Callback', @obj.callback_listbox_elect2plot);

            %set the callback function for buttom_designadd
            set(obj.gui_h.pushbutton_designadd, 'Callback', @obj.callback_pushbutton_designadd);

        end
        % =================================================================
        function obj = callback_popupmenu_level(obj,~,~)

            val_level = get(obj.gui_h.popupmenu_level,'Value');        % Getting value (subject from level)
            val_mplot = get(obj.gui_h.popupmenu_measure2plot,'Value'); % Getting value from popupmenu_measure2plot
            val_dor = get(obj.gui_h.popupmenu_dataorresult,'Value');   % Getting value from popupmenu_dataorresult

            % Getting values popupmenu_modelvar2plot
            string_vplot  = get(obj.gui_h.popupmenu_modelvar2plot ,'String');
            val_vplot     = get(obj.gui_h.popupmenu_modelvar2plot ,'Value' );
            val_typeplot  = get(obj.gui_h.popupmenu_plottype      ,'Value' );
            string_elec   = get(obj.gui_h.listbox_elect2plot      ,'String');
            val_elec      = get(obj.gui_h.listbox_elect2plot      ,'Value' );

            % Single subject level
            if val_level ~= 1

                [var2plot,filespath,tmp,obj.study] = getmeasures2plot(obj.study,val_level-1,val_mplot,obj.datorica_indx,1);

                if strcmp(get(obj.gui_h.popupmenu_measure2plot,'String'),{' '})
                    set(obj.gui_h.popupmenu_measure2plot  ,'String', obj.string_mplot);
                    set(obj.gui_h.popupmenu_measure2plot  ,'Value',1);
                end

                % Updating Electrode list
                % =========================================================

                if ~strcmp('No Variables Computed',var2plot.guiname{1})

                    load(fullfile(filespath,'LIMO.mat'),'LIMO');
                    electoplot_list = ['All Channels';{LIMO.data.chanlocs.labels}'];
                    set(obj.gui_h.listbox_elect2plot,'String',electoplot_list);

                    % Getting index for var2plot_list and setting electrode
                    % index
                    if val_typeplot == 1 || val_typeplot == 2

                        % Updating electrode list val
                        %----------------------------------------------
                        set(obj.gui_h.listbox_elect2plot,'Value',1);

                         % Just Checking if the selected variable exist in
                         % the sub (case of Results only)
                         %-------------------------------------------------
                         if val_dor == 2
                            if ~ismember(string_vplot(val_vplot),var2plot.guiname)
                                % Getting index of  'Condition_effect_1.mat' for default value
                                % 1 st pass
                                var2plot_indx = find(strcmp(var2plot.guiname,'Condition_effect_1'), 1);
                                % 2nd pass
                                if isempty(var2plot_indx)
                                    var2plot_indx = find(strcmp(var2plot.guiname,'Covariate_effect_1'),1);
                                end
                                % Setting to 1 if all fails
                                if isempty(var2plot_indx)
                                    var2plot_indx = 1;
                                end
                                set(obj.gui_h.popupmenu_modelvar2plot,'String',var2plot.guiname);
                                set(obj.gui_h.popupmenu_modelvar2plot,'Value',var2plot_indx);
                            else
                                var2plot_indx = find(strcmp(string_vplot(val_vplot),var2plot.guiname));
                                set(obj.gui_h.popupmenu_modelvar2plot,'String',var2plot.guiname);
                                set(obj.gui_h.popupmenu_modelvar2plot,'Value',var2plot_indx);
                            end
                         end
                        %--------------------------------------------------
                    elseif val_typeplot == 3
                        %var2plot_list = string_vplot;

                        % Updating electrode list val
                        %--------------------------------------------------
                        newval_elec = find(strcmp(string_elec(val_elec),electoplot_list));
                        if isempty(newval_elec)
                            newval_elec = 2;
                        end
                        set(obj.gui_h.listbox_elect2plot,'Value',newval_elec);
                    end

                    % Enabling on GUI features
                    %------------------------------------------------------
                    set(obj.gui_h.popupmenu_measure2plot  ,'Enable','on');
                    set(obj.gui_h.popupmenu_dataorresult  ,'Enable','on');
                    set(obj.gui_h.popupmenu_modelvar2plot ,'Enable','on');
                    set(obj.gui_h.popupmenu_plottype      ,'Enable','on');
                    set(obj.gui_h.pushbutton_plot         ,'Enable','on');
                    set(obj.gui_h.checkbox_stats	      ,'Enable','on');
                    set(obj.gui_h.edit_pval               ,'Enable','on');
                else
                    % Enabling off GUI features
                    %------------------------------------------------------
                    set(obj.gui_h.popupmenu_dataorresult  ,'Enable','off');
                    set(obj.gui_h.popupmenu_modelvar2plot ,'Enable','off');
                    set(obj.gui_h.popupmenu_plottype      ,'Enable','off');
                    set(obj.gui_h.pushbutton_plot         ,'Enable','off');

                    eeglab_warning('Make sure to compute the model for this measure');
                end

                % Updating limofiles_level1 structure
                %----------------------------------------------------------
                if strcmp(get(obj.gui_h.popupmenu_modelvar2plot,'Enable'),'off')
                    obj.limofiles_level1.guiname = [];
                else
                    obj.limofiles_path          = filespath;
                    obj.limofiles_level1.guiname  = var2plot.guiname;
                    obj.limofiles_level1.pathname = var2plot.pathname;
                    obj.limofiles_level1.index    = get(obj.gui_h.popupmenu_modelvar2plot,'Value');
                end

            % Group level
            else
                measure_list  = {'erp','spec'};
                datorica_list = {'dat', 'ica'};
                datatype = [datorica_list{obj.datorica_indx} measure_list{get(obj.gui_h.popupmenu_measure2plot,'Value')}];

                obj.limostruct_indx = find(~cellfun(@isempty,strfind({obj.study.design(obj.study.currentdesign).limo.datatype},datatype)));
                if ~isempty(obj.limostruct_indx) && isfield(obj.study.design(obj.study.currentdesign).limo, 'groupmodel') && ~isempty(obj.study.design(obj.study.currentdesign).limo(obj.limostruct_indx).groupmodel)
                    obj.limofiles_level2.guiname  = {obj.study.design(obj.study.currentdesign).limo(obj.limostruct_indx).groupmodel.guiname}';
                    obj.limofiles_level2.pathname = {obj.study.design(obj.study.currentdesign).limo(obj.limostruct_indx).groupmodel.filename}';
                    obj.limofiles_level2.index = 1;
                    set(obj.gui_h.popupmenu_modelvar2plot,'String',obj.limofiles_level2.guiname);
                    set(obj.gui_h.popupmenu_modelvar2plot,'Value',1);

                    % Loading expected electrodes
                    %----------------------------------------------------------
                    try
                        load(obj.study.design(obj.study.currentdesign).limo(obj.limostruct_indx).chanloc);
                        electoplot_list = ['All Channels';{expected_chanlocs.labels}'];
                        set(obj.gui_h.listbox_elect2plot,'String',electoplot_list);
                    catch
                        % implement this
                    end

                    if val_typeplot == 1 || val_typeplot == 2

                        % Updating electrode list val
                        %----------------------------------------------
                        set(obj.gui_h.listbox_elect2plot,'Value',1);

                    elseif val_typeplot == 3

                        % Updating electrode list val
                        %--------------------------------------------------
                        newval_elec = find(strcmp(string_elec(val_elec),electoplot_list));
                        if isempty(newval_elec)
                            newval_elec = 2;
                        end
                        set(obj.gui_h.listbox_elect2plot,'Value',newval_elec);
                    end

                    % Enabling on/off GUI features
                    %------------------------------------------------------
                    set(obj.gui_h.popupmenu_dataorresult  ,'Value', 2);
                    set(obj.gui_h.popupmenu_dataorresult  ,'Enable','off');
                    set(obj.gui_h.popupmenu_modelvar2plot ,'Enable','on');
                    set(obj.gui_h.popupmenu_plottype      ,'Enable','on');
                    set(obj.gui_h.pushbutton_plot         ,'Enable','on');
                    set(obj.gui_h.popupmenu_mcc	          ,'Enable','off');
                    set(obj.gui_h.popupmenu_compmethod    ,'Enable','off');
                    set(obj.gui_h.checkbox_stats	      ,'Enable','off');
                    set(obj.gui_h.edit_pval               ,'Enable','on');
                    set(obj.gui_h.pushbutton_designadd    ,'Enable','off');% Check this
                else
                    % Disabling GUI features
                    %------------------------------------------------------
                    set(obj.gui_h.popupmenu_dataorresult  ,'Enable','off');
                    set(obj.gui_h.popupmenu_modelvar2plot ,'Enable','off');
                    set(obj.gui_h.popupmenu_plottype      ,'Enable','off');
                    set(obj.gui_h.pushbutton_plot         ,'Enable','off');
                    set(obj.gui_h.pushbutton_designadd    ,'Enable','off');
                    set(obj.gui_h.edit_pval               ,'Enable','off');
                    eeglab_warning('No group level results founded');
                end
            end
        end
        % =================================================================
        function obj = callback_popupmenu_modelvar2plot(obj,~,~)

            var2plot_indx = get(obj.gui_h.popupmenu_modelvar2plot ,'Value');
            if get(obj.gui_h.popupmenu_level,'Value') ~= 1
                obj.limofiles_level1.index = var2plot_indx;
            else
                obj.limofiles_level2.index = var2plot_indx;
            end
        end
        % =================================================================
        function obj = callback_popupmenu_plottype(obj,~,~)

            val_typeplot = get( obj.gui_h.popupmenu_plottype    ,'Value');
            val_dor      = get(obj.gui_h.popupmenu_dataorresult ,'Value');
            val_level    = get( obj.gui_h.popupmenu_level       ,'Value');

            if (val_typeplot == 1 || val_typeplot == 2)
                if val_level ~= 1
                    % Call callback_popupmenu_level
                    obj = callback_popupmenu_level(obj);
                end

                % Updating listbox_elect2plot and disabling it
                set(obj.gui_h.listbox_elect2plot   ,'Value',1);
                set(obj.gui_h.listbox_elect2plot   ,'Enable','off');

                % Disabling 'Add design' button
                if  val_dor == 1
                    set(obj.gui_h.pushbutton_designadd ,'Enable','off');
                else
                    set(obj.gui_h.pushbutton_designadd ,'Enable','on');
                end

            elseif val_typeplot == 3

                if val_level ~= 1
                    if val_dor == 2
                        listtmp = obj.regnames;
                    elseif val_dor == 1
                        listtmp = obj.catvarnames;
                    end
                    set(obj.gui_h.popupmenu_modelvar2plot ,'String',listtmp);
                    set(obj.gui_h.popupmenu_modelvar2plot ,'Value',1);
                end
                set(obj.gui_h.listbox_elect2plot   ,'Enable','on');
                set(obj.gui_h.listbox_elect2plot   ,'Value' ,2);
                set(obj.gui_h.pushbutton_designadd ,'Enable','off');
            end

        end
        % =================================================================
        function obj = callback_popupmenu_dataorresult(obj,~,~)
            val_ptype = get( obj.gui_h.popupmenu_plottype   ,'Value');
            val_dor   = get(obj.gui_h.popupmenu_dataorresult,'Value');

            % Case for data
            if val_dor == 1

                if val_ptype == 1 || val_ptype == 2
                    set(obj.gui_h.popupmenu_modelvar2plot,'String',obj.catvarnames);
                    set(obj.gui_h.popupmenu_modelvar2plot,'Value',1);
                elseif val_ptype == 3
                    set(obj.gui_h.popupmenu_modelvar2plot,'String',obj.catvarnames); % THIS MUST INCLUDE CONT!!!!!!!!!!!!!?????
                    set(obj.gui_h.popupmenu_modelvar2plot,'Value',1);
                end

                % 'Add design' disable
                set(obj.gui_h.pushbutton_designadd ,'Enable','off');

            % Case for results
            elseif val_dor == 2
                if val_ptype == 1 || val_ptype == 2
                    % Call callback_popupmenu_level
                    obj = callback_popupmenu_level(obj);

                % 'Add design' enable
                set(obj.gui_h.pushbutton_designadd ,'Enable','on');

                elseif val_ptype == 3
                    set(obj.gui_h.popupmenu_modelvar2plot,'String',obj.regnames);
                    set(obj.gui_h.popupmenu_modelvar2plot,'Value',1);

                    % Call callback_popupmenu_level
                    obj = callback_popupmenu_level(obj);

                    % 'Add design' disable
                    set(obj.gui_h.pushbutton_designadd ,'Enable','off');

                end
            end
        end
        % =================================================================
        function obj = callback_checkbox_stats(obj,~,~)

            if get(obj.gui_h.checkbox_stats        ,'Value');
                set(obj.gui_h.popupmenu_mcc        ,'Enable','on');
                set(obj.gui_h.popupmenu_compmethod ,'Enable','on');
            else
                set(obj.gui_h.popupmenu_mcc        ,'Enable','off');
                set(obj.gui_h.popupmenu_mcc        ,'Value',1);
                set(obj.gui_h.popupmenu_compmethod ,'Enable','off');
                set(obj.gui_h.popupmenu_compmethod ,'Value',1);
            end
        end
        % =================================================================
        function obj = callback_listbox_elect2plot(obj,~,~)

            valtmp_plottype = get( obj.gui_h.popupmenu_plottype,'Value');
            valtmp_chan     = get( obj.gui_h.listbox_elect2plot,'Value');

            if (valtmp_plottype == 3) && (valtmp_chan == 1)
                eeglab_warning('Invalid selection for requested plot. Selecting 1st electrode instead ');
                set(obj.gui_h.listbox_elect2plot,'Value',2);
            end
        end
        % =================================================================
        function obj = callback_plot(obj,~, ~)

             % Prepare inputs for std_limoresults
            level       = get(obj.gui_h.popupmenu_level,'Value');
            if level == 1
                levelval = 2;
                testindxval = obj.limofiles_level2.index;
            else
                subjindxval = level - 1;
                levelval    = 1;
                testindxval = obj.limofiles_level1.index;
            end
            measure_list  = {'erp','spec'};
            datorica_list = {'dat', 'ica'};
            measure_val = [datorica_list{obj.datorica_indx} measure_list{get(obj.gui_h.popupmenu_measure2plot,'Value')}];

            % DEFS
            checkbox_stat_status = get(obj.gui_h.checkbox_stats,'Value');
            if checkbox_stat_status
                handles.p = str2double(get(obj.gui_h.edit_pval,'string'));
                indxtmp      = get(obj.gui_h.popupmenu_mcc,'Value');
                handles.MCC  = indxtmp;
                handles.tfce = 0;
                handles.dir  = pwd;
                indxtmp           = get(obj.gui_h.popupmenu_compmethod,'Value');
                if indxtmp == 1
                    handles.bootstrap = 0;
                else
                    handles.bootstrap = 1;
                end
            else
                handles.p         = 0.05;
                handles.MCC       = 1;
                handles.dir       = pwd;
                handles.bootstrap = 0;
                handles.tfce      = 0;
            end

            % Determine if 'Original Data' or 'Results'
            if get(obj.gui_h.popupmenu_dataorresult,'Value') == 1
                flagdataval = 1;
            else
                flagdataval = 0 ;
            end

            % Getting the plot type
            plottypeval   = get(obj.gui_h.popupmenu_plottype,'Value');
            if plottypeval == 3
                chanindxval = get( obj.gui_h.listbox_elect2plot,'Value')-1;
                if chanindxval == 0,
                    eeglab_warning('Must select a valid electrode');
                    return;
                end
            end
            % ---------------------
            % --- Data ---
            if flagdataval == 1
                % Level 1
                if levelval == 1
                    if plottypeval ~= 3
                        std_limoresults(obj.study,'plottype',plottypeval,'flagdata',flagdataval,'measure',measure_val,'level',1,'subjindx',subjindxval,'regressor',obj.cat_indx(get(obj.gui_h.popupmenu_modelvar2plot,'value')));
                    else
                        std_limoresults(obj.study,'plottype',3,'flagdata',flagdataval,'measure',measure_val,'level',1,'subjindx',subjindxval,'regressor',obj.cat_indx(get(obj.gui_h.popupmenu_modelvar2plot,'value')),'chanindx',chanindxval);
                    end
                    % Level 2
                else
                    fprintf('Under construction');

                end
            % --- Results ---
            else
                % Level 1
                if levelval == 1
                    if plottypeval ~= 3
                    std_limoresults(obj.study,'plottype',plottypeval,'flagdata',0,'measure',measure_val,'level',1,'subjindx',subjindxval,'testindx',testindxval);
                    else
                        std_limoresults(obj.study,'plottype',3,'flagdata',0,'measure',measure_val,'level',1,'subjindx',subjindxval,'regressor',obj.reg_indx(get(obj.gui_h.popupmenu_modelvar2plot,'value')),'chanindx',chanindxval);
                    end

                % Level 2
                else
                    if plottypeval ~= 3
                    std_limoresults(obj.study,'plottype',plottypeval,'flagdata',0,'measure',measure_val,'level',2,'testindx',testindxval);
                    else
                        std_limoresults(obj.study,'plottype',3,'flagdata',0,'measure',measure_val,'level',2,'testindx',testindxval,'chanindx',chanindxval);
                    end
                end
            end
        end
        % =================================================================
        function obj = callback_pushbutton_designadd(obj,~,~)
            clear -global LIMO;

            val_level  = get( obj.gui_h.popupmenu_level        ,'Value');
            val_mplot  = get(obj.gui_h.popupmenu_measure2plot  ,'Value');
            stringtmp  = get(obj.gui_h.popupmenu_modelvar2plot ,'String');
            pwdtmp = pwd;
            limo_contrast_manager(fullfile(obj.limofiles_path,'LIMO.mat'));
            cd(pwdtmp);
            htmp = findall(0,'Type','Figure','Tag','figure_limo_contrast_manager');
            if ~isempty(htmp)
                waitfor(htmp); clear htmp;
            end
            % Get new generated file and add it to the list as current
            % ---------------------------------------------------------
            [currentfiles,tmp,tmp,STUDY] = getmeasures2plot(obj.study,val_level-1,val_mplot,obj.datorica_indx,1);
            obj.study = STUDY;
            newfile = setdiff(currentfiles.guiname,stringtmp);
            if ~isempty(newfile)
                %stringtmp(end+1) = newfile;
                set(obj.gui_h.popupmenu_modelvar2plot,'String',currentfiles.guiname);
                set(obj.gui_h.popupmenu_modelvar2plot,'Value',length(currentfiles.guiname));
                %obj.limofiles_filename = newfile{1};
            else
                set(obj.gui_h.popupmenu_modelvar2plot,'Value',1);
            end
        end
    end
end
% =================================================================
%% =================================================================
function [handles,STUDY] = guibuilder(STUDY,analysis)

% Create list "Level of Analysis" (Using First Subject)
%--------------------------------------------------------------------------
subjnames = STUDY.design(STUDY.currentdesign).cases.value;

listlevel = {'Group (Level 2)'};
for i=1:length(subjnames)
    listlevel{i+1,1} = [subjnames{i} ' (Level 1)'];
end

% Create list for "Measures to Plot" (Using First Subject and first measure available)
%--------------------------------------------------------------------------
measure2plot_list     = {'ERP','Power Spectrum'};
datorica_list         = {'dat', 'ica'};
measure2plot_internal = {'erp','spec'};
datorica              =  find(strcmp(analysis,datorica_list));

for i = 1:length(measure2plot_internal)
    measure_flag{i} = any(cellfun(@(x) ~isempty(x),strfind({STUDY.design(STUDY.currentdesign).limo.datatype},measure2plot_internal{i})));
end
measure_flag = cell2mat(measure_flag);

% Create list "Variable to Plot" (Using First Subject)
%--------------------------------------------------------------------------
if ~logical(sum(measure_flag))
    var2plot_list = {'No Variable has been found'};
    var2plot_indx = 1;
else
    tmp = find(measure_flag);
    measure2plot_indx = tmp(1); % With this we are forcing to pick the first measure available
    [var2plot,tmp,tmp,STUDY] = getmeasures2plot(STUDY,1,measure2plot_indx,datorica,1);
    if ~iscell(var2plot)
        var2plot_list = var2plot.guiname;
    else
        var2plot_list = var2plot;
    end
    % Getting index of  'Condition_effect_1.mat' for default value
    var2plot_indx = find(strcmp(var2plot.guiname,'Condition_effect_1'), 1);
    if isempty(var2plot_indx)
        var2plot_indx = find(strcmp(var2plot.guiname,'Covariate_effect_1'),1);
    end
end

% Create list elect2plot_list
%--------------------------------------------------------------------------
tmpchan         =  struct2cell(STUDY.changrp(1,:));
electoplot_list = ['All Channels';{tmpchan{1,1,:}}'];
electoplot_indx = 1;

% TOOLTIPS texts
%--------------------------------------------------------------------------

ttiptext{1} = ['Group or individual analysis. Individual analysis' 10 ...          % ttiptext_level
    'is the same a single subject analysis.' 10 ...
    'Group analysis is the analysis of a group of subjects.'];
ttiptext{2} = ['EEG measure to plot.' 10 '(ERP/Log Spectrum)'];                    % ttiptext_m2plot
ttiptext{3} = 'Select to plot Original Data or Results from the Linear Model';     % ttiptext_dorresult
ttiptext{4} = ['Selection of experimental conditions, subject groups, other' 10 ...% ttiptext_mvar2plot
    'regressors and contrast. Some options might be shaded out' 10 ...
    'based on the ?Plot Type?selected below.'];
ttiptext{5} = 'Select type of plot';                                                % ttiptext_plottype
ttiptext{6} = 'Select p-value to compute statistic';                                % ttiptext_pval
ttiptext{7} = 'Select the channels to be used in the plot';                         % ttiptext_chan

ttiptext{8} = 'Select Multiple Comparisons Method';
ttiptext{9} = 'Select Computational Approach to Perform Multiple Comparisons';
% Stuff for texts
%--------------------------------------------------------------------------
textnames = {'text_level','text_measure2plot','text_plottype','text_dataorresult','text_modelvar2plot','text_pval','text_elect2plot','text_mcc','text_compmethod'};
textpos   = {[0.0349 0.941 0.333 0.0428],...
    [0.0349 0.832 0.306 0.0592],...
    [0.0349 0.737 0.186 0.0625],...
    [0.0349 0.655 0.422 0.0526],...
    [0.0349 0.562 0.422 0.0526],...
    [0.0349 0.48 0.399 0.0428 ],...
    [0.0349 0.378 0.345 0.0428],...
    [0.0426 0.591 0.705 0.242 ],...
    [0.0426 0.227 0.481 0.197]};
textstring = {'Level of Analysis','Data Measure','Plot Type','Data or Results','Variable to Plot','Threshold (p-value )','Electrodes to Plot','Method','Computational Approach'};
% Stuff for popupmenus
%--------------------------------------------------------------------------
plottype_list    = {'Combined Plot','Scalp Maps Series','Time Course'};
datorresult_list = {'Data';'Linear Model Results'};
mcc_list         = {'None';'Clustering';'TFCE';'Max'};
compmethod_list  = {'None','Default Method'};
xalign1          = 0.450; %0.481;
popupnames = {'popupmenu_level','popupmenu_measure2plot','popupmenu_plottype','popupmenu_dataorresult','popupmenu_modelvar2plot','popupmenu_mcc','popupmenu_compmethod'};
popuppos   = {[xalign1 0.921 0.550 0.0625],...           % level
              [xalign1 0.829 0.550 0.0625],...           % measure2plot
              [xalign1 0.737 0.550 0.0625],...           % plottype
              [xalign1 0.645 0.550 0.0625],...           % dataorresult
              [xalign1+0.08 0.553 0.550-0.08 0.0625],... % modelvar2plot
              [0.535 0.561 0.465 0.273 ],...             % mcc
              [0.535 0.152 0.465 0.273]};                % compmethod
popupstring = {listlevel,measure2plot_list,plottype_list,datorresult_list,var2plot_list,mcc_list,compmethod_list};
popupindex  = {2,measure2plot_indx,1,2,var2plot_indx,1,1};
%-------------------------------------------------------------------------
compmethod_list = {''};                                                    % UPDATE THIS
pval_default    = num2str(0.5);
icadefs;
color           = BACKEEGLABCOLOR;

% Figure
%--------------------------------------------------------------------------
handles.fig = figure('MenuBar','none',...
    'Name','pop_limoresults',...
    'NumberTitle','off',...
    'Units', 'Points',...
    'Color', color,...
    'Position',[549.072 185.686 283.538 466.212],...
    'Resize', 'off');

%Panel 1 (Plot Settings)
%--------------------------------------------------------------
% Panel
handles.panel_1 = uipanel('parent',handles.fig,...
    'units','normalized',...
    'position',[0.0182 0.306 0.956 0.683],...
    'title','Plot Settings',...
    'FontSize',12,...
    'backgroundcolor',color,...
    'FontWeight','bold',...
    'Tag', 'panel_1');

%Panel 2 (Compute Statistics)
%--------------------------------------------------------------------------
handles.panel_2 = uipanel('parent',handles.fig,...
    'units','normalized',...
    'position',[0.0182 0.12 0.956 0.173],...
    'title','Correct for Multiple Comparisons',... % 'Compute Statistics (optional)'
    'backgroundcolor',color,...
    'FontSize',12,...
    'FontWeight','bold',...
    'Tag','panel_2');

% Texts
%--------------------------------------------------------------------------
for i = 1:length(textnames)
    if i > 7 parent = handles.panel_2 ; else parent = handles.panel_1; end

    handles.(textnames{i}) = uicontrol('parent'              ,parent ,...
        'style'               ,'text',...
        'units'               ,'normalized',...
        'position'            ,textpos{i},...
        'string'              ,textstring{i},...
        'FontSize'            ,11,...
        'HorizontalAlignment' ,'left',...
        'backgroundcolor'     ,color,...
        'tooltipString'       ,ttiptext{i},...
        'Tag'                 ,textnames{i});
end

% Popups Menus
%--------------------------------------------------------------------------
ttip_popup = {ttiptext{[1:5,8,9]}};
for i = 1:length(popupnames)
    if i > 5 parent = handles.panel_2; else parent = handles.panel_1; end

    handles.(popupnames{i}) = uicontrol('parent'        ,parent,...
        'style'         ,'popupmenu',...
        'units'         ,'normalized',...
        'position'      ,popuppos{i},...
        'string'        ,popupstring{i},...
        'value'         ,popupindex{i},...
        'Fontsize'      ,10,...
        'tooltipString' ,ttip_popup{i},...
        'Tag'           ,popupnames{i});
end
set(handles.popupmenu_mcc,       'Enable','off');
set(handles.popupmenu_compmethod,'Enable','off');

% Edit
handles.edit_pval = uicontrol('parent',handles.panel_1,...
    'style','edit',...
    'units','normalized',...
    'position',[xalign1+0.02 0.451 0.271 0.0724],...
    'string',pval_default,...
    'backgroundcolor',[0.929 0.929 0.929],...
    'tooltipString',ttiptext{6},...
    'Tag','edit_pval');

% List
handles.listbox_elect2plot = uicontrol('parent',handles.panel_1,...
    'style','listbox',...
    'units','normalized',...
    'position',[xalign1+0.02 0.0263 0.488 0.395],...
    'string',electoplot_list,...
    'Value',electoplot_indx,...
    'backgroundcolor',[0.929 0.929 0.929],...
    'FontSize',11,...
    'enable','off',...
    'tooltipString',ttiptext{7},...
    'Tag','listbox_elect2plot');

%Panel 2 (Compute Statistics)
%--------------------------------------------------------------------------
% Checkbox
handles.checkbox_stats = uicontrol('parent',handles.fig,...
    'style','checkbox',...
    'units','normalized',...
    'position',[0.73 0.253 0.106 0.0493],...
    'string','',...
    'backgroundcolor',color,...
    'Tag','checkbox_stats');

% Button
handles.pushbutton_plot = uicontrol('parent',handles.fig,...
    'style','pushbutton',...
    'units','normalized',...
    'position',[0.113 0.0321 0.766 0.0664],...
    'string','PLOT',...
    'backgroundcolor',[0.929 0.929 0.929],...
    'Tag', 'pushbutton_plot');

% Button add design
handles.pushbutton_designadd = uicontrol('parent',handles.panel_1,...
    'style','pushbutton',...
    'units','normalized',...
    'position',[xalign1+0.02 0.553+0.005 0.07 0.0625 - 0.005],...
    'string','+',...
    'FontWeight','bold',...
    'FontSize', 12,...
    'tooltipString','Add contrast',...
    'backgroundcolor',[0.929 0.929 0.929],...
    'Tag', 'pushbutton_designadd');
end

%% =================================================================
function [var2plot,filespath,limoindx,STUDY] = getmeasures2plot(STUDY,subjN,measureindx,datoricaindx,checknewfile_flag)

% measureindx  is the index to {'erp','spec'}
% datoricaindx is the index to {'dat', 'ica'}

% Init
filespath = [];
limoindx = [];
var2plot.guiname{1}  = 'No Variables Computed';
measure_list         = {'erp','spec'};
datorica_list        = {'dat', 'ica'};
if ~exist('checknewfile_flag','var'), checknewfile_flag = 0; end

requested_datatype = [datorica_list{datoricaindx} measure_list{measureindx}];
measures_computed  = {STUDY.design(STUDY.currentdesign).limo.datatype};

for i = 1:length(measure_list)
    measure_flag{i} = any(cellfun(@(x) ~isempty(x),strfind(measures_computed,measure_list{i})));
end
measure_flag = cell2mat(measure_flag);

% Warning for gui
if ~logical(sum(measure_flag))
    eeglab_warning('No results have been found for this subject');
end
if ismember(requested_datatype,measures_computed)
    limoindx  = find(strcmp(requested_datatype,measures_computed));
    % Generating list
    %----------------
    filespath         = STUDY.design(STUDY.currentdesign).limo(limoindx).basefolder_level1{subjN};

    if checknewfile_flag
        tmp = dir(filespath);
        if ~isempty({tmp.name})
            var2plot_list        = {tmp.name}';

            % Cleaning out the list
            %----------------------
            list2cleanout = {'Betas.mat','LIMO.mat','Yr.mat','Yhat.mat','Res.mat','.','..'};
            for i = 1:length(list2cleanout)
                ind2delete{i} = find(strcmp(var2plot_list,list2cleanout{i}));
            end
            nonemptyvals              = find(cellfun(@(x) ~isempty(x), ind2delete));
            ind2delete                = [ind2delete{nonemptyvals}];
            var2plot_list(ind2delete) = [];

            %Update STUDY

            [newfiles, newfilesindx] = setdiff(cellfun(@(x) fullfile(filespath,x),var2plot_list,'UniformOutput', false),STUDY.design(STUDY.currentdesign).limo(limoindx).model(subjN).filename);
            if ~isempty(newfiles)
                STUDY.design(STUDY.currentdesign).limo(limoindx).model(subjN).guiname(newfilesindx) = cellfun(@(x) x(1:end-4),var2plot_list(newfilesindx),'UniformOutput', false);
                STUDY.design(STUDY.currentdesign).limo(limoindx).model(subjN).filename(newfilesindx) = cellfun(@(x) fullfile(filespath,x),var2plot_list(newfilesindx),'UniformOutput', false);
                STUDY = pop_savestudy( STUDY, [],'filepath', STUDY.filepath,'savemode','resave');
                display('pop_limoresults: New contrast files added to STUDY ');
            end
        end
    end

    var2plot.guiname  = (STUDY.design(STUDY.currentdesign).limo(limoindx).model(subjN).guiname);
    var2plot.pathname = (STUDY.design(STUDY.currentdesign).limo(limoindx).model(subjN).filename);
end
end

% =================================================================
function eeglab_warning(text)

icadefs;
eeglabcolor = BACKEEGLABCOLOR;
h           = warndlg(text,'EEGLAB Warning');
set(h,'color', eeglabcolor);

uiwait(h);
end


%kkedit ' '
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kedit.pane file
%
% Parameters:
% InputFile: i 'Input File', optional: 'Input ASCII file'
% OutputFile: o 'Output File', optional: 'Resulting output ASCII File'
%
% Example: o = kkedit(i, {'i','';'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kedit - ASCII file editor
%
%  DESCRIPTION
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc.  All rights reserved.
%

function varargout = kkedit(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kkedit(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'o', '__output'};
maxval={1,1};
minval={1,1};
istoggle=[1,1];
was_set=istoggle * 0;
paramtype={'InputFile','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=0; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'kedit"  '],Inputs,narglist);


% Defines a parameter
%
% Author: Jonathan Karr
% Affilitation: Covert Lab, Department of Bioengineering, Stanford University
% Last updated: 11/17/2009
classdef Parameter < edu.stanford.covert.cell.kb.KnowledgeBaseObject
    properties
        process          = edu.stanford.covert.cell.kb.Process.empty(0, 0);
        state           = edu.stanford.covert.cell.kb.State.empty(0, 0);
        reactions       = edu.stanford.covert.cell.kb.Reaction.empty(0, 0);
        proteinMonomers = edu.stanford.covert.cell.kb.ProteinMonomer.empty(0, 0);
        proteinComplexs = edu.stanford.covert.cell.kb.ProteinComplex.empty(0, 0);
    end

    properties %(SetAccess = protected)
        index
        defaultValue
        units
        experimentallyConstrained
    end

    methods
        function this = Parameter(knowledgeBase, wid, wholeCellModelID, name, ...
                index, defaultValue, units, experimentallyConstrained, ...
                comments, crossReferences)

            if nargin == 0; return; end;

            this = edu.stanford.covert.cell.kb.Parameter.empty(size(wid, 1), 0);
            this(size(wid, 1), 1) = edu.stanford.covert.cell.kb.Parameter;
            for i = 1:size(wid, 1)
                this(i, 1).idx = i;
                this(i, 1).knowledgeBase = knowledgeBase;
                this(i, 1).wid = wid(i);
                this(i, 1).wholeCellModelID = wholeCellModelID{i};
                this(i, 1).name = name{i};
                this(i, 1).index = index{i};
                this(i, 1).defaultValue = this.parseDefaultValue(defaultValue{i});
                this(i, 1).units = units{i};
                this(i, 1).experimentallyConstrained = experimentallyConstrained(i);
                if exist('comments','var') && ~isempty(comments); this(i,1).comments = comments{i}; end;
                if exist('crossReferences', 'var')
                    if size(crossReferences, 1) > 1
                        this(i, 1).crossReferences = crossReferences(i);
                    else
                        this(i, 1).crossReferences = struct;
                        fields = fieldnames(crossReferences);
                        for j = 1:size(fields,1)
                            values = crossReferences.(fields{j});
                            this(i, 1).crossReferences.(fields{j}) = values(i);
                        end
                    end
                end
            end
        end

        function serializeLinks(this)
            for i = 1:numel(this)
                this(i).process         = this.serializeLinksHelper(this(i).process);
                this(i).state           = this.serializeLinksHelper(this(i).state);
                this(i).reactions       = this.serializeLinksHelper(this(i).reactions);
                this(i).proteinMonomers = this.serializeLinksHelper(this(i).proteinMonomers);
                this(i).proteinComplexs = this.serializeLinksHelper(this(i).proteinComplexs);
                serializeLinks@edu.stanford.covert.cell.kb.KnowledgeBaseObject(this(i))
            end
        end

        function deserializeLinks(this, kb)
            for i = 1:numel(this)
                this(i).process         = this.deserializeLinksHelper(this(i).process, kb.processes);
                this(i).state           = this.deserializeLinksHelper(this(i).state, kb.states);
                this(i).reactions       = this.deserializeLinksHelper(this(i).reactions, kb.reactions);
                this(i).proteinMonomers = this.deserializeLinksHelper(this(i).proteinMonomers, kb.proteinMonomers);
                this(i).proteinComplexs = this.deserializeLinksHelper(this(i).proteinComplexs, kb.proteinComplexs);
                deserializeLinks@edu.stanford.covert.cell.kb.KnowledgeBaseObject(this(i), kb);
            end
        end

        function deleteLinks(this)
            for i = 1:numel(this)
                this(i).process         = [];
                this(i).state           = [];
                this(i).reactions       = [];
                this(i).proteinMonomers = [];
                this(i).proteinComplexs = [];
                deleteLinks@edu.stanford.covert.cell.kb.KnowledgeBaseObject(this(i))
            end
        end
    end

    methods (Static = true)
        function parsedValue = parseDefaultValue(rawValue)
            if isempty(rawValue)
                parsedValue = {};
                return;
            end

            if iscell(rawValue) && numel(rawValue) == 1
                rawValue = rawValue{1};
            end

            rawValue = strsplit(';', rawValue)';
            parsedValue = zeros(size(rawValue));
            for i = 1:length(rawValue)
                parsedValue(i) = str2double(rawValue{i});
            end
            if any(isnan(parsedValue))
                parsedValue = rawValue;
            end
        end
    end
end


% The COBRAToolbox: testTranslateMetagenome2AGORA.m
%
% Purpose:
%     - tests the basic functionality of translateMetagenome2AGORA
%
% Authors:
%     - Almut Heinken - March 2019
%
% Ensure that the organisms in the input file were correctly translated.
% This is the case if all organisms in the output file correspond to an
% AGORA strain model or AGORA pan-model.
% Note that this test cannot tell if the biological identity of the
% translated organisms is correct as this requires manual inspection.
% Moreover, input files with abundance data from other source may fail due
% to differences in formatting and nomenclature.

if ispc && exist('AGORA_infoFile.xlsx','file')
    % Read in the info file with all AGORA strains and taxa
    [~, infoFile, ~] = xlsread('AGORA_infoFile.xlsx');

    % Download an example file with abundance data from EMBL-EBI
    system('curl -O https://www.ebi.ac.uk/metagenomics/api/v1/studies/MGYS00001248/pipelines/3.0/file/SRP065497_taxonomy_abundances_v3.0.tsv')

    % Test the output file on different taxonomical levels
    % Note: On phylum and class level, some samples sum up to zero due to too
    % few corresponding data points in the input file. Thus, these taxon levels
    % cannot be tested.
    taxLevels={
        'Species'
        'Genus'
        'Family'
        'Order'
        };

    for t=1:size(taxLevels,1)
        fprintf([' > Running translateMetagenome2AGORA with ' taxLevels{t,1} '...\n']);
        % Define the taxon level of the input file
        orgList=unique(infoFile(2:end,find(strcmp(taxLevels{t,1},infoFile(1,:)))));
        orgList(strncmp('unclassified', orgList, 12)) = [];
        [translatedAbundances,normalizedAbundances,unmappedRows]=translateMetagenome2AGORA('SRP065497_taxonomy_abundances_v3.0.tsv',taxLevels{t,1});

        % Verify that the output file is not empty
        assert(size(translatedAbundances,1)>1)

        fprintf(' > Output file is not empty.\n');

        if size(translatedAbundances,1)>1
            translatedOrgs=translatedAbundances(2:end,1);
            translatedOrgs=strrep(translatedOrgs,'pan','');
            translatedOrgs=strrep(translatedOrgs,'_',' ');

            % Find the overlap between translated organisms and AGORA organisms
            C = intersect(translatedOrgs,orgList);

            % Verify that all output organisms overlap with AGORA organisms
            assert(length(translatedOrgs) == length(C))
        end

        % Verify that the relative abundances for each sample sum up to 1
        for i=2:size(normalizedAbundances,2)
            assert(sum(str2double(normalizedAbundances(2:end,i)))-1 < 0.0001)
        end

        fprintf([' > Testing tax level ' taxLevels{t,1} ' done.\n']);
    end

    % output a success message
    fprintf('Done.\n');
else
    fprintf('Could not run testTranslateMetagenome2AGORA because AGORA_infoFile.xlsx not found or this is not a windows pc')
end


function Conn = hlp_subtractConnectivity(Conn1,Conn2)
    % return a Connectivity object containing the difference in
    % connectivity between two datasets

    Conn = Conn1;

    connmethods = hlp_getConnMethodNames(Conn1);

    for c=1:length(connmethods)
        Conn.(connmethods{c}) = Conn1.(connmethods{c}) - Conn2.(connmethods{c});
    end

    otherfields = setdiff_bc(fieldnames(Conn1),connmethods);
    for f=1:length(otherfields)
        Conn.(otherfields{f}) = Conn1.(otherfields{f});
    end


function varargout = visualization(mode,image_dir,varargin)

switch mode

  % init figure
  case 'init'

    % create figure using size of first image in repository
    fig = figure(1);
    img = imread(sprintf('%s/%010d.png',image_dir,0));
    set(fig,'position',[100,100,0.8*size(img,2),0.8*2*size(img,1)]);
    h(1).axes = axes('position',[0,0.5,1,0.5]);
    h(2).axes = axes('position',[0,0,1,0.5]);
    varargout{1} = h;

  % update figure
  case 'update'

    % unpack input arguments
    h        = varargin{1};
    img_idx  = varargin{2};
    nimages  = varargin{3};

    % read image
    img = imread(sprintf('%s/%010d.png',image_dir,img_idx));

    % clear axes, draw image
    cla(h(1).axes); cla(h(2).axes);
    imshow(img,'parent',h(1).axes); axis(h(1).axes,'image','off'); hold(h(1).axes, 'on');
    imshow(img,'parent',h(2).axes); axis(h(2).axes,'image','off'); hold(h(2).axes, 'on');

    % title
    text(size(img,2)/2,3,sprintf('2D Bounding Boxes'),'parent',h(1).axes,'color','g','HorizontalAlignment','center','VerticalAlignment','top','FontSize',14,'FontWeight','bold','BackgroundColor','black');
    text(size(img,2)/2,3,sprintf('3D Bounding Boxes'),'parent',h(2).axes,'color','g','HorizontalAlignment','center','VerticalAlignment','top','FontSize',14,'FontWeight','bold','BackgroundColor','black');

    % legend
    text(0,00,'Not occluded','parent',h(1).axes,'color','g','HorizontalAlignment','left','VerticalAlignment','top','FontSize',14,'FontWeight','bold','BackgroundColor','black');
    text(0,30,'Partly occluded','parent',h(1).axes,'color','y','HorizontalAlignment','left','VerticalAlignment','top','FontSize',14,'FontWeight','bold','BackgroundColor','black');
    text(0,60,'Fully occluded','parent',h(1).axes,'color','r','HorizontalAlignment','left','VerticalAlignment','top','FontSize',14,'FontWeight','bold','BackgroundColor','black');
    text(0,90,'Unknown','parent',h(1).axes,'color','w','HorizontalAlignment','left','VerticalAlignment','top','FontSize',14,'FontWeight','bold','BackgroundColor','black');

    % frame number
    text(size(img,2),0,sprintf('frame %d/%d',img_idx,nimages-1), 'parent', h(1).axes,'color','g','HorizontalAlignment','right','VerticalAlignment','top','FontSize',14,'FontWeight','bold','BackgroundColor','black', 'Interpreter','none');

    % usage instructions
    text(size(img,2)/2,size(img,1),sprintf('''SPACE'': Next Image  |  ''-'': Previous Image  |  ''x'': +100  |  ''y'': -100 | ''q'': quit'), 'parent', h(2).axes,'color','g','HorizontalAlignment','center','VerticalAlignment','bottom','FontSize',14,'FontWeight','bold', 'BackgroundColor','black');
end


close all;clear;
load 'x1'
load 'x2'
load 'x3'
load 'x4'
load 'x5'

addpath 'uavShow'

sim('mavsim_show');


function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
%    or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (q.fang <at> neu.edu)
% created on 2013/08/01
%
% $Id$
%
% input:
%      fname: input file name, if fname contains "{}" or "[]", fname
%             will be interpreted as a UBJSON string
%      opt: a struct to store parsing options, opt can be replaced by
%           a list of ('param',value) pairs - the param string is equivalent
%           to a field in opt. opt can have the following
%           fields (first in [.|.] is the default)
%
%           opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
%                         for each element of the JSON data, and group
%                         arrays based on the cell2mat rules.
%           opt.IntEndian [B|L]: specify the endianness of the integer fields
%                         in the UBJSON input data. B - Big-Endian format for
%                         integers (as required in the UBJSON specification);
%                         L - input integer fields are in Little-Endian order.
%           opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or
%                         earlier versions (JSONLab 1.0 final or earlier),
%                         the "name" tag is treated as a string. To load
%                         these UBJSON data, you need to manually set this
%                         flag to 1.
%
% output:
%      dat: a cell array, where {...} blocks are converted into cell arrays,
%           and [...] are converted to arrays
%
% examples:
%      obj=struct('string','value','array',[1 2 3]);
%      ubjdata=saveubjson('obj',obj);
%      dat=loadubjson(ubjdata)
%      dat=loadubjson(['examples' filesep 'example1.ubj'])
%      dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
%     BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

global pos inStr len  esc index_esc len_esc isoct arraytoken fileendian systemendian

if(regexp(fname,'[\{\}\]\[]','once'))
   string=fname;
elseif(exist(fname,'file'))
   fid = fopen(fname,'rb');
   string = fread(fid,inf,'uint8=>char')';
   fclose(fid);
else
   error('input file does not exist');
end

pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\','  ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);

% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);

opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;

jsoncount=1;
while pos <= len
    switch(next_char)
        case '{'
            data{jsoncount} = parse_object(opt);
        case '['
            data{jsoncount} = parse_array(opt);
        otherwise
            error_pos('Outer level structure must be an object or an array');
    end
    jsoncount=jsoncount+1;
end % while

jsoncount=length(data);
if(jsoncount==1 && iscell(data))
    data=data{1};
end

%%-------------------------------------------------------------------------
function object = parse_object(varargin)
    parse_char('{');
    object = [];
    type='';
    count=-1;
    if(next_char == '$')
        type=inStr(pos+1); % TODO
        pos=pos+2;
    end
    if(next_char == '#')
        pos=pos+1;
        count=double(parse_number());
    end
    if next_char ~= '}'
        num=0;
        while 1
            if(jsonopt('NameIsString',0,varargin{:}))
                str = parseStr(varargin{:});
            else
                str = parse_name(varargin{:});
            end
            if isempty(str)
                error_pos('Name of value at position %d cannot be empty');
            end
            %parse_char(':');
            val = parse_value(varargin{:});
            num=num+1;
            object.(valid_field(str))=val;
            if next_char == '}' || (count>=0 && num>=count)
                break;
            end
            %parse_char(',');
        end
    end
    if(count==-1)
        parse_char('}');
    end
    if(isstruct(object))
        object=struct2jdata(object);
    end

%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
    cid=dataclass{id};
    len=bytelen(id);
else
    error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------

function [data, adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
    newdata=int8(datastr);
else
    newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(fileendian~=systemendian)
    newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);

%%-------------------------------------------------------------------------

function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr
    parse_char('[');
    object = cell(0, 1);
    dim=[];
    type='';
    count=-1;
    if(next_char == '$')
        type=inStr(pos+1);
        pos=pos+2;
    end
    if(next_char == '#')
        pos=pos+1;
        if(next_char=='[')
            dim=parse_array(varargin{:});
            count=prod(double(dim));
        else
            count=double(parse_number());
        end
    end
    if(~isempty(type))
        if(count>=0)
            [object, adv]=parse_block(type,count,varargin{:});
            if(~isempty(dim))
                object=reshape(object,dim);
            end
            pos=pos+adv;
            return;
        else
            endpos=matching_bracket(inStr,pos);
            [cid,len]=elem_info(type);
            count=(endpos-pos)/len;
            [object, adv]=parse_block(type,count,varargin{:});
            pos=pos+adv;
            parse_char(']');
            return;
        end
    end
    if next_char ~= ']'
         while 1
            val = parse_value(varargin{:});
            object{end+1} = val;
            if next_char == ']'
                break;
            end
            %parse_char(',');
         end
    end
    if(jsonopt('SimplifyCell',0,varargin{:})==1)
      try
        oldobj=object;
        object=cell2mat(object')';
        if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
            object=oldobj;
        elseif(size(object,1)>1 && ismatrix(object))
            object=object';
        end
      catch
      end
    end
    if(count==-1)
        parse_char(']');
    end

%%-------------------------------------------------------------------------

function parse_char(c)
    global pos inStr len
    skip_whitespace;
    if pos > len || inStr(pos) ~= c
        error_pos(sprintf('Expected %c at position %%d', c));
    else
        pos = pos + 1;
        skip_whitespace;
    end

%%-------------------------------------------------------------------------

function c = next_char
    global pos inStr len
    skip_whitespace;
    if pos > len
        c = [];
    else
        c = inStr(pos);
    end

%%-------------------------------------------------------------------------

function skip_whitespace
    global pos inStr len
    while pos <= len && isspace(inStr(pos))
        pos = pos + 1;
    end

%%-------------------------------------------------------------------------
function str = parse_name(varargin)
    global pos inStr
    bytelen=double(parse_number());
    if(length(inStr)>=pos+bytelen-1)
        str=inStr(pos:pos+bytelen-1);
        pos=pos+bytelen;
    else
        error_pos('End of file while expecting end of name');
    end
%%-------------------------------------------------------------------------

function str = parseStr(varargin)
    global pos inStr
 % len, ns = length(inStr), keyboard
    type=inStr(pos);
    if type ~= 'S' && type ~= 'C' && type ~= 'H'
        error_pos('String starting with S expected at position %d');
    else
        pos = pos + 1;
    end
    if(type == 'C')
        str=inStr(pos);
        pos=pos+1;
        return;
    end
    bytelen=double(parse_number());
    if(length(inStr)>=pos+bytelen-1)
        str=inStr(pos:pos+bytelen-1);
        pos=pos+bytelen;
    else
        error_pos('End of file while expecting end of inStr');
    end

%%-------------------------------------------------------------------------

function num = parse_number(varargin)
    global pos inStr isoct fileendian systemendian
    id=strfind('iUIlLdD',inStr(pos));
    if(isempty(id))
        error_pos('expecting a number at position %d');
    end
    type={'int8','uint8','int16','int32','int64','single','double'};
    bytelen=[1,1,2,4,8,4,8];
    datastr=inStr(pos+1:pos+bytelen(id));
    if(isoct)
        newdata=int8(datastr);
    else
        newdata=uint8(datastr);
    end
    if(fileendian~=systemendian)
        newdata=swapbytes(typecast(newdata,type{id}));
    end
    num=typecast(newdata,type{id});
    pos = pos + bytelen(id)+1;

%%-------------------------------------------------------------------------

function val = parse_value(varargin)
    global pos inStr

    switch(inStr(pos))
        case {'S','C','H'}
            val = parseStr(varargin{:});
            return;
        case '['
            val = parse_array(varargin{:});
            return;
        case '{'
            val = parse_object(varargin{:});
            return;
        case {'i','U','I','l','L','d','D'}
            val = parse_number(varargin{:});
            return;
        case 'T'
            val = true;
            pos = pos + 1;
            return;
        case 'F'
            val = false;
            pos = pos + 1;
            return;
        case {'Z','N'}
            val = [];
            pos = pos + 1;
            return;
    end
    error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------

function error_pos(msg)
    global pos inStr len
    poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
    if poShow(3) == poShow(2)
        poShow(3:4) = poShow(2)+[0 -1];  % display nothing after
    end
    msg = [sprintf(msg, pos) ': ' ...
    inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
    error( ['JSONparser:invalidFormat: ' msg] );

%%-------------------------------------------------------------------------

function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
    pos=regexp(str,'^[^A-Za-z]','once');
    if(~isempty(pos))
        if(~isoct)
            str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
        else
            str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
        end
    end
    if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
        return;
    end
    if(~isoct)
        str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
    else
        pos=regexp(str,'[^0-9A-Za-z_]');
        if(isempty(pos))
            return;
        end
        str0=str;
        pos0=[0 pos(:)' length(str)];
        str='';
        for i=1:length(pos)
            str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
        end
        if(pos(end)~=length(str))
            str=[str str0(pos0(end-1)+1:pos0(end))];
        end
    end
    %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';

%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
    if(str(pos)=='"')
        if(~(pos>1 && str(pos-1)=='\'))
            endpos=pos;
            return;
        end
    end
    pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
    c=tokens(pos);
    if(c==']')
        level=level-1;
        if(isempty(e1r))
            e1r=bpos(pos);
        end
        if(level==0)
            endpos=bpos(pos);
            return
        end
    end
    if(c=='[')
        if(isempty(e1l))
            e1l=bpos(pos);
        end
        level=level+1;
        maxlevel=max(maxlevel,level);
    end
    if(c=='"')
        pos=matching_quote(tokens,pos+1);
    end
    pos=pos+1;
end
if(endpos==0)
    error('unmatched "]"');
end


function gdrawnow
% function gdrawnow
% ------------------------------------------------------------------------
% The |gdrawnow| function is similar to the |drawnow| command but also
% activates the |vcw| widget if present for the current figure window.
%
%
% Kevin Mattheus Moerman
%
% Change log:
% 2020/05/11 Created
% 2020/05/11 Added triple call to drawnow which appears to fix MATLAB bug
% when multiple figures are used and plotting occurs in the wrong figure
% window.
% 2020/05/11 Added new axis colorbar handling
% ------------------------------------------------------------------------
%%
% Force full drawnow
drawnow; drawnow;  drawnow; %Triple to avoid MATLAB bug

%% Activate vcw

hf=gcf;

if isfield(hf.UserData,'vcw')

    switch hf.UserData.vcw.buttonHandle.State
        case 'on'
            H=findobj(hf,'Type','colorbar'); %Handle set for all colorbars in figure;
            if ~isempty(H)
                if ~isempty(hf.UserData.vcw.colorbarHandles)
                    Hp=hf.UserData.vcw.colorbarHandles;
                    logicSetManual=~ismember(H,Hp);
                    if nnz(logicSetManual)>0
                        H_new=H(logicSetManual);
                        hf.UserData.vcw.colorbarHandles=[hf.UserData.vcw.colorbarHandles H_new];
                        hf.UserData.vcw.colorbarLocSet(end:end+numel(H_new))={H_new.Location};
                        for q=1:1:numel(H_new) %Loop over colorbar handles and set location property
                            set(H_new(q),'Location','manual');
                        end
                    end
                end
            end
        case 'off'
            hf.UserData.vcw.buttonHandle.State='on';
    end

    %Set default views for new axes and attempt to hide interactive toolbars
    h = findobj(hf, 'Type', 'axes', '-depth', 1)'; %All axis handles
    if ~isempty(h)
        for hNow = h
            %Set default views if not present
            if ~isfield(hNow.UserData,'defaultView')
                hNow.UserData.defaultView=camview(hNow);
            end

            %Try to hide toolbar
            try
                hNow.Toolbar.Visible = 'off';
            catch
            end
        end
    end

end

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% 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 3 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, see <http://www.gnu.org/licenses/>.


%HEATTRANSFER Heat transfer physics mode definition.

% Copyright 2013-2022 Precise Simulation, Ltd.


% ir_mex_build_table
% run matlab's "mex" command to "compile" the table interpolation code
% into mex files.

dir_current = pwd;
dir_nufft = path_find_dir('nufft');
dir_table = [dir_nufft filesep 'table'];
cd(dir_table)

% compile mex files using ir_mex_fun2 ("2" since there are two arguments)
fun = ir_mex_fun();
fun('interp1_table_adj_mex.c',	'interp1_table1_adj.c')
fun('interp1_table_mex.c',	'interp1_table1_for.c')
fun('interp2_table_adj_mex.c',	'interp2_table1_adj.c')
fun('interp2_table_mex.c',	'interp2_table1_for.c')
fun('interp3_table_adj_mex.c',	'interp3_table1_adj.c')
fun('interp3_table_mex.c',	'interp3_table1_for.c')

cd(dir_current)

% "test" mex files by running them (each should display usage)
try
	interp1_table_adj_mex
	interp1_table_mex
    interp2_table_adj_mex
    interp2_table_mex
    interp3_table_adj_mex
    interp3_table_mex
catch
    disp(['WARNING! Error compiling mex files in ', mfilename])
end