classdef ForceModelsEnum < matlab.mixin.SetGet & matlab.mixin.Heterogeneous
    %ForceModelsEnum Summary of this class goes here
    %   Detailed explanation goes here

    enumeration
        Gravity('Gravity',GravityForceModel(),false, true);
        Drag('Drag Force',DragForceModel(),true, false);
        Thrust('Thrust',ThrustForceModel(),true, false);
        Normal('Normal Force',NormalForceModel(),true, false);
        Lift('Lift Force',LiftForceModel(),true, false);
        Gravity3rdBody('3rd Body Gravity',Gravity3rdBodyForceModel(),true, true);
    end

    properties
        name char
        model AbstractForceModel
        canBeDisabled(1,1) logical = false;
        allowedForSecondOrder(1,1) logical = false
    end

    methods
        function obj = ForceModelsEnum(name, model, canBeDisabled, allowedForSecondOrder)
            obj.name = name;
            obj.model = model;
            obj.canBeDisabled = canBeDisabled;
            obj.allowedForSecondOrder = allowedForSecondOrder;
        end
    end

    methods(Static)
        function m = getEnumsOfDisablableForceModels()
            [m,~] = enumeration('ForceModelsEnum');
            m = m([m.canBeDisabled]);
        end

        function listBoxStrs = getListBoxStrs()
            [m,~] = enumeration('ForceModelsEnum');

            listBoxStrs = {};
            for(i=1:length(m)) %#ok<*NO4LP>
                listBoxStrs{end+1} = m(i).name; %#ok<AGROW>
            end
        end

        function listBoxStrs = getListBoxStrsOfDisablableModels()
            m = ForceModelsEnum.getEnumsOfDisablableForceModels();

            listBoxStrs = {};
            for(i=1:length(m)) %#ok<*NO4LP>
                listBoxStrs{end+1} = m(i).name; %#ok<AGROW>
            end
        end

        function [ind, fmE] = getIndOfListboxStrsForModel(model)
            [m,~] = enumeration('ForceModelsEnum');

            ind = -1;
            for(i=1:length(m))
                if(strcmpi(class(m(i).model),class(model)))
                    ind = i;
                    fmE = m(i);
                    break;
                end
            end
        end

        function [ind, fmE] = getIndOfDisablableListboxStrsForModel(model)
            m = ForceModelsEnum.getEnumsOfDisablableForceModels();

            ind = -1;
            for(i=1:length(m))
                if(strcmpi(class(m(i).model),class(model)))
                    ind = i;
                    fmE = m(i);
                    break;
                end
            end
        end

        function fmArr = getDefaultArrayOfForceModelEnums()
            fmArr = [ForceModelsEnum.Gravity, ForceModelsEnum.Drag, ForceModelsEnum.Thrust];
        end

        function fmArr = getAllForceModelsThatCannotBeDisabled()
            [m,~] = enumeration('ForceModelsEnum');

            fmArr = ForceModelsEnum.empty(1,0);
            for(i=1:length(m))
                if(m(i).canBeDisabled == false)
                    fmArr(end+1) = m(i); %#ok<AGROW>
                end
            end
        end
    end
end


function  write2hdf5
% write image data (and simple feature data) from one sequence to hdf5 file
% positive and negative example seperate
% IMPORTANT!!!
% All the data and labels saved into hdf5 should be sing
data_dir = '/scratch/BS/pool2/tang/multicut/pairwise_example/';
data_set = 'TownCenter-Sample';%'tud-crossing';%'ETH-Bahnhof';%'ETH-Pedcross2';%

chunksz = 1000;

positive_img_dir  = [data_dir data_set '/positive/'];
negative_img_dir  = [data_dir data_set '/negative/'];
save_dir = [data_dir data_set '/mixed_hdf5/'];
if ~exist(save_dir)
    mkdir(save_dir);
end

fprintf('Listing all the images ...\n')
positive_img_list = dir([positive_img_dir '*.jpg']);
negative_img_list = dir([negative_img_dir '*.jpg']);

num_img = length(positive_img_list) + length(negative_img_list);
num_round = (num_img/2)/chunksz;
parfor k = 1:num_round
    fprintf('Saving hdf5 file %d ...\n', k);
    last_end_img_idx = (k-1)*chunksz;

    batchdata = single(zeros(227,227,3,chunksz*2));
    batchlabs = single(zeros(1,chunksz*2));

    filename = [save_dir sprintf('%05d',last_end_img_idx + 1) '.h5'];
    count = 0;
    for i = 1:chunksz
        idx = last_end_img_idx + i;
        positive_img_name  = positive_img_list(idx);
        img = imread([ positive_img_dir positive_img_name.name]);
        % unit to single
        img = imresize(img,[227,227]);

        img =  single(img);
%         img(:,120:end,1) = 255;
        %
        img = img(:,:,[3 2 1]);
        %
        img = permute(img, [2 1 3]);
        %

        count = count +1;
        batchdata(:,:,:,count) = img;
        batchlabs(count) = 1;

        negative_img_name  = negative_img_list(idx);
        img = imread([ negative_img_dir negative_img_name.name]);
        % unit to single
        img = imresize(img,[227,227]);
        img =  single(img);
        %
        img = img(:,:,[3 2 1]);
        %
        img = permute(img, [2 1 3]);

        count = count +1;
        batchdata(:,:,:,count) = img;
        batchlabs(count) = 0;
    end
    curr_dat_sz=store2hdf5(filename, batchdata, batchlabs, 1);
end
end


%% Rearranging CHARGUI to Make it Resizable and Dockable
% This script reverse-engineers |charGUI| and rebuilds it in a way that is
% both resizable and dockable.  It does so using |uipanel| and positioning
% with normalized units.

%% Create a New CHARGUI
% First, create a new instance of |charGUI|.
f = charGUI;

%% Cache the Major GUI Components
% Next, find the major GUI components: |axes|, |uipanel|, and |uicontrol|.
% Keeping references to these items will allow us to lay them out later.
% In the meantime, turn off their visiblity so that the steps taken below
% appear clearly in the GUI.
axs = findobj(f,'type','axes');
pans = findobj(f,'type','uipanel');
uis = findobj(f,'type','uicontrol');

set(axs,'visible','off');
set(pans,'visible','off');
set(uis,'visible','off');

%% Construct a New Layout Framework
% Use |uipanel| to create the framework for the new GUI layout.  Divide the
% space into three portions using normalized units.  The first, occupying
% the upper left-hand portion of the GUI, will contain the main axes.  The
% second, occupying the right-hand quarter of the GUI, will contain the
% every |uicontrol|.  The third, occupuying the bottom 30% of the GUI in
% the left-hand 75%, will contain the processing |axes|.
newpans = zeros(1,3);
for i = 1:3
    newpans(i) = uipanel('parent',f,'units','normalized');
end
set(newpans(1),'position',[0 .3 .75 .7]);
set(newpans(2),'position',[.75 0 .25 1]);
set(newpans(3),'position',[0 0 .75 .3]);

%% Populate the First Panel
% By putting the main set of |axes| into a |uipanel|, it can be laid out
% relative to the panel, as opposed to the whole GUI.  Use normalized
% units to make sure that the |axes| grow when the |uipanel| grows.
% Position it starting 10% up from the bottom and 10% right from the
% left-hand side of the GUI and have it occupy 80% of the horizontal and
% vertical |uipanel| space.
set(axs(1),'parent',newpans(1),'units','normalized',...
    'position',[.1 .1 .8 .8]);
set(get(newpans(1),'children'),'visible','on');

%% Populate the Second Panel
% Parent the |uicontrol| items to the second |uipanel|.  Maintain the
% use of characters units so that each |uicontrol| will not grow and shrink
% along with the |uipanel|.  Instead, each will maintain the same size and
% placement.
set(uis,'parent',newpans(2));
newuipos = get(uis(1),'position');
newuipos(1:2) = [2 1];
set(uis(1),'position',newuipos);
newuipos = get(uis(3),'position');
newuipos(1:2) = [2 14];
set(uis(3),'position',newuipos);
newuipos(1:2) = [2 18];
set(uis(4),'position',newuipos);
newuipos(1:2) = [2 22];
set(uis(5),'position',newuipos);
newuipos(1:2) = [2 26];
set(uis(6),'position',newuipos);
newuipos(1:2) = [2 30];
set(uis(2),'position',newuipos);
newuipos(1:2) = [2 34];
set(uis(7),'position',newuipos);
set(get(newpans(2),'children'),'visible','on');

%% Populate the Third Panel
% Each processing |axes| are already contained within a |uipanel|, which
% merely needs to be positioned within one containing |uipanel|.  Again,
% use normalized units so that these will grow and shrink with the
% containing |uipanel|.
%
% Also apply normalized units and new positions to the |axes| contained in
% the subpanels.  Doing so will fill in the GUI space and allow us, as the
% GUI grows, to see more detail in the processing.
set(pans,'parent',newpans(3),'units','normalized');
set(pans(4),'position',[.01 .025 .23 .95]);
set(pans(3),'position',[.26 .025 .23 .95]);
set(pans(2),'position',[.51 .025 .23 .95]);
set(pans(1),'position',[.76 .025 .23 .95]);
set(axs(2:5),'units','normalized','position',[.05 .05 .9 .9]);
set(get(newpans(3),'children'),'visible','on');

%% Touch Up the GUI and Make it Resizable
% Put the finishing touches on the GUI.  Apply the same background colors
% that exsited before to each new |uipanel| and remove the border.  The
% |figure| can now be made resizable.  Try docking it by setting its
% |windowstyle| property!
for i = 1:3
    set(newpans(i),'backgroundcolor',get(pans(1),'backgroundcolor'),...
        'bordertype','none');
end
set(f,'resize','on');


%% HELLO_FSU uses the fsuClusterMatlab command to run the HELLO "computation".
%
%  Discussion:
%
%    The arguments to fsuClusterMatlab mean:
%
%    '~/matlab/hello_parfor' allows us to specify an output directory;
%
%    [] allows us to specify switches to the MOAB queue handler, such as more time.
%
%    'p" indicates this is a "parfor" job;
%
%    'w' indicates that the MATLAB session should wait for completion;
%
%    workers is the number of processors requested;
%
%    @hello_fun indicates the function we want to execute;
%
%    { n } contains input arguments to the function.
%
%    The function "hello_fun" must correspond to a MATLAB M-file "hello_fun.m"
%    and that file must be in MATLAB's path.
%
%    The easiest way to ensure that the file is in MATLAB's path is to
%    create a subdirectory called "matlab" immediately below your home directory,
%    and place the function file there (as well as any other files needed
%    by the job).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 March 2011
%
%  Author:
%
%    John Burkardt
%
  n = 10;
  workers = 4;

  tic

  fsuClusterMatlab ( '~/matlab/hello_parfor', [], 'p', 'w', workers, ...
    @hello_fun, { n } )

  toc


function figbolden(pos,pv,m)
% embolden the current figure
% Inputs: pos = [xmin ymin width height] gives the lower left corner position and the window size in pixels
%               [width height] leaves the lower left corner alone
%               [width] has a standard aspect ratio of 4:3
%               [-width/height] leaves the area unchanged but fixes the aspect ratio
%         pv is a cell name containing attribute-value pairs.
%            default = {'FontName' 'Ariel'; 'FontSize' 16; 'LineWidth' 2; 'MarkerSize' 8}
%         m is a mode string:
%                'l' lists the changes made
%                'd' uses default pv settings
%                'x' suppresses changes

%      Copyright (C) Mike Brookes 2003
%      Version: $Id: figbolden.m 3497 2013-09-26 16:10:51Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   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 can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ps={'Title' 'XLabel' 'YLabel' 'Children'};
if nargin<3
    m='';
end
if nargin<2 || any(m=='d')
    pv={'FontName' 'Arial'; 'FontSize' 16; 'LineWidth' 2; 'MarkerSize' 8};
end
pp={'Symbol';'Wingdings'};      % protected fonts
if nargin<1
    pos=[];
end
mlist=any(m=='l');  % list changes
mnotx=~any(m=='x'); % do changes
scsz=get(0,'screensize');
if length(pos)
    po=get(gcf,'position');
    if length(pos)>2            % position is specified
        po(1:2)=pos(1:2);
        pos(1:2)=[];      % remove xmin,ymin
    end
    if length(pos)>1
        po(3:4)=pos(1:2);
    else
        if pos(1)>0
            po(3:4)=[1 0.75]*pos(1);
        else
            po(3:4)=[-pos(1) 1]*sqrt(-po(3)*po(4)/pos(1)); % preserve area
        end
    end
    set(gcf,'position',po);
end
hlist=get(gcf,'children');
while length(hlist)
    pl=get(hlist(1));
    %fprintf('list length = %d, handle = %f\n',length(hlist),hlist(1));
    for i=1:size(pv,1)
        if isfield(pl,pv{i,1})
            if i>1 || all(~strcmpi(get(hlist(1),pv{i,1}),pp))
                pval=get(hlist(1),pv{i,1});
                if ~all(size(pval)==size(pv{i,2})) || ~all(pval(:) == pv{i,2}(:))
                    if mnotx
                        set(hlist(1),pv{i,1},pv{i,2})
                    end
                    if mlist
                        if ischar(pval)
                            fch='s';
                        else
                            fch='g';
                        end
                        fprintf(['change %f %s: %' fch ' -> %' fch '\n'],hlist(1),pv{i,1},pval,pv{i,2});
                    end
                end
            end
        end
    end
    for i=1:length(ps)
        if isfield(pl,ps{i})
            hlist=[hlist; get(hlist(1),ps{i})];
            %fprintf('add %f:%s\n',hlist(1),ps{i});
        end
    end
    hlist(1)=[];
end


function cosmo_disp(x,varargin)
% display the input as a string representation
%
% cosmo_disp(x,opt)
%
% Inputs:
%   x              any type of data element (can be a dataset struct)
%   opt            Optional struct with fields
%     .threshold   If the number of values in an array along a dimension
%                  exceeds threshold, then an array is showed in summary
%                  style along that dimension. Default: 5
%     .edgeitems   When an array is shown in summary style, edgeitems sets
%                  the number of items at the beginning and end of the
%                  array to be shown (separated by '...' in rows and by ':'
%                  in columns).
%                  Default: 3
%     .precision   Numeric precision, indicating number of decimals after
%                  the floating point
%                  Default: 3
%     .strlen      Maximal string lenght, if a string is longer the
%                  beginning and end are shown separated by ' ... '.
%                  Default: 20
%     .depth       Maximum recursion depth
%                  Default: 6
%
% Side effect:     Calling this function caused the representation of x
%                  to be displayed.
%
%
% Examples:
%     % display a complicated data structure
%     x=struct();
%     x.a_cell={[],{'cell within cell',[1 2; 3 4]}};
%     x.small_matrix=[10 11 12; 13 14 15];
%     x.big_matrix=reshape(1:200,10,20);
%     x.huge=2^40;
%     x.tiny=2^-40;
%     x.a_string='hello world';
%     x.a_struct.another_struct.name='me';
%     x.a_struct.another_struct.func=@abs;
%     cosmo_disp(x);
%     %|| .a_cell
%     %||   { [  ]  { 'cell within cell'  [ 1         2
%     %||                                   3         4 ] } }
%     %|| .small_matrix
%     %||   [ 10        11        12
%     %||     13        14        15 ]
%     %|| .big_matrix
%     %||   [  1        11        21  ...  171       181       191
%     %||      2        12        22  ...  172       182       192
%     %||      3        13        23  ...  173       183       193
%     %||      :         :         :        :         :         :
%     %||      8        18        28  ...  178       188       198
%     %||      9        19        29  ...  179       189       199
%     %||     10        20        30  ...  180       190       200 ]@10x20
%     %|| .huge
%     %||   [ 1.1e+12 ]
%     %|| .tiny
%     %||   [ 9.09e-13 ]
%     %|| .a_string
%     %||   'hello world'
%     %|| .a_struct
%     %||   .another_struct
%     %||     .name
%     %||       'me'
%     %||     .func
%     %||       @abs
%     %
%     cosmo_disp(x.a_cell)
%     %|| { [  ]  { 'cell within cell'  [ 1         2
%     %||                                 3         4 ] } }
%     cosmo_disp(x.a_cell{2}{2})
%     %|| [ 1         2
%     %||   3         4 ]
%
%     % make a cell in a cell in a cell in a cell ...
%     m={{{{{{{{{{{'hello'}}}}}}}}}}};
%     cosmo_disp(m)
%     %|| { { { { { { <cell> } } } } } }
%     cosmo_disp(m,'depth',8)
%     %|| { { { { { { { { <cell> } } } } } } } }
%     cosmo_disp(m,'depth',Inf)
%     %|| { { { { { { { { { { { 'hello' } } } } } } } } } } }
%
%     % illustrate 'threshold' and 'edgeitems' arguments
%     cosmo_disp(num2cell('a':'k'))
%     %|| { 'a'  'b'  'c' ... 'i'  'j'  'k'   }@1x11
%     cosmo_disp(num2cell('a':'k'),'threshold',Inf)
%     %|| { 'a'  'b'  'c'  'd'  'e'  'f'  'g'  'h'  'i'  'j'  'k' }
%     cosmo_disp(num2cell('a':'k'),'edgeitems',2)
%     %|| { 'a'  'b' ... 'j'  'k'   }@1x11
%
%     % illustrate 'precision' argument
%     cosmo_disp(pi*[1 2],'precision',1);
%     %|| [ 3       6 ]
%     cosmo_disp(pi*[1 2],'precision',3);
%     %|| [ 3.14      6.28 ]
%     cosmo_disp(pi*[1 2],'precision',5);
%     %|| [ 3.1416      6.2832 ]
%     cosmo_disp(pi*[1 2],'precision',7);
%     %|| [ 3.141593      6.283185 ]
%
%     % illustrate n-dimensional arrays
%     x=zeros([2 2 1 2 3]);
%     x(:)=2*(1:numel(x));
%     cosmo_disp(x)
%     %|| <double>@2x2x1x2x3
%     %||    (:,:,1,1,1) =  [ 2         6
%     %||                     4         8 ]
%     %||    (:,:,1,2,1) =  [ 10        14
%     %||                     12        16 ]
%     %||    (:,:,1,1,2) =  [ 18        22
%     %||                     20        24 ]
%     %||    (:,:,1,2,2) =  [ 26        30
%     %||                     28        32 ]
%     %||    (:,:,1,1,3) =  [ 34        38
%     %||                     36        40 ]
%     %||    (:,:,1,2,3) =  [ 42        46
%     %||                     44        48 ]
%     cosmo_disp(reshape(char(65:72),[2 2 2]))
%     %|| <char>@2x2x2
%     %||    (:,:,1) = 'AC
%     %||               BD'
%     %||    (:,:,2) = 'EG
%     %||               FH'
%     cosmo_disp(zeros([2 3 5 7 0 2]))
%     %|| <double>@2x3x5x7x0x2 (empty)
%
%     % illustrate non-singleton structs
%     x=struct('x',{1 2; 3 4});
%     cosmo_disp(x);
%     %|| <struct>@2x2
%     %||    (1,1).x
%     %||           [ 1 ]
%     %||    (2,1).x
%     %||           [ 3 ]
%     %||    (1,2).x
%     %||           [ 2 ]
%     %||    (2,2).x
%     %||           [ 4 ]
%     x3=cat(3,x,x,x);
%     cosmo_disp(x3);
%     %|| <struct>@2x2x3
%     %||    (1,1,1).x
%     %||             [ 1 ]
%     %||    (2,1,1).x
%     %||             [ 3 ]
%     %||    (1,2,1).x
%     %||             [ 2 ]
%     %||      :        :
%     %||    (2,1,3).x
%     %||             [ 3 ]
%     %||    (1,2,3).x
%     %||             [ 2 ]
%     %||    (2,2,3).x
%     %||             [ 4 ]
%
% Notes:
%   - Unlike the builtin 'disp' function, this function shows the contents
%     of the input using recursion. For example if a cell contains a
%     struct, then the contents of that struct is shown as well
%   - A use case is displaying dataset structs
%
% #   For CoSMoMVPA's copyright information and license terms,   #
% #   see the COPYING file distributed with CoSMoMVPA.           #

    defaults.threshold=5;    % max #items before triggering summary style
    defaults.edgeitems=3;    % #items at edges in summary style
    defaults.precision=3;    % show floats with 3 decimals
    defaults.strlen=20;      % insert '...' with strings more than 20 chars
    defaults.depth=6;        % maximal depth
    defaults.show_size=false;% whether to show size of matrices

    opt=cosmo_structjoin(defaults,varargin);

    % get string representation of x
    s=disp_helper(x, opt);

    % print string representation of x
    disp(s);

function s=disp_helper(x, opt)
    % general helper function to get a string representation. Unlike the
    % main function this function returns a string, which makes it suitable
    % for recursion
    depth=opt.depth;
    if depth<=0
        s=any2summary_str(x,opt);
        return
    end

    opt.depth=depth-1;

    if ~has_size(x)
        s=any2summary_str(x,opt);
    else
        s=nd_any2str(x,opt);
    end

function s=any2summary_str(x,unused)
    if has_size(x)
        sz=size(x);
    else
        sz=[1 1];
    end
    s=surround_with(true,'<',class(x),'>',sz);

function tf=has_size(x)
    % helper, because some classes have no 'size'
    try
        size(x);
        tf=true;
    catch
        tf=false;
    end

function y=nd_any2str(x,opt)
    if isstruct(x)
        if numel(x)<=1
            y=struct2str(x,opt);
        else
            y=multi_any2string(x,0,opt);
        end
    elseif numel(size(x))==2
        if iscell(x)
            y=cell2str(x,opt);
        elseif isnumeric(x) || islogical(x)
            y=matrix2str(x,opt);
        elseif ischar(x)
            y=string2str(x,opt);
        elseif isa(x, 'function_handle')
            y=function_handle2str(x,opt);
        else
            y=any2summary_str(x,opt);
        end
    else
        y=multi_any2string(x,2,opt);
    end

function y=multi_any2string(x,ndim_post,opt)
    sz=size(x);
    sz_rest=sz((ndim_post+1):end);
    ndim_rest=numel(sz_rest);
    n_rest=prod(sz_rest);

    parts=cell(ndim_rest,1);
    for k=1:ndim_rest
        parts{k}=num2cell(1:sz_rest(k));
    end

    p=cosmo_cartprod(parts);
    if ndim_post>0
        xflat=reshape(x,[sz(1:ndim_post) n_rest]);
    else
        xflat=x(:);
    end

    [pre,post]=get_mx_idxs(xflat,opt.edgeitems,opt.threshold,ndim_post+1);

    header=any2summary_str(x,opt);
    s_pre=nd_any2str_helper(xflat,p, pre,opt);

    if isempty(post)
        s_post={'',''};
        s_dots={'',''};
    else
        s_post=nd_any2str_helper(xflat,p,post,opt);
        s_dots=cell(1,2);
        for k=1:2
            szs=cellfun(@(x)size(x,2),s_post(:,k));
            pos=round(max(szs)/2);
            s_dots{k}=[spaces(1,pos) ':'];
        end
    end
    s_all=cat(1,s_pre,s_dots,s_post);

    y=strcat_({header;strcat_(s_all)});

function s=nd_any2str_helper(xflat, p, idxs, opt)
    n_rest=numel(idxs);
    s=cell(n_rest,2);
    sz=size(xflat);
    npre=numel(sz)-1;
    for k=1:n_rest
        idx=idxs(k);
        switch npre
            case 1
                % for struct
                v=xflat(idx);
                idx_prefix='';
                idx_postfix='';
            case 2
                % anything else
                v=xflat(:,:,idx);
                idx_prefix=':,:,';
                idx_postfix=' = ';
            otherwise
                assert(false);
        end

        v_str=disp_helper(v,opt);
        idx_str=sprintf(',%d',p(idx,:));
        s{k,1}=sprintf('   (%s%s)%s',idx_prefix,idx_str(2:end),idx_postfix);
        s{k,2}=v_str;
    end

function y=strcat_(xs)
    if isempty(xs)
        y='';
        return
    end

    % all elements in xs are char
    [nr,nc]=size(xs);
    ys=cell(1,nc);

    % sizes for each element
    width_per_col=max_element_size(xs,2);
    height_per_row=max_element_size(xs,1);
    for k=1:nc
        xcol=cell(nr,1);
        width=width_per_col(k);
        row_pos=0;
        for j=1:nr
            height=height_per_row(j);
            if height==0
                continue;
            end

            x=xs{j,k};
            if ~ischar(x) && isempty(x)
                x='';
            end

            sx=size(x);
            to_add=[height width]-sx;

            % pad with spaces
            row_pos=row_pos+1;
            xcol{row_pos}=[[x spaces(sx(1),to_add(2))];...
                        spaces(to_add(1), width)];
        end
        ys{k}=char(xcol{1:row_pos});
    end
    y=[ys{:}];

function m=max_element_size(x,dim)
    % faster than cellfun
    n=numel(x);
    sizes=zeros(size(x));
    for k=1:n
        sizes(k)=size(x{k},dim);
    end
    m=max(sizes,[],3-dim);

function y=spaces(nx,ny)
    % faster than repmat(' ',nx,ny)
    if nx>0 && ny>0
        y(nx,ny)=' ';
        y(:)=' ';
    else
        if nx<0
            nx=0;
        end
        if ny<0
            ny=0;
        end
        y=reshape('',nx,ny);
    end

function y=struct2str(x,opt)
    if numel(x)==0
        show_size=opt.show_size;
        y=[surround_with(show_size,'', 'struct', '', size(x)) ' (empty)'];
        return;
    end

    assert(numel(x)==1)
    fns=fieldnames(x);
    n=numel(fns);

    if n==0
        show_size=opt.show_size;
        y=[surround_with(show_size,'', 'struct', '', size(x)) ' (empty)'];
    else
        r=cell(n*2,1);
        for k=1:n
            fn=fns{k};
            r{k*2-1}=['.' fn];
            d=disp_helper(x.(fn),opt);
            r{k*2}=[spaces(size(d,1),2) d];
        end
        y=strcat_(r);
    end

function s=function_handle2str(x,opt)
    s_with_quotes=string2str(func2str(x),opt);
    s=['@' s_with_quotes(2:(end-1))];

function s=string2str(x, opt)
    if ~ischar(x), error('expected a char'); end
    [nrows,ncols]=size(x);

    if ncols>opt.strlen
        infix=' ... ';
        h=floor((opt.strlen-numel(infix))/2);
        x=strcat_({x(:,1:h), infix ,x(:,ncols+((1-h):0))});
    end
    quote='''';
    pre=quote;
    post=[spaces(nrows-1,1);quote];
    s=strcat_({pre,x,post});

function s=cell2str(x, opt)
    % display a cell

    edgeitems=opt.edgeitems;
    threshold=opt.threshold;

    % get indices of rows and columns to show
    [r_pre, r_post]=get_mx_idxs(x, edgeitems, threshold, 1);
    [c_pre, c_post]=get_mx_idxs(x, edgeitems, threshold, 2);

    part_idxs={{r_pre, r_post}, {c_pre, c_post}};

    nrows=numel([r_pre r_post])+~isempty(r_post);
    ncols=numel([c_pre c_post])+~isempty(c_post);

    sinfix=cell(nrows,ncols*2+1);
    for k=1:(ncols-1)
        sinfix{1,k*2+2}='  ';
    end

    cpos=1;
    for cpart=1:2
        col_idxs=part_idxs{2}{cpart};
        nc=numel(col_idxs);

        rpos=0;
        for rpart=1:2
            row_idxs=part_idxs{1}{rpart};

            nr=numel(row_idxs);
            if nr==0
                continue
            end
            for ci=1:nc
                col_idx=col_idxs(ci);
                trgc=cpos+ci*2;
                for ri=1:nr
                    row_idx=row_idxs(ri);
                    sinfix{rpos+ri,trgc}=disp_helper(x{row_idx,...
                                                             col_idx},opt);
                    if cpart==2 && ci==1 && nc>0
                        sinfix{rpos+ri,cpos+ci*2-1}=' ... ';
                    end
                end

                if rpart==2
                    max_length=max(cellfun(@numel,sinfix(:,trgc)));
                    pre_spaces=spaces(1,floor(max_length/2-1));
                    sinfix{rpos,cpos+ci*2}=[pre_spaces ':'];
                end
            end
            rpos=rpos+nr+1;
        end
        cpos=cpos+nc*2;
    end

    show_size=opt.show_size || ~isempty(r_post) || ~isempty(c_post);
    s=surround_with(show_size,'{ ', strcat_(sinfix), ' }', size(x));

function pre_infix_post=surround_with(show_size, pre, infix, post, matrix_sz)
    % surround infix by pre and post, doing
    n=prod(matrix_sz);
    if show_size && n~=1
        size_str=sprintf('x%d',matrix_sz);
        size_str(1)='@';
        if n==0
            size_str=[size_str ' (empty)'];
        end
    else
        size_str='';
    end
    post=strcat_({spaces(size(infix,1)-1,1); [post size_str]});
    pre_infix_post=strcat_({pre, infix, post});

function s=matrix2str(x,opt)
    if isempty(x)
        show_size=opt.show_size;
        s=surround_with(show_size,'[','  ',']',size(x));
        return
    end

    % display a matrix
    edgeitems=opt.edgeitems;
    threshold=opt.threshold;
    precision=opt.precision;

    % get indices of rows and columns to show
    [r_pre, r_post]=get_mx_idxs(x, edgeitems, threshold, 1);
    [c_pre, c_post]=get_mx_idxs(x, edgeitems, threshold, 2);

    % data to be shown
    y=x([r_pre r_post],[c_pre c_post]);

    % convert to string
    s=num2str(y,precision);

    % number of characters in first and second dimension
    [nc_row,nc_col]=size(s);

    % see where each column is a space; that's a potential split point
    sp_col=sum(s==' ',1)==nc_row;

    % col_index has value k for characters in the k-th column, else zero
    col_index=zeros(1,nc_col);
    col_count=1;
    in_num=true;
    for k=1:nc_col
        if in_num
            if sp_col(k)
                col_count=col_count+1;
                in_num=false;

            else
                col_index(k)=col_count;
            end
        elseif ~sp_col(k)
            in_num=true;
            col_index(k)=col_count;
        end
    end

    % deal with rows
    row_blocks=cell(3,1);
    if isempty(r_post)
        row_blocks{1,1}=s;
    else
        % insert ':' for each column
        line=spaces(1,nc_col);
        for k=1:max(col_index)
            idxs=find(col_index==k);
            median_pos=round(mean(idxs));
            line(median_pos)=':';
        end
        row_blocks{1}=s(1:edgeitems,:);
        row_blocks{2}=line;
        row_blocks{3}=s(edgeitems+(1:edgeitems),:);
    end

    % deal with columns
    row_and_col_blocks=cell(3,3);
    for row=1:3
        if isempty(c_post)
            row_and_col_blocks{row}=row_blocks{row};
        else
            % insert ' ... ' halfway each row
            pre_end=find(col_index==edgeitems,1,'last')+1;
            post_start=find(col_index==(edgeitems+1),1,'first')-1;

            r=row_blocks{row,1};
            if isempty(r)
                continue;
            end
            row_and_col_blocks{row,1}=r(:,1:pre_end);
            if row~=2
                row_and_col_blocks{row,2}=repmat(' ... ',size(r,1),1);
            end
            row_and_col_blocks{row,3}=r(:,post_start:end);
        end
    end

    show_size=opt.show_size || ~isempty(r_post) || ~isempty(c_post);
    s=surround_with(show_size,'[ ',strcat_(row_and_col_blocks),' ]',...
                                                                size(x));

function [pre,post]=get_mx_idxs(x, edgeitems, threshold, dim)
    % returns the first and last indices for showing an array along
    % dimension dim. If size(x,dim)<2*edgeitems, then pre has all the
    % indices, otherwise pre and post have the first and last edgeitems
    % indices, respectively
    n=size(x,dim);

    if n>max(threshold,2*edgeitems) % properly deal with Inf values
        pre=1:edgeitems;
        post=n-edgeitems+(1:edgeitems);
    else
        pre=1:n;
        post=[];
    end


function rules1
global x y z alpha

xn=str2num(get(x,'String'));
yn=str2num(get(y,'String'));
zn=str2num(get(z,'String'));

alphan=str2num(get(alpha,'String'));

rules(xn,yn,zn,alphan);


function weekday_test ( )

%*****************************************************************************80
%
%% WEEKDAY_TEST tests the WEEKDAY library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 April 2010
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'WEEKDAY_TEST:\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the WEEKDAY library.\n' );

  weekday_test01 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'WEEKDAY_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end
function weekday_test01 ( )

%*****************************************************************************80
%
%% WEEKDAY_TEST01 tests YMD_TO_WEEKDAY_COMMON.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 March 2010
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'WEEKDAY_TEST01\n' );
  fprintf ( 1, '  For dates in the Common calendar:\n' );
  fprintf ( 1, '  YMD_TO_WEEKDAY_COMMON returns the day of the week.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  YMD                   Weekday    Weekday\n' );
  fprintf ( 1, '                        Tabulated  Computed\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, y, m, d, w1 ] = weekday_values ( n_data );

    if ( n_data == 0 )
      break;
    end

    s3 = ymd_to_s_common ( y, m, d );
    w2 = ymd_to_weekday_common ( y, m, d );
    s1 = weekday_to_name_common ( w1 );
    s2 = weekday_to_name_common ( w2 );

    fprintf ( 1, '  %20s  %9s  %9s\n', s3, s1, s2 );

  end

  return
end


% LTFAT - Base routines
%
%  Peter L. Søndergaard, 2009 - 2018.
%
%  Basic routines
%    LTFATSTART       -  Start the toolbox
%    LTFATSTOP        -  Stop the toolbox
%    LTFATHELP        -  Help
%    LTFATMEX         -  Compile Mex/Oct interfaces
%    LTFATBASEPATH    -  Return the base path
%    ISOCTAVE         -  True if interpreter is Octave
%
%  Parameter handling
%    LTFATARGHELPER   -  Handle optional parameters of functions
%    LTFATGETDEFAULTS -  Get the default values for a function
%    LTFATSETDEFAULTS -  Get the default values for a function
%    SCALARDISTRIBUTE -  Expand parameters to common size
%
%  Graphical user interfaces
%    MULACLAB         -  Short Time-Fourier transform modification in Matlab
%
%  For help, bug reports, suggestions etc. please visit
%  http://github.com/ltfat/ltfat/issues


function varargout = mpower_internal(varargin)
switch class(varargin{1})
    case 'double'
        varargout{1} = varargin{1};
    case 'char'
        % Note, the order here is assumed in GP formulation
        varargout{1} = (varargin{3} == varargin{2});
        varargout{2} = struct('convexity','none','monotonicity','none','definiteness','none','model','exact');
        varargout{3} = varargin{3};
    otherwise
end


function [SAMimage, coords, stepsize] = ctf_read_svl(filename)
% ctf_read_svl - reads SAM image from a .svl file (generated by SAMsrc)
%
% [SAMimage, coords, stepsize] = ctf_read_svl(filename)
%
% Returns SAMimage as voxels x 1 array of intensities
% coords contains corresponding voxel locations
%

% $Revision: 1.1 $ $Date: 2009-01-30 03:49:27 $

% Copyright (C) 2005, Sarang Dalal and Darren Weber
%
% 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.

% History:  10/2005, Darren.Weber_at_radiology.ucsf.edu
%                    Sarang Dalal developed nut_read_svl.m
%                    DLW adapted nut_read_svl.m into ctf functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ver = '$Revision: 1.1 $ $Date: 2009-01-30 03:49:27 $';
fprintf('CTF_READ_SVL [v %s]\n',ver(11:15));

if(nargin < 1)
    help ctf_read_svl;
    return;
end

fid=fopen(filename,'r','b');
identity = transpose(fread(fid,8,'*char'));
if(~strcmp(identity,'SAMIMAGE'))
    error('This doesn''t look like a SAM IMAGE file.');
end
vers = fread(fid,1,'int32');
setname = fread(fid,256,'*char');

% int32 vs. double for fiducial locations:
% The CTF svl format assumes that the fiducials will be
% integer  values when defined in terms of MRI voxel
% indices, but will be floating point values when
% defined in MEG head coordinates.
numchans = fread(fid,1,'int32');
numweights = fread(fid,1,'int32');
if(numweights ~= 0)
    warning('... numweights ~= 0');
end

padbytes1 = fread(fid,1,'int32');

xstart = fread(fid,1,'double');
xend = fread(fid,1,'double');
ystart = fread(fid,1,'double');
yend = fread(fid,1,'double');
zstart = fread(fid,1,'double');
zend = fread(fid,1,'double');
stepsize = fread(fid,1,'double');

[meshz,meshy,meshx]=ndgrid(zstart:stepsize:zend,ystart:stepsize:yend,xstart:stepsize:xend);
coords = [meshx(:) meshy(:) meshz(:)];

hpfreq = fread(fid,1,'double');
lpfreq = fread(fid,1,'double');
bwfreq = fread(fid,1,'double');
meannoise = fread(fid,1,'double');

MRIname = transpose(fread(fid,256,'*char'));
nasion = fread(fid,3,'int32');
rightPA = fread(fid,3,'int32');
leftPA = fread(fid,3,'int32');

SAMtype = fread(fid,1,'int32');
SAMunit = fread(fid,1,'int32');

padbytes2 = fread(fid,1,'int32');

% DLW: why are these doubles and those above are int32?
nasion_meg = fread(fid,3,'double');
rightPA_meg = fread(fid,3,'double');
leftPA_meg = fread(fid,3,'double');

SAMunitname = fread(fid,32,'*char');

SAMimage = fread(fid,inf,'double');

fclose(fid);

return


function y = newvar( prob, name, siz, str, geo )
error( nargchk( 2, 5, nargin ) );

%
% Check problem
%

if ~isa( prob, 'cvxprob' ),
    error( 'First argument must be a cvxprob object.' );
end
p = index( prob );
global cvx___

%
% Check name
%

if ischar( name ),
    if ~isempty( name ),
        if size( name, 1 ) ~= 1,
            error( 'Second argument must be a string or a subscript structure array.' );
        elseif ~isvarname( name ),
            error( 'Invalid variable name: %s', name );
        elseif isfield( cvx___.problems( p ).variables, name ),
            error( 'Variable already exists: %s', name );
        end
        nstr = struct( 'type', '.', 'subs', name );
    else
        nstr = [];
    end
elseif ~isstruct( name ),
    error( 'Second argument must be a string or a subscript structure array.' );
else
    nstr = name;
    name = cvx_subs2str( name, [ 1, 0, 1 ], 1 );
    name(1) = [];
    if ~isequal( nstr(1).type, '.' ),
        error( 'Invalid subscript structure: first element must be a field reference.' );
    end
end

%
% Retrieve an existing variable, and check for conflicts
%

vars = cvx___.problems( p ).variables;
if ~isempty( nstr ),
    try
        y = builtin( 'subsref', vars, nstr );
    catch
        y = [];
    end
    if nargin == 2,
        if ~isempty( y ), return; end
        error( [ 'Unknown variable: ', name ] );
    elseif ~isempty( y ),
        error( [ 'Duplicate variable name: ', name ] );
    end
elseif nargin == 2,
    error( 'Second argument must be a non-empty string or subscript structure array.' );
else
    y = []; %#ok
end

%
% Check for conflict with dual variable
%

if ~isempty( nstr ) && isfield( cvx___.problems( p ).duals, nstr(1).subs ),
    error( 'Primal/dual variable name conflict: %s', nstr(1).subs );
end

%
% Quick exit for retrieval mode
%

if nargin == 2,
    y = cvx___.problems( p ).variables;
    try
        y = subsref( y, name );
        return
    catch
        error( [ 'Unknown variable: ', nstr ] );
    end
end

%
% Create the variable
%

if isa( siz, 'cvx' ),

    %
    % Out of an existing object
    %

    y = newsubst( prob, siz );

else

    %
    % Check size
    %

    [ temp, siz ] = cvx_check_dimlist( siz, true );
    if ~temp,
        error( 'Invalid size vector.' );
    end

    %
    % Check structure
    %

    len = prod( siz );
    if nargin < 4 || isempty( str ),
        dof = len;
        str = [];
    elseif ~isnumeric( str ) || ndims( str ) > 2 || size( str, 2 ) ~= len,
        error( 'Fourth argument must be a valid structure matrix.' );
    elseif nnz( str ) == 0,
        error( 'Structure matrix cannot be identically zero.' );
    else
        temp = any( str, 2 );
        dof = full( sum( temp ) );
        if dof ~= length( temp ),
            str = str( temp, : );
        end
    end

    %
    % Geometric flag
    %

    if nargin < 5 || isempty( geo ),
        geo = false;
    elseif ~isnumeric( geo ) && ~islogical( geo ) || length( geo ) ~= 1,
        error( 'Fifth argument must be true or false.' );
    end

    %
    % Allocate the raw variable data
    %

    geo  = any( geo( : ) );
    odim = length( cvx___.reserved );
    ndim = odim + 1 : odim + ( geo + 1 ) * dof;
    cvx___.reserved(    ndim, 1 ) = 0;
    cvx___.vexity(      ndim, 1 ) = 0;
    cvx___.canslack(    ndim, 1 ) = true;
    cvx___.readonly(    ndim, 1 ) = p;
    cvx___.geometric(   ndim, 1 ) = 0;
    cvx___.logarithm(   ndim, 1 ) = 0;
    cvx___.exponential( ndim, 1 ) = 0;
    if geo,
        ndim2 = ndim( 1 : dof );
        ndim  = ndim( dof + 1 : end );
        cvx___.vexity(      ndim,  1 ) = +1;
        cvx___.canslack(    ndim,  1 ) = true;
        cvx___.geometric(   ndim,  1 ) = +1;
        cvx___.exponential( ndim2, 1 ) = ndim( : );
        cvx___.logarithm(   ndim,  1 ) = ndim2( : );
    end
    cvx___.x = [];
    cvx___.y = [];

    %
    % Create the variable object
    %

    if dof == 0,
        str2 = sparse( 1, 0 );
    else
        str2 = sparse( ndim, 1 : dof, 1 );
        if ~isempty( str ),
            str2 = str2 * str;
        end
    end
    y = cvx( siz, str2, dof * ( 1 - 2 * geo ), false );

end

%
% If the variable is named, save it in the problem structure
%

if ~isempty( nstr ),
    try
        cvx___.problems( p ).variables = builtin( 'subsasgn', vars, nstr, y );
    catch
        error( [ 'Invalid variable name: ', name ] );
    end
end

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function vw = UpdateMapWindow(vw)
%
% vw = UpdateMapWindow
%
% Sets the MapWindow sliders to correspond to current parameter map (if any
% is present).
%
% Ress, 6/03
% ras, 11/04 -- doesn't always throw out the prev. set points
% jw,  2/10  -- avoid error if map range is not defined (e.g., due to all map
%                               values being NaNs)
if isempty(vw.map), return, end

parMap = viewGet(vw,'map');

if isfield(vw, 'ui') && isfield(vw.ui,'windowHandle'); % test for non-hidden vw
    % Find min/max and reset sliders
	minVal = inf;
	maxVal = -inf;
    for iScan = 1:viewGet(vw, 'numScans')
        if length(parMap) >= iScan && ~isempty(parMap{iScan})
            % the 'mrvMinmax' function ignores NaNs and Infs, this helps
            % prevent slider-setting errors
            rng = mrvMinmax( parMap{iScan}(:) );

            % deal with NaNs to avoid error when setting map window limits
            if isempty(rng), rng = [0 1]; end

            minVal = min(minVal, rng(1));
            maxVal = max(maxVal, rng(2));
        end
    end

    % deal w/ min/max being switched
    if (minVal>maxVal), tmp=maxVal; maxVal=minVal; minVal=tmp; end

    % if new min/max are outside current set pts, keep same set pts;
    % otherwise, reset points to minVal & maxVal
    setVals = viewGet(vw, 'mapWin');
    setMin = setVals(1); setMax = setVals(2);
%    if setMin < minVal
        setMin = minVal;
%    end
%    if setMax > maxVal
        setMax = maxVal;
%    end

	vw = resetSlider(vw, vw.ui.mapWinMin, minVal, maxVal, setMin);
	vw = resetSlider(vw, vw.ui.mapWinMax, minVal, maxVal, setMax);
end

return


% Matlab Wrapper for SVMlight
% Version 0.92, August 2002
%
% Wrapper functions:
%   svml - Wrapper for SVMlight
%   svmltrain - Wrapper for SVMlight: Training
%   svmlfwd - Wrapper for SVMlight: Prediction
%   demsvml1 - Demo program for Matlab SVMlight wrapper
%
% Auxiliary functions to generate and read data files
%   svmlread - Read a data file generated by SVM light
%   svmlwrite - Write matrix into data file for SVM light
%   svmlopt - Generate/alter options structure for SVM light
%   consist - Check that arguments are consistent.
%
% Calling routines
%   svm_classify - Interface to SVM light, classification module
%   svm_learn - Interface to SVM light, learning module
%
%
% Copyright (c) by Anton Schwaighofer (2002)
% mailto:anton.schwaighofer@gmx.net
%
% This program is released unter the GNU General Public License.
%

% $Revision: 1.3 $ $Date: 2002/08/09 20:25:26 $
%
% 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 view = makePointROI(view, pt, createNew)
% Create a region of interest comprising a single voxel.
%
% view = makePointROI([view], [pt=get from UI], [createNew=1]);
%
% view: mrVista view structure. [Default: current view]
%
% pt: 3-element vector specifying the point. In inplane, this is
%	  [row col slice] of the coordinates, relative to the inplane anatomy;
%	  in gray/volume views, this is [axi cor sag] slice specification; in
%	  flat views, it's [x y hemisphere].
%	  [Default: for 3-view windows, take from the crosshairs position. For
%	  other views, prompts the user to type in the coords.]
%
% createNew: flag to make a new ROI with the point. [default 1] Otherwise,
% will add the point to the view's selected ROI -- much like addROIpoints,
% but allows for a more precise way of specifying the coords.
%
% ras, 09/2008.
if notDefined('view'),			view = getCurView;				end
if notDefined('createNew'),		createNew = 1;					end
if notDefined('pt')
	if checkfields(view, 'loc')
		pt = view.loc;
	else
		pt = inputdlg({'Enter the point coordinates:'}, mfilename, 1);
		pt = str2num(pt{1});
	end
end

% check that the point is valid
if length(pt)~=3
	error('point must be a 3-element vector.')
end

if createNew==1
	view = newROI(view, sprintf('Point %s', num2str(pt)), [], [], pt(:));

else
	if isempty(view.ROIs) || view.selectedROI < 1
		error('No existing ROIs in view.')
	end
	roi = view.ROIs(view.selectedROI);
	if isempty(roi.coords)
		roi.coords = pt(:);
	else
		roi.coords(:,end+1) = pt(:);
	end
	view.ROIs(view.selectedROI) = roi;
end

return


% ----------------------------------------------------------------------------
% function hfssRotate(fid, ObjList, Axis, Degrees)
%
% Description :
% -------------
% Creates the VB Script necessary to rotate a given set of objects.
%
% Parameters :
% ------------
% fid     - file identifier of the HFSS script file.
% ObjList - a cell array of objects that need to be rotated.
% Axis    - axis of the rotation.
% Degrees - value of the rotation in degrees.
%
% Note :
% ------
%
% Example :
% ---------
% fid = fopen('myantenna.vbs', 'wt');
% ... create some objects here ...
% hfssRotate(fid, {'Dipole1', 'Dipole2'}, 'X', -30);
% ----------------------------------------------------------------------------

% ----------------------------------------------------------------------------
% CHANGELOG
%
% 23-Sep-2012: *Initial release (DRP).
% 21-Apr-2021: *Fix rotation of just one element with string name (DRP).
% ----------------------------------------------------------------------------

% ----------------------------------------------------------------------------
% Written by Daniel Rodriguez Prado
% danysan@gmail.com
% 23 September 2012
% ----------------------------------------------------------------------------
function hfssRotate(fid, ObjectList, Axis, Degrees)

if (~iscell(ObjectList)) % Fixes rotation when there is only one string.
    ObjectList = {ObjectList};
end

nObjects = length(ObjectList);

% Preamble.
fprintf(fid, '\n');
fprintf(fid, 'oEditor.Rotate _\n');
fprintf(fid, 'Array("NAME:Selections", _\n');

% Object Selections.
fprintf(fid, '"Selections:=", "');
for iObj = 1:nObjects
	fprintf(fid, '%s', ObjectList{iObj});
	if (iObj ~= nObjects)
		fprintf(fid, ',');
    end
end
fprintf(fid, '"), _\n');

% Transalation Vector.
fprintf(fid, 'Array("NAME:RotateParameters", _\n');
fprintf(fid, '"RotateAxis:=", "%s", _\n', upper(Axis));
fprintf(fid, '"RotateAngle:=", "%fdeg")\n', Degrees);


% initFigures
% Position 6 figures on the edges of the screen.
% [xmin ymin w h] where (0,0) = bottom left
% Numbers assume screen resolution is 1024 x 1280

global FIGNUM NUMFIGS
FIGNUM = 1; NUMFIGS = 6;

screenMain = true; % set to false if initializing figures for second screen
%screenMain = false;

if screenMain
  xoff = 0;
else
  %xoff = 1280;
  xoff = -1280;
end

% 2 x 3 design
w = 400; h = 300;
xs = [10 450 875] + xoff;
ys = [650 40];

if 0
% 3x3 design
w = 350; h = 250;
xs = [10 380 750]+xoff;
ys = [700 350 10];
end

Nfigs = length(xs)*length(ys);
if screenMain
  fig = 1;
else
  fig = Nfigs + 1;
end

for yi=1:length(ys)
  for xi=1:length(xs)
    figure(fig);
    set(gcf, 'position', [xs(xi) ys(yi) w h]);
    fig = fig + 1;
  end
end

% To plot something on the next available figure (with wrap around), use
% sfigure(FIGNUM); clf; FIGNUM = wrap(FIGNUM+1, NUMFIGS);


function idxPrm = addPrm(obj, varargin)
% ADDPRM Add parameter(s) to problem

% Fields of prm structure
% - x0           -> mandatory
% - xhat         -> NaN
% - sig          -> NaN
% - const        -> can be omitted
% - idxAdj       -> NaN
% - lowerBound   -> can be omitted
% - upperBound   -> can be omitted
% - scale4report -> can be omitted
% - report       -> can be omitted
% - label        -> can be omitted

prm2add = paramvalue2struct(varargin{:}); % create struct

noPrm2add = numel(prm2add.x0); % no. of parameters to add

% Add default values if not specified
if ~isfield(prm2add, 'const'       ), prm2add.const        = false(       noPrm2add, 1); end
if ~isfield(prm2add, 'lowerBound'  ), prm2add.lowerBound   = repmat(-Inf, noPrm2add, 1); end
if ~isfield(prm2add, 'upperBound'  ), prm2add.upperBound   = repmat(+Inf, noPrm2add, 1); end
if ~isfield(prm2add, 'scale4report'), prm2add.scale4report = ones(        noPrm2add, 1); end
if ~isfield(prm2add, 'report'      ), prm2add.report       = true(        noPrm2add, 1); end
if ~isfield(prm2add, 'label'       ), prm2add.label        = repmat({''}, noPrm2add, 1); end

% Default values
prm2add.xhat   = NaN(noPrm2add,1);
prm2add.sig    = NaN(noPrm2add,1);
prm2add.idxAdj = NaN(noPrm2add,1);

% Add observations with 'direct indexing' (faster than other methods)
% Indices
if isempty(obj.prm)
    idxPrm2add = 1:noPrm2add;
else
    noPrm = numel(obj.prm.x0); % actual no. of parameters
    idxPrm2add = noPrm+1:noPrm+noPrm2add;
end

% Add
obj.prm.x0(          idxPrm2add,1) = prm2add.x0;
obj.prm.xhat(        idxPrm2add,1) = prm2add.xhat;
obj.prm.sig(         idxPrm2add,1) = prm2add.sig;
obj.prm.const(       idxPrm2add,1) = prm2add.const;
obj.prm.idxAdj(      idxPrm2add,1) = prm2add.idxAdj;
obj.prm.lowerBound(  idxPrm2add,1) = prm2add.lowerBound;
obj.prm.upperBound(  idxPrm2add,1) = prm2add.upperBound;
obj.prm.scale4report(idxPrm2add,1) = prm2add.scale4report;
obj.prm.report(      idxPrm2add,1) = prm2add.report;
obj.prm.label(       idxPrm2add,1) = prm2add.label;

% Indices of observations
idxPrm = uint32(idxPrm2add)';

% % Input parsing ----------------------------------------------------------------
%
% p = inputParser;
% p.addParamValue('x0'          , NaN  , @(x) size(x,2)==1);
% p.addParamValue('const'       , false, @(x) islogical(x) && size(x,2)==1);
% p.addParamValue('lowerBound'  , -Inf , @(x) isnumeric(x) && size(x,2)==1);
% p.addParamValue('upperBound'  , +Inf , @(x) isnumeric(x) && size(x,2)==1);
% p.addParamValue('scale4report', 1    , @(x) isnumeric(x) && size(x,2)==1);
% p.addParamValue('label'       , {''} , @iscell);
% p.parse(varargin{:});
% p = p.Results;
%
% % Add parameter(s) to problem --------------------------------------------------
%
% if numel(p.const)        == 1, p.const        = repmat(p.const       , numel(p.x0), 1); end
% if numel(p.lowerBound)   == 1, p.lowerBound   = repmat(p.lowerBound  , numel(p.x0), 1); end
% if numel(p.upperBound)   == 1, p.upperBound   = repmat(p.upperBound  , numel(p.x0), 1); end
% if numel(p.scale4report) == 1, p.scale4report = repmat(p.scale4report, numel(p.x0), 1); end
% if numel(p.label)        == 1, p.label        = repmat(p.label       , numel(p.x0), 1); end
%
% xhat   = NaN(numel(p.x0), 1);
% sig    = NaN(numel(p.x0), 1);
% idxAdj = NaN(numel(p.x0), 1);
%
% prm2add = table(                  p.x0, xhat  , sig  , p.const, idxAdj  , p.lowerBound, p.upperBound, p.scale4report, p.label, ...
%                 'VariableNames', {'x0', 'xhat', 'sig', 'const', 'idxAdj', 'lowerBound', 'upperBound', 'scale4report', 'label'});
%
% obj.prm = [obj.prm; prm2add];
%
% idxPrm = uint32([height(obj.prm)-height(prm2add)+1 : height(obj.prm)]');

end


function ezaxes(command)
    %
    %   GUI input for axes
    %
    %   typing 'ezaxes' from the command line opens an
    %   interactive dialogue box, allowing the user to specify
    %   grids, axes size, fonts, scaling etc.
    %   using pulldown menus.
    %
    %
    %   Richard G. Cobb    3/96
    %   rcobb@afit.af.mil
    %

    if nargin < 1
        %
        figold=gcf;
        haold=gca;
        newfig=figure_w_normalized_uicontrolunits('Color',[0.9 0.9 0.9],'NumberTitle','off','Name',...
            'EZ AXES',...
            'NextPlot','new',...
            'Units','Normalized',...
            'Position',[.1 .1  .4 .3]);
        sfactor=1;
        axis(axis);
        axis off
        line([.52 .52],[-.2 1.2],'Color',[0 1 0],'LineWidth',3);
        uicontrol('Parent',newfig,...
            'style','pushbutton',...
            'string','Close',...
            'units','normalized',...
            'position',[.1 .85 .15 .1*sfactor],...
             'Callback','delete(gcf)');

        uicontrol('Parent',newfig,...
            'style','pushbutton',...
            'string','Refresh',...
            'units','normalized',...
            'position',[.3 .85 .15 .1*sfactor],...
             'Callback','ezarrow(98)');

        ui(1)=figold; bi(1)=haold;
        % Box Button
        ui(2)=0;
        bi(2) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.1 .7 .2 .1*sfactor],...
            'String','Boxed',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(2)');
        %% grid button
        ui(3)=0;
        bi(3) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.1 .55 .2 .1*sfactor],...
            'String','Grid',...
            'Visible','on',...
            'Value',1,...
            'Callback','ezaxes(3)');
        % axes menu
        T4=['Equal ';'Square';'Normal';'Image ';'On    ';'Off   '];
        ui(4) = uicontrol('Style','Popup','Units','Normalized',...
            'Position',[.1 .4 .2 .1*sfactor],...
            'String',T4,...
            'Visible','off',...
            'HorizontalAlignment', 'left',...
            'Callback','ezaxes(24)');
        bi(4) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.1 .4 .2 .1*sfactor],...
            'String','Axes',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(4)');

        % Tick direction button
        ui(5)=0;
        bi(5) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.1 .25 .2 .1*sfactor],...
            'String','Tick Direction',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(5)');

        % Ticklength edit
        ui(6)=uicontrol('Style','edit','Units','Normalized',...
            'Position',[.1 .1 .2 .1*sfactor],...
            'String',' ',...
            'Visible','off',...
            'Value',0,...
            'Callback','ezaxes(26)');
        bi(6) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.1 .1 .2 .1*sfactor],...
            'String','Tick Length',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(6)');

        % grid line style menu
        T7=[' - ';' --';' : ';' -.'];
        ui(7) = uicontrol('Style','Popup','Units','Normalized',...
            'Position',[.32 .7 .2 .1*sfactor],...
            'String',T7,...
            'Visible','off',...
            'HorizontalAlignment', 'left',...
            'Callback','ezaxes(27)');
        bi(7) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.32 .7 .2 .1*sfactor],...
            'String','GridLines',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(7)');

        % Font name menu
        T8=['Avant Garde           ';...
            'Bookman               ';...
            'Courier               ';...
            'Helvetica             ';...
            'Helvetica Narrow      ';...
            'New Century Schoolbook';...
            'Palatino              ';...
            'Symbol                ';...
            'Times                 ';...
            'Zapf Chancery         ';...
            'Zapf Dingbats         '];
        ui(8) = uicontrol('Style','Popup','Units','Normalized',...
            'Position',[.32 .55 .2 .1*sfactor],...
            'String',T8,...
            'Visible','off',...
            'HorizontalAlignment', 'left',...
            'Callback','ezaxes(28)');
        bi(8) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.32 .55 .2 .1*sfactor],...
            'String','FontName',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(8)');

        % font size menu
        T9=['10';'12';'16';'20';'24';'30'];
        ui(9) = uicontrol('Style','Popup','Units','Normalized',...
            'Position',[.32 .4 .2 .1*sfactor],...
            'String',T9,...
            'Visible','off',...
            'HorizontalAlignment', 'left',...
            'Callback','ezaxes(29)');
        bi(9) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.32 .4 .2 .1*sfactor],...
            'String','FontSize',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(9)');

        % font weight menu
        T10=['Normal ';...
            'Light  ';...
            'Demi   ';...
            'Bold   '];
        ui(10) = uicontrol('Style','Popup','Units','Normalized',...
            'Position',[.32 .25 .2 .1*sfactor],...
            'String',T10,...
            'Visible','off',...
            'HorizontalAlignment', 'left',...
            'Callback','ezaxes(30)');
        bi(10) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.32 .25 .2 .1*sfactor],...
            'String','FontWeight',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(10)');

        % font angle menu
        T11=['Normal ';'Italic ';'Oblique'];
        ui(11) = uicontrol('Style','Popup','Units','Normalized',...
            'Position',[.32 .1 .2 .1*sfactor],...
            'String',T11,...
            'Visible','off',...
            'HorizontalAlignment', 'left',...
            'Callback','ezaxes(31)');
        bi(11) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.32 .1 .2 .1*sfactor],...
            'String','FontAngle',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(11)');

        %% direction button
        ui(12)=0;
        bi(12) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.8 .85 .05 .1*sfactor],...
            'String','X',...
            'Visible','on',...
            'Value',0,...
            'BackgroundColor',[ 0 0 0 ],...
            'ForegroundColor',[ 0 1 0 ],...
            'Callback','ezaxes(12)');
        %% flip button

        ui(13)=0;
        bi(13) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.55 .7 .1 .1*sfactor],...
            'String','Flip',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(13)');

        %% grid button
        ui(14)=0;
        bi(14) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.7 .7 .1 .1*sfactor],...
            'String','Grid',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(14)');

        %% scale button
        ui(15)=0;
        bi(15) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.85 .7 .1 .1*sfactor],...
            'String','Scale',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(15)');

        %% limits edit
        ui(16)=uicontrol('Style','edit','Units','Normalized',...
            'Position',[.55 .475 .44 .1*sfactor],...
            'String',vec2str(get(haold,'Xlim')),...
            'Visible','off',...
            'Value',0,...
            'Callback','ezaxes(36)');
        bi(16) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.55 .475 .2 .1*sfactor],...
            'String','Limits',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(16)');

        %% tick edits
        ui(17)=uicontrol('Style','edit','Units','Normalized',...
            'Position',[.55 .325 .44 .1*sfactor],...
            'String',vec2str(get(haold,'XTick')),...
            'Visible','off',...
            'Value',0,...
            'Callback','ezaxes(37)');
        bi(17) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.55 .325 .2 .1*sfactor],...
            'String','Ticks',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(17)');

        %% ticklabel edit
        ui(18)=uicontrol('Style','edit','Units','Normalized',...
            'Position',[.55 .175 .44 .1*sfactor],...
            'String',mat2str(get(haold,'XTickLabels')),...
            'Visible','off',...
            'Value',0,...
            'Callback','ezaxes(38)');
        bi(18) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.55 .175 .2 .1*sfactor],...
            'String','Tick Labels',...
            'Visible','on',...
            'Value',0,...
            'Callback','ezaxes(18)');

        %%% text strings
        uicontrol(...
            'style','text',...
            'string','Direction:',...
            'units','normalized',...
            'HorizontalAlignment','Center',...
            'position',[.5 .85 .3 .1*sfactor],...
            'BackgroundColor',[ 0 0 0 ],...
            'ForegroundColor',[ 0 1 0 ]);

        set(newfig,'UserData',[ui' bi']);

    elseif command == 1

    elseif command == 2
        handles = get(gcf,'UserData');
        if strcmp(get(handles(1,2),'Box'),'off')
            set(handles(1,2),'Box','on')
        else
            set(handles(1,2),'Box','off')
        end
    elseif command == 3
        handles = get(gcf,'UserData');
        figure_w_normalized_uicontrolunits(handles(1,1))
        grid
    elseif command == 4
        handles = get(gcf,'UserData');
        set(handles(4,2),'Visible','off')
        set(handles(4,1),'Visible','on')
    elseif command == 24
        handles = get(gcf,'UserData');
        T4=['Equal ';'Square';'Normal';'Image ';'On    ';'Off   '];
        figure_w_normalized_uicontrolunits(handles(1,1))
        axis(deblank(lower(T4(get(handles(4,1),'Value'),:))))
        set(handles(4,2),'Visible','on')
        set(handles(4,1),'Visible','off')

    elseif command == 5
        handles = get(gcf,'UserData');
        if strcmp(get(handles(1,2),'TickDir'),'in')
            set(handles(1,2),'TickDir','out')
        else
            set(handles(1,2),'TickDir','in')
        end
    elseif command == 6
        handles = get(gcf,'UserData');
        set(handles(6,2),'Visible','off')
        set(handles(6,1),'String',vec2str(get(handles(1,2),'Ticklength')))
        set(handles(6,1),'Visible','on')
    elseif command == 26
        handles = get(gcf,'UserData');
        set(handles(1,2),'TickLength',eval(get(handles(6,1),'String')))
        set(handles(6,2),'Visible','on')
        set(handles(6,1),'Visible','off')
    elseif command == 7
        handles = get(gcf,'UserData');
        set(handles(7,2),'Visible','off')
        set(handles(7,1),'Visible','on')
    elseif command == 27
        handles = get(gcf,'UserData');
        T7=[' - ';' --';' : ';' -.'];
        set(handles(1,2),'GridLineStyle',T7(get(handles(7,1),'Value'),:))
        set(handles(7,2),'Visible','on')
        set(handles(7,1),'Visible','off')

    elseif command == 8
        handles = get(gcf,'UserData');
        set(handles(8,2),'Visible','off')
        set(handles(8,1),'Visible','on')
    elseif command == 28
        handles = get(gcf,'UserData');
        T8=['Avant Garde           ';...
            'Bookman               ';...
            'Courier               ';...
            'Helvetica             ';...
            'Helvetica Narrow      ';...
            'New Century Schoolbook';...
            'Palatino              ';...
            'Symbol                ';...
            'Times                 ';...
            'Zapf Chancery         ';...
            'Zapf Dingbats         '];
        set(handles(1,2),'FontName',deblank(T8(get(handles(8,1),'Value'),:)))
        set(handles(8,2),'Visible','on')
        set(handles(8,1),'Visible','off')

    elseif command == 9
        handles = get(gcf,'UserData');
        set(handles(9,2),'Visible','off')
        set(handles(9,1),'Visible','on')
    elseif command == 29
        T9=['10';'12';'16';'20';'24';'30'];
        handles = get(gcf,'UserData');
        set(handles(1,2),'FontSize',eval(T9(get(handles(9,1),'Value'),:)))
        set(handles(9,2),'Visible','on')
        set(handles(9,1),'Visible','off')

    elseif command == 10
        handles = get(gcf,'UserData');
        set(handles(10,2),'Visible','off')
        set(handles(10,1),'Visible','on')
    elseif command == 30
        T10=['Normal ';...
            'Light  ';...
            'Demi   ';...
            'Bold   '];
        handles = get(gcf,'UserData');
        set(handles(1,2),'FontWeight',deblank(T10(get(handles(10,1),'Value'),:)))
        set(handles(10,2),'Visible','on')
        set(handles(10,1),'Visible','off')

    elseif command == 11
        handles = get(gcf,'UserData');
        set(handles(11,2),'Visible','off')
        set(handles(11,1),'Visible','on')
    elseif command == 31
        T11=['Normal ';'Italic ';'Oblique'];
        handles = get(gcf,'UserData');
        set(handles(1,2),'FontAngle',deblank(T11(get(handles(11,1),'Value'),:)))
        set(handles(11,2),'Visible','on')
        set(handles(11,1),'Visible','off')

    elseif command == 12
        handles = get(gcf,'UserData');
        if strcmp(get(handles(12,2),'String'),'X')
            set(handles(12,2),'String','Y')
        elseif strcmp(get(handles(12,2),'String'),'Y')
            set(handles(12,2),'String','Z')
        else
            set(handles(12,2),'String','X')
        end

    elseif command == 13
        handles = get(gcf,'UserData');
        if strcmp(get(handles(12,2),'String'),'X')
            if strcmp(get(handles(1,2),'XDir'),'normal')
                set(handles(1,2),'XDir','reverse')
            else
                set(handles(1,2),'XDir','normal')
            end
        elseif strcmp(get(handles(12,2),'String'),'Y')
            if strcmp(get(handles(1,2),'YDir'),'normal')
                set(handles(1,2),'YDir','reverse')
            else
                set(handles(1,2),'YDir','normal')
            end
        else
            if strcmp(get(handles(1,2),'ZDir'),'normal')
                set(handles(1,2),'ZDir','reverse')
            else
                set(handles(1,2),'ZDir','normal')
            end
        end

    elseif command == 14
        handles = get(gcf,'UserData');
        if strcmp(get(handles(12,2),'String'),'X')
            if strcmp(get(handles(1,2),'XGrid'),'on')
                set(handles(1,2),'XGrid','off')
            else
                set(handles(1,2),'XGrid','on')
            end
        elseif strcmp(get(handles(12,2),'String'),'Y')
            if strcmp(get(handles(1,2),'YGrid'),'on')
                set(handles(1,2),'YGrid','off')
            else
                set(handles(1,2),'YGrid','on')
            end

        else
            if strcmp(get(handles(1,2),'ZGrid'),'on')
                set(handles(1,2),'ZGrid','off')
            else
                set(handles(1,2),'ZGrid','on')
            end

        end
    elseif command == 15
        handles = get(gcf,'UserData');
        if strcmp(get(handles(12,2),'String'),'X')
            if strcmp(get(handles(1,2),'XScale'),'linear')
                set(handles(1,2),'XScale','log')
            else
                set(handles(1,2),'XScale','linear')
            end
        elseif strcmp(get(handles(12,2),'String'),'Y')
            if strcmp(get(handles(1,2),'YScale'),'linear')
                set(handles(1,2),'YScale','log')
            else
                set(handles(1,2),'YScale','linear')
            end

        else
            if strcmp(get(handles(1,2),'ZScale'),'linear')
                set(handles(1,2),'ZScale','log')
            else
                set(handles(1,2),'ZScale','linear')
            end
        end
    elseif command == 16
        handles = get(gcf,'UserData');
        set(handles(16,2),'Visible','off')
        if strcmp(get(handles(12,2),'String'),'X')
            set(handles(16,1),'String',vec2str(get(handles(1,2),'Xlim')))
        elseif strcmp(get(handles(12,2),'String'),'Y')
            set(handles(16,1),'String',vec2str(get(handles(1,2),'Ylim')))
        else
            set(handles(16,1),'String',vec2str(get(handles(1,2),'Zlim')))
        end
        set(handles(16,1),'Visible','on')
    elseif command == 36
        handles = get(gcf,'UserData');
        if strcmp(get(handles(12,2),'String'),'X')
            set(handles(1,2),'Xlim',eval(get(handles(16,1),'String')))
        elseif strcmp(get(handles(12,2),'String'),'Y')
            set(handles(1,2),'Ylim',eval(get(handles(16,1),'String')))
        else
            set(handles(1,2),'Zlim',eval(get(handles(16,1),'String')))
        end

        set(handles(16,2),'Visible','on')
        set(handles(16,1),'Visible','off')

    elseif command == 17
        handles = get(gcf,'UserData');
        set(handles(17,2),'Visible','off')
        if strcmp(get(handles(12,2),'String'),'X')
            set(handles(17,1),'String',vec2str(get(handles(1,2),'XTick')))
        elseif strcmp(get(handles(12,2),'String'),'Y')
            set(handles(17,1),'String',vec2str(get(handles(1,2),'YTick')))
        else
            set(handles(17,1),'String',vec2str(get(handles(1,2),'ZTick')))
        end
        set(handles(17,1),'Visible','on')
    elseif command == 37
        handles = get(gcf,'UserData');
        if strcmp(get(handles(12,2),'String'),'X')
            set(handles(1,2),'XTick',eval(get(handles(17,1),'String')))
        elseif strcmp(get(handles(12,2),'String'),'Y')
            set(handles(1,2),'YTick',eval(get(handles(17,1),'String')))
        else
            set(handles(1,2),'ZTick',eval(get(handles(17,1),'String')))
        end

        set(handles(17,2),'Visible','on')
        set(handles(17,1),'Visible','off')

    elseif command == 18
        handles = get(gcf,'UserData');
        set(handles(18,2),'Visible','off')
        if strcmp(get(handles(12,2),'String'),'X')
            set(handles(18,1),'String',ms2strv(get(handles(1,2),'XTickLabels')))
        elseif strcmp(get(handles(12,2),'String'),'Y')
            set(handles(18,1),'String',ms2strv(get(handles(1,2),'YTickLabels')))
        else
            set(handles(18,1),'String',ms2strv(get(handles(1,2),'ZTickLabels')))
        end
        set(handles(18,1),'Visible','on')
    elseif command == 38
        handles = get(gcf,'UserData');
        if strcmp(get(handles(12,2),'String'),'X')
            set(handles(1,2),'XTickLabels',ms2strv(get(handles(18,1),'String')))
        elseif strcmp(get(handles(12,2),'String'),'Y')
            set(handles(1,2),'YTickLabels',ms2strv(get(handles(18,1),'String')))
        else
            set(handles(1,2),'ZTickLabels',ms2strv(get(handles(18,1),'String')))
        end

        set(handles(18,2),'Visible','on')
        set(handles(18,1),'Visible','off')

    elseif command == 19

    elseif command == 20
    elseif command == 98
        handles = get(gcf,'UserData');
        figure_w_normalized_uicontrolunits(handles(1,1))
        refresh
    elseif command == 99
    end


function savedxf(node,face,elem,fname)
%
% savedxf(node,face,elem,fname)
%
% save a surface mesh to DXF format
%
% author: Qianqian Fang, <q.fang at neu.edu>
% date: 2010/04/25
%
% input:
%      node: input, surface node list, dimension (nn,3)
%      face: input, surface face element list, dimension (be,3)
%      elem: input, tetrahedral element list, dimension (ne,4)
%      fname: output file name
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

if(nargin==2)
   fname=face;
   face=[];
   elem=[];
end

if(nargin==3)
   fname=elem;
   elem=[];
end

fid=fopen(fname,'wt');
if(fid==-1)
    error('You do not have permission to save mesh files.');
end

fprintf(fid,'0\nSECTION\n2\nHEADER\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n');

if(~isempty(face))
  fprintf(fid,'0\nPOLYLINE\n66\n1\n8\nI2M\n70\n64\n71\n%d\n72\n%d\n',size(node,1),size(face,1));
end

if(~isempty(node))
  node=node(:,1:3);
  fprintf(fid,'0\nVERTEX\n8\nI2M\n10\n%.16f\n20\n%.16f\n30\n%.16f\n70\n192\n',node');
end

if(~isempty(face))
  face=face(:,1:3);
  fprintf(fid,'0\nVERTEX\n8\nI2M\n62\n254\n10\n0.0\n20\n0.0\n30\n0.0\n70\n128\n71\n%d\n72\n%d\n73\n%d\n',face');
end

fprintf(fid,'0\nSEQEND\n0\nENDSEC\n');

if(~isempty(face))
  fprintf(fid,'0\nSECTION\n2\nENTITIES\n0\nINSERT\n8\n1\n2\nMesh\n10\n0.0\n20\n0.0\n30\n0.0\n41\n1.0\n42\n1.0\n43\n1.0\n50\n0.0\n0\nENDSEC\n');
end

fprintf(fid,'0\nEOF');

fclose(fid);


function y = mod(varargin)
% Allows inputs to be char
if ischar(varargin{1})
    varargin{1} = double(varargin{1});
end
if ischar(varargin{2})
    varargin{2} = double(varargin{2});
end
if ~any(cellfun(@(x) isa(x,'sym'), varargin))
    y = builtin('mod', varargin{:});
else
    y = builtin('@sym/mod', varargin{:});
end
end


function h = quiver(sAF,varargin)
% quiver spherical axis field
%
% Syntax
%   quiver3(sAF)
%
% See also
%   S2VectorField/plot
%

% plot the function values
h = plot(sAF,varargin{:});

% remove output if not required
if nargout == 0, clear h; end

end


function [HDR] = sclose(HDR)
% SCLOSE closes the file with the handle HDR
% [HDR] = sclose(HDR)
%    HDR.FILE.status = -1 if file could not be closed.
%    HDR.FILE.status = 0 indicates the file has been closed.
%
% see also: SOPEN, SREAD, SSEEK, STELL, SCLOSE, SWRITE

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

%	$Id: sclose.m 2566 2010-11-24 13:04:34Z schloegl $
%	(C) 1997-2005,2006,2008 by Alois Schloegl <a.schloegl@ieee.org>
%    	This is part of the BIOSIG-toolbox http://biosig.sf.net/

if (HDR.FILE.FID<0) || ~HDR.FILE.OPEN,
        HDR.FILE.status = -1;
        %fprintf(HDR.FILE.stderr,'Warning SCLOSE (%s): invalid handle\n',HDR.FileName);
end;

if HDR.FILE.OPEN >= 2,          % write-open of files
	% check file length - simple test for file integrity
        EndPos = ftell(HDR.FILE.FID);          % get file length
        % force file pointer to the end, otherwise Matlab 6.5 R13 on PCWIN
        status = fseek(HDR.FILE.FID,0,'eof');

        if strcmp(HDR.TYPE,'BKR');
                if HDR.NS<1,
                        fprintf(HDR.FILE.stderr,'Error SCLOSE BKR: number of channels (HDR.NS) must be larger than zero.\n');
                        return;
                end;
                if HDR.NRec<1,
                        fprintf(HDR.FILE.stderr,'Error SCLOSE BKR: number of blocks (HDR.NRec) must be larger than zero.\n');
                        return;
                end;
                % check file length and write Headerinfo.
                HDR.SPR = (EndPos-HDR.HeadLen)/(HDR.NRec*HDR.NS*2);
                if isnan(HDR.SPR), HDR.SPR=0; end;
                if HDR.FILE.OPEN==3;
                        if any(isnan([HDR.NRec,HDR.NS,HDR.SPR,HDR.DigMax,HDR.PhysMax,HDR.SampleRate])), 	% if any unknown, ...
                                fprintf(HDR.FILE.stderr,'Error SCLOSE BKR: some important header information is still undefined (i.e. NaN).\n');
                                fprintf(HDR.FILE.stderr,'\t HDR.NRec,HDR.NS,HDR.SPR,HDR.DigMax,HDR.PhysMax,HDR.SampleRate must be defined.\n');
                                fprintf(HDR.FILE.stderr,'\t Try again.\n');
                        end;

                        fclose(HDR.FILE.FID);
                        HDR.FILE.FID = fopen(HDR.FileName,'r+');

                        count=fwrite(HDR.FILE.FID,HDR.VERSION,'int16');	        % version number of header
                        count=fwrite(HDR.FILE.FID,HDR.NS,'int16');	        % number of channels
                        count=fwrite(HDR.FILE.FID,HDR.SampleRate,'int16');      % sampling rate
                        count=fwrite(HDR.FILE.FID,HDR.NRec,'int32');            % number of trials: 1 for untriggered data
                        count=fwrite(HDR.FILE.FID,HDR.SPR,'uint32');            % samples/trial/channel
                        count=fwrite(HDR.FILE.FID,HDR.PhysMax,'int16');		% Kalibrierspannung
                        count=fwrite(HDR.FILE.FID,HDR.DigMax, 'int16');		% Kalibrierwert
                        count=fwrite(HDR.FILE.FID,zeros(4,1),'uint8');
                        count=fwrite(HDR.FILE.FID,[HDR.Filter.LowPass,HDR.Filter.HighPass],'float');

                        fseek(HDR.FILE.FID,32,'bof');
                        HDR.FLAG.TRIGGERED   = HDR.NRec>1;	% Trigger Flag
                        count = fwrite(HDR.FILE.FID,HDR.FLAG.TRIGGERED,'int16');           % FLAG TRIGGERED
                end;

	elseif strcmp(HDR.TYPE,'EDF') || strcmp(HDR.TYPE,'BDF') || strcmp(HDR.TYPE,'GDF'),
         	tmp = floor((EndPos - HDR.HeadLen) / HDR.AS.bpb);  % calculate number of records
                if isnan(tmp)
                	tmp = 0;
                end;

                if (HDR.NRec~=tmp)
                       if ~any(HDR.FILE.PERMISSION=='z')
                               HDR.NRec=tmp;
                               fseek(HDR.FILE.FID,236,'bof');
                               if strcmp(HDR.TYPE,'GDF')
                                        c=fwrite(HDR.FILE.FID,[HDR.NRec,0],'int32');
                               else
                                        fprintf(HDR.FILE.FID,'%-8i',HDR.NRec);
                                end;
                        else    %% due to a limitation in zlib
                                fprintf(HDR.FILE.stderr,'ERROR SCLOSE: number-of-records-field (HDR.NRec) could not be updated in file %s.\n',HDR.FileName);
                        end;
                end;

                if strcmp(HDR.TYPE,'GDF') && isfield(HDR,'EVENT'),
                	if ~all([HDR.NS, HDR.NRec, HDR.AS.bpb]>0)
                		HDR.AS.EVENTTABLEPOS = HDR.HeadLen;
                	else
	                        HDR.AS.EVENTTABLEPOS = HDR.HeadLen+HDR.AS.bpb*HDR.NRec;
	                end;
                        if isfield(HDR.EVENT,'VAL')
                                % handling of sparse (non-equidistant) sampling values
                                if isempty(HDR.EVENT.DUR)
                                        HDR.EVENT.DUR = zeros(size(HDR.EVENT.TYP));
                                end;
                                if (HDR.VERSION<1.90)
                                        fprintf(2,'Warning SCLOSE: GDF v2.0 or higher required for storing sparse samples but version is only %4.2f.\n',HDR.VERSION);
                                        %ix0 = ~isnan(HDR.EVENT.VAL);
                                        %HDR.EVENT.POS = HDR.EVENT.POS(~ix0);
                                        %HDR.EVENT.TYP = HDR.EVENT.TYP(~ix0);
                                        %HDR.EVENT.CHN = HDR.EVENT.CHN(~ix0);
                                        %HDR.EVENT.DUR = HDR.EVENT.DUR(~ix0);
                                        %HDR.EVENT = rmfield(HDR.EVENT,'VAL');
                                end;
	                end;
                        if isfield(HDR.EVENT,'VAL')
                                ix  = find(~isnan(HDR.EVENT.VAL));
                                tmp = unique(HDR.EVENT.CHN(ix));

                                flag.invalid = 0;
                                if (~all(HDR.EVENT.CHN(ix) > 0))
                                        flag.invalid = 1;
                                        fprintf(2,'Warning SCLOSE: Sparse sampling values without valid channel. Samples are not stored.\n');
                                        tmp = tmp(tmp > 0);
                                end;
                                if any(HDR.GDFTYP(tmp) > 6)
                                        fprintf(2,'Warning SCLOSE: Sparse sampling values must be of type integer using no more than 32 bits. Data is converted to uint32.\n');
                                end;

                                if any(HDR.AS.SPR(tmp)) || flag.invalid,
                                        fprintf(2,'Warning SCLOSE: Sparse sampling value for non-sparse channels not allowed. The following channel(s) is(are) affected: ');
                                        fprintf(2,'%i', tmp(HDR.AS.SPR(tmp)>0) );
                                        fprintf(2,'.  Samples are not stored.\n')
                                        ix0 = ~isnan(HDR.EVENT.VAL) & ~(HDR.EVENT.CHN>0); % initialize index with logical(0)
                                        for k = 1:length(tmp),
                                                if (HDR.AS.SPR(tmp(k))>0),
                                                        ix0 = ix0 | (HDR.EVENT.CHN==tmp(k));
                                                end;
                                        end;
                                        HDR.EVENT.POS = HDR.EVENT.POS(~ix0);
                                        HDR.EVENT.TYP = HDR.EVENT.TYP(~ix0);
                                        HDR.EVENT.CHN = HDR.EVENT.CHN(~ix0);
                                        HDR.EVENT.DUR = HDR.EVENT.DUR(~ix0);
                                        HDR.EVENT.VAL = HDR.EVENT.VAL(~ix0);
                                        ix = ~isnan(HDR.EVENT.VAL);
                                end;

                                % prepare for storing
                                HDR.EVENT.TYP(ix) = hex2dec('7fff');
                                HDR.EVENT.DUR(ix) = HDR.EVENT.VAL(ix);
                        end;

                        len = [length(HDR.EVENT.POS),length(HDR.EVENT.TYP)];
                        EVENT.Version = 1;
                        if isfield(HDR.EVENT,'CHN') && isfield(HDR.EVENT,'DUR'),
                                if any(HDR.EVENT.CHN) || any(HDR.EVENT.DUR),
                                        EVENT.Version = 3;
					len = [len,length(HDR.EVENT.CHN),length(HDR.EVENT.DUR)];
                                end;
                        end;

                        if any(len~=len(1))
                                fprintf(HDR.FILE.stderr,'Error SCLOSE-GDF: cannot write Event table, file %s not closed.\n',HDR.FileName);
				return;
                        else
                                status  = fseek(HDR.FILE.FID,HDR.HeadLen+HDR.AS.bpb*HDR.NRec,'bof');
                                %status = fseek(HDR.FILE.FID,0,'eof');
                                if ftell(HDR.FILE.FID)~=HDR.AS.EVENTTABLEPOS,
                                        fprintf(HDR.FILE.stderr,'Warning SCLOSE-GDF: inconsistent GDF file\n');
                                end
				if ~isfield(HDR.EVENT,'SampleRate'),
					HDR.EVENT.SampleRate = HDR.SampleRate;
				end;

				% write eventtable info: Version, SampleRate & length
				if (HDR.VERSION<1.94)
					tmp = HDR.EVENT.SampleRate;
					tmp = [EVENT.Version,mod(tmp,256),floor(mod(tmp,65536)/256),floor(tmp/65536)];
	                                fwrite(HDR.FILE.FID,tmp,'uint8');
	                                fwrite(HDR.FILE.FID,length(HDR.EVENT.POS),'uint32');
				else
					tmp = length(HDR.EVENT.POS);
					tmp = [EVENT.Version,mod(tmp,256),floor(mod(tmp,65536)/256),floor(tmp/65536)];
	                                fwrite(HDR.FILE.FID,tmp,'uint8');
	                                fwrite(HDR.FILE.FID,HDR.EVENT.SampleRate,'float32');
				end;

				% write table
                                c1 = fwrite(HDR.FILE.FID,HDR.EVENT.POS,'uint32');
                                c2 = fwrite(HDR.FILE.FID,HDR.EVENT.TYP,'uint16');
                                c3 = length(HDR.EVENT.POS); c4 = c3;
                                if EVENT.Version==3;
                                        c3 = fwrite(HDR.FILE.FID,HDR.EVENT.CHN,'uint16');
                                        c4 = fwrite(HDR.FILE.FID,HDR.EVENT.DUR,'uint32');
                                end;
                                if any([c1,c2,c3,c4]~=length(HDR.EVENT.POS))
                                        fprintf(2,'\nError SCLOSE: writing of EVENTTABLE failed. File %s not closed.\n', HDR.FileName);
                                        return;
                                end
                        end;
                end;

        elseif strcmp(HDR.TYPE,'CFWB');
                tmp = (EndPos-HDR.HeadLen)/HDR.AS.bpb;
                if isnan(tmp), tmp=0; end;
                if (tmp~=HDR.NRec);
                        if ~any(HDR.FILE.PERMISSION=='z')
                                HDR.NRec = tmp;
                                fseek(HDR.FILE.FID,14*4,-1);
                                count = fwrite(HDR.FILE.FID,HDR.NRec,'int32');           % channels
                        else
                                fprintf(HDR.FILE.stderr,'ERROR SCLOSE (CFWB): number-of-samples-field (HDR.SPR) could not be updated in file %s.\n',HDR.FileName);
                        end;
                end;

        elseif strcmp(HDR.TYPE,'SND');
                tmp = (EndPos-HDR.HeadLen)/HDR.AS.bpb;
                if isnan(tmp), tmp=0; end;
                if (HDR.FILE.OPEN==3) && (tmp~=HDR.SPR);
                        if ~any(HDR.FILE.PERMISSION=='z')
                                HDR.SPR = tmp;
                                fseek(HDR.FILE.FID,8,'bof');
                                count = fwrite(HDR.FILE.FID,HDR.SPR*HDR.AS.bpb,'uint32');           % bytes
                                fseek(HDR.FILE.FID,20,-1);
                                count = fwrite(HDR.FILE.FID,HDR.NS,'uint32');           % channels
                        else
                                fprintf(HDR.FILE.stderr,'ERROR SCLOSE (SND): fields HDR.SPR and HDR.NS could not be updated in file %s.\n',HDR.FileName);
                        end;
		end;

        elseif strcmp(HDR.TYPE,'AIF');
                if HDR.FILE.OPEN==3;
                        fseek(HDR.FILE.FID,4,-1);
                        count = fwrite(HDR.FILE.FID,EndPos-8,'uint32');           % bytes
                        fseek(HDR.FILE.FID,HDR.WAV.posis(2),-1);
                        count = fwrite(HDR.FILE.FID,EndPos-4-HDR.WAV.posis(2),'uint32');           % channels
                end;

        elseif strcmp(HDR.TYPE,'FLT') ;
		% warning FLT/header might have changed in needs to be rewritten
        elseif strcmp(HDR.TYPE,'WAV') ;
                if HDR.FILE.OPEN==3;
                        fseek(HDR.FILE.FID,4,-1);
                        count = fwrite(HDR.FILE.FID,EndPos-16,'uint32');           % bytes
                        fseek(HDR.FILE.FID,HDR.WAV.posis(2),-1);
                        count = fwrite(HDR.FILE.FID,EndPos-4-HDR.WAV.posis(2),'uint32');           % channels
                end;
        end;
end;

if 0,
elseif strcmp(HDR.TYPE,'ZIP')
        [SUCCESS,MESSAGE,MESSAGEID] = rmdir(HDR.ZIP.TEMPDIR,'s');

elseif strcmp(HDR.TYPE,'FIF') && HDR.FILE.OPEN;
        global FLAG_NUMBER_OF_OPEN_FIF_FILES
        rawdata('close');
        HDR.FILE.OPEN = 0;
        HDR.FILE.status = 0;
        FLAG_NUMBER_OF_OPEN_FIF_FILES = FLAG_NUMBER_OF_OPEN_FIF_FILES-1;

elseif strmatch(HDR.TYPE,{'ADI','GTEC','LABVIEW','MAT','MAT4','MAT5','native','XML','XML-FDA','SierraECG'}),
        HDR.FILE.OPEN = 0;

elseif HDR.FILE.OPEN,
        HDR.FILE.OPEN = 0;
        HDR.FILE.status = fclose(HDR.FILE.FID);
end;


function [val,lb,ub] = gridconstraints(fh,x_struct, p_struct, k, N, x, p, userdata)
gridConHandler = ocl.Constraint(userdata);
x = ocl.Variable.create(x_struct,x);
p = ocl.Variable.create(p_struct,p);

fh(gridConHandler,k,N,x,p);

val = gridConHandler.values;
lb = gridConHandler.lowerBounds;
ub = gridConHandler.upperBounds;


% eegdrawg() - subroutine used by eegplotgold() to plot data.
%
% Author: Colin Humphries, CNL, Salk Institute, La Jolla, 7/96

% Copyright (C) Colin Humphries, CNL, Salk Institute 7/96 from eegplot()
%
% 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

% 4-4-97 shortened name to eegdrawq() -sm
% 4-7-97 allowed data names other than 'data' -ch
% 01-25-02 reformated help & license -ad

function y = eegdrawg(fighandle)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Extract variables from figure and axes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

userdata = get(fighandle,'UserData');
samplerate = userdata(1);
PLOT_TIME = userdata(2);
spacing_var = userdata(3);
time = userdata(4);
maxtime = userdata(5);
axhandle = userdata(6);
plotcolor = userdata(7);
disp_scale = userdata(12);
colors = ['y','w'];
dataname = get(axhandle,'UserData');
eval(['global ',dataname])

cla % Clear figure

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Define internal variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

eval(['[chans,frames] = size(',dataname,');']);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Label x-axis
% This routine relabels the x-axis based on the new value of time.
% Labels are placed on one second intervals
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Xlab = num2str(time);
for j = 1:1:PLOT_TIME
   Q = num2str(time+j);
   Xlab = str2mat(Xlab, Q);
end
set (gca, 'Ytick', 0:spacing_var:chans*spacing_var)
set (gca, 'XTickLabels', Xlab)
set (gca, 'XTick',(0:samplerate:PLOT_TIME*samplerate))

axis([0 PLOT_TIME*samplerate 0 (chans+1)*spacing_var]);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plotting routine
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for i = 1:chans                 %repeat for each channel
   if (maxtime-time>PLOT_TIME)
      eval(['F = ',dataname,'(chans-i+1,(time*samplerate)+1:((time+PLOT_TIME)*samplerate));'])
   else
      eval(['F = ',dataname,'(chans-i+1,(time*samplerate)+1:(maxtime*samplerate));'])
   end
   F = F - mean(F) + i*spacing_var;
   plot (F,'clipping','off','color',colors(plotcolor))
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot Scaling I
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if disp_scale == 1
   line([(PLOT_TIME+.3)*samplerate,(PLOT_TIME+.3)*samplerate],[1.5*spacing_var 2.5*spacing_var],'clipping','off','color','w')
   line([(PLOT_TIME+.3)*samplerate-10,(PLOT_TIME+.3)*samplerate+10],[2.5*spacing_var,2.5*spacing_var],'clipping','off','color','w')
   line([(PLOT_TIME+.3)*samplerate-10,(PLOT_TIME+.3)*samplerate+10],[1.5*spacing_var,1.5*spacing_var],'clipping','off','color','w')
   text((PLOT_TIME+.5)*samplerate,2*spacing_var,num2str(round(spacing_var)),'clipping','off')
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set slider=edit
% This routine resets the value of the user controls so that
%    they agree.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

   H = findobj(fighandle,'style','slider');
   D = findobj(fighandle,'style','edit');
   set (D, 'string', num2str(time));