function fh = mycursors(varargin)
% MYCURSORS - Create as many cursors as you want on an axes
%   FH = MYCURSORS(VARARGIN) add cursor on an axes.
%
%   VARARGIN can contain 0, 1 or 2 elements:
%     1) First input is the handle of the axes on which you want to create the
%        cursor.
%        Default value is the current axes (GCA)
%     2) Second input is the color of the cursor.
%        Default value is red ('r' or [1 0 0])
%
%   FH is a structure containing function handles that enable you to manipulate
%   the cursor. FH structure looks like:
%     FH.add(XPOS) : Adds a cursor on the same axes at the position x = XPOS.
%                    XPOS is facultative. Default value is the middle of the
%                    axes.
%     FH.off(NUM)  : Removes the NUMth cursor created
%                    If NUM is a character string then the function removes only
%                    the last cursor.
%     FH.val(NUM)  : Returns a vector containing the positions of the NUMth
%                    cursor.
%                    If you omit NUM then the function returns the position of
%                    all cursors.
%     FH.hdl()     : Returns a matrix containing the handles of the cursors in
%                    the first column and the handles of the associated labels
%                    in the second column.

% Default inputs
inArgs = {...
  gca, ... % Current axes is used by default
  'r'  ... % Default color for cursors is red
  };

% Replace default input arguments by input values
inArgs(1:nargin) = varargin;

% Initializations
axeH = inArgs{1};
figH = ancestor(axeH,'figure');
curH = [];
labH = [];
curC = [];
curL = [];
yLim = ylim(axeH);
curColor = inArgs{2};

% Add a cursor
CursorAdd();

% Assign Output Argument
fh = struct('add',@CursorAdd,'off',@CursorOff,'val',@CursorValue,'hdl',@CursorHandles);

% Drag Cursor shape
curCData = [...
  NaN NaN NaN NaN NaN   2   2   2   2   2 NaN NaN NaN NaN NaN NaN
  NaN NaN NaN NaN NaN   2   1   2   1   2 NaN NaN NaN NaN NaN NaN
  NaN NaN NaN NaN NaN   2   1   2   1   2 NaN NaN NaN NaN NaN NaN
  NaN NaN NaN NaN   2   2   1   2   1   2   2 NaN NaN NaN NaN NaN
  NaN NaN NaN   2   1   2   1   2   1   2   1   2 NaN NaN NaN NaN
  NaN NaN   2   1   1   2   1   2   1   2   1   1   2 NaN NaN NaN
  NaN   2   1   1   1   1   1   2   1   1   1   1   1   2 NaN NaN
    2   1   1   1   1   1   1   2   1   1   1   1   1   1   2 NaN
  NaN   2   1   1   1   1   1   2   1   1   1   1   1   2 NaN NaN
  NaN NaN   2   1   1   2   1   2   1   2   1   1   2 NaN NaN NaN
  NaN NaN NaN   2   1   2   1   2   1   2   1   2 NaN NaN NaN NaN
  NaN NaN NaN NaN   2   2   1   2   1   2   2 NaN NaN NaN NaN NaN
  NaN NaN NaN NaN NaN   2   1   2   1   2 NaN NaN NaN NaN NaN NaN
  NaN NaN NaN NaN NaN   2   1   2   1   2 NaN NaN NaN NaN NaN NaN
  NaN NaN NaN NaN NaN   2   2   2   2   2 NaN NaN NaN NaN NaN NaN
  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
  ];
curHotSpot = [8 8];

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

  function CursorAdd(varargin)
    % Adds a new cursor on the axes

    % Check input to define default cursor position
    if nargin
      defPos = varargin{1};
    else
      defPos = diff(xlim(axeH)) / 2;
    end

    % Get axes limits
    yLim2 = ylim(axeH);

    % Create Cursor Line
    curH(end+1) = line([defPos defPos],yLim2,'Color',curColor,'LineWidth',2,'Parent',axeH);

    % Create associated label
    labH(end+1) = text(defPos,yLim2(2),...
      sprintf('%u',length(curH)),...
      'BackgroundColor','w',...
      'EdgeColor',curColor,...
      'LineWidth',2,...
      'Color',curColor,...
      'FontSize',8,...
      'FontWeight','bold');

    % Set the WindowButtonDownFcn
    set(curH(end),'ButtonDownFcn',@ButtonDownFcn)

  end

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

  function CursorOff(varargin)
    % Remove one or all cursors

    % Execute only if there is a cursor
    if ~isempty(curH)

      if nargin

        if ischar(varargin{1})
          ind2del = length(curH); % Remove last cursor if nothing is specified
        else
          ind2del = varargin{1};
          ind2del(ind2del>length(curH)) = []; % Remove indices outside the range
          ind2del(ind2del<1) = []; % Remove indices outside the range
        end

        % Delete specified cursor and associated label
        delete(curH(ind2del));
        delete(labH(ind2del));

        % Remove cursor and label handles from vectors
        curH(ind2del) = [];
        labH(ind2del) = [];

        % Update labels
        for indL=1:length(labH)
          set(labH(indL),'String',indL)
        end

      else

        % Remove all cursors and all associated labels
        delete([curH labH]);

      end

    end

  end

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

  function res = CursorValue(varargin)
    % Returns the positions of each cursor in a vector

    % Executes only if there is a cursor
    if ~isempty(curH)

      if nargin

        % Ensure that number specified in input argument is correct
        ind = varargin{1};
        ind(ind>length(curH)) = []; % Remove indices outside the range
        ind(ind<1) = []; % Remove indices outside the range

        % Retrieve data
        res = get(curH(ind),'XData');

      else

        % If no input specified then returns all positions
        if ~iscell(get(curH,'XData'))
          res = cell2mat({get(curH,'XData')});
        else
          res = cell2mat(get(curH,'XData'));
        end

      end

      % Remove the second column
      res(:,2) = [];

    else

      % If there is no cursor then returns an empty vector
      res = [];

    end

  end

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

  function res = CursorHandles()
    % Returns a matrix with cursor handles in the first column and labels
    % handles in the second

    % Execute only if there is a cursor
    if ~isempty(curH)

      res = [curH(:) labH(:)];

    end

  end

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

  function ButtonDownFcn(varargin)

    % Update current cursor handle
    curC = varargin{1};

    if ~isempty(curC)

      % Get label handle associated
      curL = labH(curC==curH);

      % Change cursor pointer
      set(figH,'Pointer','custom','PointerShapeCData',curCData,'PointerShapeHotSpot',curHotSpot)

      % Update EraseMode property for the current Cursor
      set(curC,'EraseMode','xor')

      % Update figure callbacks
      set(figH,'WindowButtonMotionFcn',@ButtonMotionFcn)
      set(figH,'WindowButtonUpFcn',@ButtonUpFcn)

    end

  end

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

  function ButtonUpFcn(varargin)

    % Change cursor pointer
    set(figH,'Pointer','arrow')

    % Update EraseMode property for the current Cursor
    set(curC,'EraseMode','normal')

    % Update Figure Callbacks
    set(figH,'WindowButtonMotionFcn','')

    % Unset current Cursor and label
    curC = [];
    curL = [];

  end

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

  function ButtonMotionFcn(varargin)

    % Get current point
    curP = get(axeH,'CurrentPoint');

    % Get axes limits
    yLim2 = ylim(axeH);

    % Update cursor position
    set(curC,'XData',[curP(1) curP(1)],'YData',[min(yLim(1),yLim2(1)) max(yLim(2),yLim2(2))])

    % Move label
    set(curL,'Position',[curP(1) yLim2(2)]);

    % Refresh Display
    drawnow;

  end

end


function [fx,dfdx,dfdP] = f_Id(x,P,u,in)
% this function applies the identity mapping
fx = x;
dfdx = eye(size(x,1));
dfdP = zeros(size(P,1),size(x,1));


function test_suite = test_grDilate
%TEST_GRDILATE  test suite for function grDilate
%
%   output = test_grDilate(input)
%
%   Example
%   testGrDilate
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2011-05-18,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function testSimpleGraph(testCase) %#ok<*DEFNU>

[nodes, edges, values] = createTestGraph01(); %#ok<ASGLU>

valDil = grDilate(edges, values);
exp = [80;80;70;70;80;50;80;40];
testCase.assertEqual(exp, valDil);


classdef (Abstract) SolverApplication < handle
    % SolverApplication defines an abstract interface class for NLP solvers
    %
    %
    % @author Ayonga Hereid @date 2016-10-21
    %
    % Copyright (c) 2016, AMBER Lab
    % All right reserved.
    %
    % Redistribution and use in source and binary forms, with or without
    % modification, are permitted only in compliance with the BSD 3-Clause
    % license, see
    % http://www.opensource.org/licenses/bsd-license.php

    properties

        % A structure for NLP solver options
        %
        % @type struct
        Options

    end

    methods (Abstract)

        % An abstract method that initialize the solver to be ready to
        % solve the given NLP problem
        initialize(obj, nlp);

        % An abstract method that run the NLP problem
        optimize(obj, nlp);
    end

    methods
        function obj = SolverApplication()
            % The default constructor function

            obj.Options = struct;
        end

    end

end


% dipfit_1_to_2() - convert dipfit 1 structure to dipfit 2 structure.
%
% Usage:
%  >> EEG.dipfit = dipfit_1_to_2(EEG.dipfit);
%
% Note:
% For non-standard BESA models (where the radii or the conductances
% have been modified, users must create a new model in Dipfit2 from
% the default BESA model.
%
% Author: Arnaud Delorme, SCCN, La Jolla 2005

% Copyright (C) Arnaud Delorme, SCCN, La Jolla 2005
%
% 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 newdipfit = dipfit_1_to_2( dipfit );

    if isfield( dipfit, 'model')
        newdipfit.model = dipfit.model;
    end;
    if isfield( dipfit, 'chansel')
        newdipfit.chansel = dipfit.chansel;
    end;

    ind = 1; % use first template (BESA)
    newdipfit.coordformat = template_models(ind).coordformat;
    newdipfit.mrifile     = template_models(ind).mrifile;
    newdipfit.chanfile    = template_models(ind).chanfile;

    if ~isfield(dipfit, 'vol')
        newdipfit.hdmfile = template_models(ind).hdmfile;
    else
        newdipfit.vol     = dipfit.vol;

        %if length(dipfit.vol) == 4
            %if ~all(dipfit.vol == [85-6-7-1 85-6-7 85-6 85]) | ...
            %   ~all(dipfit.c   == [0.33 1.00 0.0042 0.33]) | ...
            %   ~all(dipfit.o = [0 0 0])
            %    disp('Warning: Conversion from dipfit 1 to dipfit 2 can only deal');
            %    disp('         with standard (not modified) BESA model');
            %    disp('         See "help dipfit_1_to_2" to convert this model');
            %    newdipfit = [];
            %end;
        %end;
    end;


function D = cubic_disp_2d(Knots, volsz, spacing)
% deform image
    if isa(Knots, 'single')
        D = mex_2d_cubic_disp_float(Knots, single(volsz), single(spacing));
    elseif isa(Knots, 'double')
        D = mex_2d_cubic_disp_double(Knots, volsz, spacing);
    elseif isa(Knots, 'gpuArray')
        error('Not implemented')
    else
        error('Variables class mismatch')
    end
end


check_active_images;

for kk =  ind_active,

   if ~exist(['x_' num2str(kk)]),

      fprintf(1,'WARNING: Need to extract grid corners on image %d\n',kk);

      active_images(kk) = 0;

      eval(['dX_' num2str(kk) ' = NaN;']);
      eval(['dY_' num2str(kk) ' = NaN;']);

      eval(['wintx_' num2str(kk) ' = NaN;']);
      eval(['winty_' num2str(kk) ' = NaN;']);

      eval(['x_' num2str(kk) ' = NaN*ones(2,1);']);
      eval(['X_' num2str(kk) ' = NaN*ones(3,1);']);

      eval(['n_sq_x_' num2str(kk) ' = NaN;']);
      eval(['n_sq_y_' num2str(kk) ' = NaN;']);

   else

      eval(['xkk = x_' num2str(kk) ';']);

      if isnan(xkk(1)),

	 fprintf(1,'WARNING: Need to extract grid corners on image %d - This image is now set inactive\n',kk);

	 active_images(kk) = 0;

      end;

   end;

end;


function status = tsinfo(filename)

% status = tsinfo(filename)
% display information about signal file 'filename'

trenner = '--------------------------------------------------------------------------------';

if exist(filename)
	sig = signal(filename);
	if isempty(sig)
		status = -1;
		warning(['Error opening file ' filename ]);
		return;
	else
		temp = dir(filename);
		filesize = num2str(temp.bytes);
		[path,Name,ext] = fileparts(filename);
		yunt = unit(yaxis(sig));
		string1 = { ...
		['Filename                        : ' filename] ; ...
		['Filesize                         : ' filesize ' bytes'] ; ...
		['Number of dimensions       : ' num2str(length(dlens(sig)))] ; ...
		['Length in each dimension   : ' num2str(dlens(sig))] ; ...
		['Total samples                  : ' num2str(prod(dlens(sig)))] ; ...
		trenner ; ...
 		['yname                           : ' name(yaxis(sig))] ; ...
		['yunit                              : '  name(yunt)] ; ...
		trenner };
		string2 = {};
% 		siz = size(sig.optparam);
% 		ende = siz(1);
% 		for i=1:ende
% 			string2 = addcomment(string2, [sig.optparam{i}]);
% 		end
%		string2 = addcomment(string2, trenner);
% 		string3 = {};
% 	   for i=1:length(dlens(sig))
% 			xax = xaxis(sig, i);
% 		   string3 = addcomment(string3, ['Dimension : ' num2str(i)]);
% 		   string3 = addcomment(string3, ['Length : ' num2str(dlens(sig, i))]);
% 		   string3 = addcomment(string3, ['xfirst : ' num2str(first(xax))]);
% 		   string3 = addcomment(string3, ['xdelta : ' num2str(delta(xax))]);
% 		   %string3 = addcomment(string3, ['xdelta^(-1) : ' num2str(1/delta(xax))]);
% 		   string3 = addcomment(string3, ['xunit : ' label(xax)]);
% 		   string3 = addcomment(string3, ['xname : ' name(xax)]);
% 		   string3 = addcomment(string3, trenner);
% 	   end
%
% 		string4 = { ['Comment :'] ; ''};
% 		string = addcomment(string3, trenner);
% 		string5 = { trenner; ['History :'] ; ''};
% 		string = cat(1, string1, string2, string3, string4, comment(sig), string5, history(sig));
%
		string = string1;
		handle = figure('Color', [1 1 1], ...
		'Resize','off', ...
		'NumberTitle','off', ...
		'KeyPressFcn','close(gcbf)', ...
		'MenuBar','none', ...
		'Name',['tsinfo on file ' Name]);
		pos = get(handle, 'Position');
		lbox = uicontrol('Parent',handle, ...
		'Units','points', ...
		'Position', [0.8 0.8 440 330], ...
		'BackgroundColor',[1 1 1], ...
		'String', string, ...
		'Style','listbox', ...
		'Tag','InfoListbox', ...
		'Value',1);
	end
else
	warndlg(['Can''t find file ' filename],'Info on File');
	status = -1;
	return;
end


function livefg(ma)
% livefg(m) where m is a initialized handle to a framegrabber shows live image
% in a window.

% Vladimir Smutny 22.10.1999

global loop

f = figure;
set(f, 'Name', 'Camera Viewer',...
   'NumberTitle', 'off',...
   'Interruptible','on',...
   'KeyPressFcn','global loop; loop=0;' );
colormap gray(256)
set(gca,'Position',[0,0,1,1]);

%image(grabfg(ma)')

mov=[];
mov.cdata = grabfg(ma)';
mov.colormap=gray(256);
movsize=size(mov.cdata);
set(gcf,'Position',[50,50,movsize(2),movsize(1)]);
loop = 1;
while (loop ~= 0),
   mov.cdata=grabfg(ma)';
   movie(mov);
   pause(0.1);
end


%{
Copyright (c) 2015, Tom Mertens
All rights reserved.

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

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

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

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

% Contruction of Laplacian pyramid
%
% Arguments:
%   image 'I'
%   'nlev', number of levels in the pyramid (optional)
%
% tom.mertens@gmail.com, August 2007
%
%
% More information:
%   'The Laplacian Pyramid as a Compact Image Code'
%   Burt, P., and Adelson, E. H.,
%   IEEE Transactions on Communication, COM-31:532-540 (1983).
%

function pyr = laplacian_pyramid(I,nlev)

r = size(I,1);
c = size(I,2);

if ~exist('nlev')
    % compute the highest possible pyramid
    nlev = floor(log(min(r,c)) / log(2));
end

% recursively build pyramid
pyr = cell(nlev,1);
filter = pyramid_filter;
J = I;
for l = 1:nlev - 1
    % apply low pass filter, and downsample
    I = downsample(J,filter);
    odd = 2*size(I) - size(J);  % for each dimension, check if the upsampled version has to be odd
    % in each level, store difference between image and upsampled low pass version
    pyr{l} = J - upsample(I,odd,filter);
    J = I; % continue with low pass image
end
pyr{nlev} = J; % the coarest level contains the residual low pass image


function [ ywinrange ] = bz_MultiLFPPlot( lfp,varargin )
%bz_MultiLFPPlot(lfp). This function plots multiple lfp channels from a
%buzcode lfp structure with the channels appropriately spaced.
%
%USAGE
%   figure
%       bz_MultiLFPPlot(lfp)
%
%INPUT
%   lfp         a buzcode lfp structure. channels are assumed to be ordered
%               from top to bottom
%   (optional)
%   'channels'  subset/ordering of channels to plot (0-index a la neuroscope)
%               default is to take the channels as ordered in lfp.channels
%   'timewin'   only plot a subwindow of time
%   'spikes'    a buzcode spikes struct to display spikes above the LFP
%   'sortmetric'metric by which to sort the cells in the raster (eg FR)
%   'cellgroups'{Ngroups} cell array of logical arrays of group members
%   'plotcells' list of cell UIDs to plot (not implemented. sad.)
%   'axhandle'  axes handle in which to put the plot
%   'scaleLFP'  multiplicative factor to scale the y range of LFP
%   'scalespikes' size of spike points (default:5)
%   'spikeside' 'top' (default) or 'bottom'
%   'LFPlabels' text labels for each LFP channel (default: channel number)
%   'LFPmidpoints' (default: evenly spaced)
%   'lfpcolor'
%   'lfpwidth'
%
%
%DLevenstein 2017
%% parse the inputs!
channelsValidation = @(x) assert(isnumeric(x) || strcmp(x,'all'),...
    'channels must be numeric or "all"');
spikedefault.spindices = [nan nan];

% parse args
p = inputParser;
addParameter(p,'channels','all',@isnumeric)
addParameter(p,'timewin',[0 Inf],@isnumeric)
addParameter(p,'spikes',[]) %should have iscellinfo function
addParameter(p,'sortmetric',[])
addParameter(p,'cellgroups',{})
addParameter(p,'axhandle',gca)
addParameter(p,'scaleLFP',1,@isnumeric)
addParameter(p,'scalespikes',5,@isnumeric)
addParameter(p,'plotcells',nan,@isnumeric)
addParameter(p,'spikeside','top')
addParameter(p,'LFPlabels',[])
addParameter(p,'LFPmidpoints',[])
addParameter(p,'lfpcolor','k')
addParameter(p,'lfpwidth',0.5)
parse(p,varargin{:})
timewin = p.Results.timewin;
channels = p.Results.channels;
spikes = p.Results.spikes;
sortmetric = p.Results.sortmetric;
cellgroups = p.Results.cellgroups;
plotcells = p.Results.plotcells;
ax = p.Results.axhandle;
scaleLFP = p.Results.scaleLFP;
scalespikes = p.Results.scalespikes;
spikeside = p.Results.spikeside;
LFPlabels = p.Results.LFPlabels;
lfpmidpoints = p.Results.LFPmidpoints;
lfpcolor = p.Results.lfpcolor;
lfpwidth = p.Results.lfpwidth;

if isempty(spikes)
    spikes = spikedefault;
else
    %Implement raster sorting - cell sort
    if min(spikes.spindices(:,2))==0
        spikes.spindices(:,2) = spikes.spindices(:,2)+1;
    end

    if isempty(sortmetric)
        sortmetric = 1:max(spikes.spindices(:,2));
    end
    [~,cellsort] =sort(sortmetric);

    %Goups
    if ~isempty(cellgroups)
        for gg = 1:length(cellgroups)
            groupsort{gg} = intersect(cellsort,find(cellgroups{gg}),'stable');
        end
        cellsort = [groupsort{:}];

        %Cell sort should now map from CellID in spikes.spindices to their
        %desired order in the raster, such that cellsort(IDX) is the
        %UID of the IDXth cell in the raster
    end

    %Sort the raster - this fails if every cell doesn't have a group
    [~,sortraster] = sort(cellsort);
    %sortraster(UID) is the position of cell UID in the raster
%     if isempty(sortraster)
%         sortraster = 1:max(spikes.spindices(:,2));
%     end
    %This accounts for cells that have no group
    sortraster(end+1:max(spikes.spindices(:,2)))=nan;
    %

    if ~isnan(plotcells)
        temp = nan(size(sortraster));
        temp(plotcells) = sortraster(plotcells);
        sortraster = temp;
    end
    spikes.spindices(:,2) = sortraster(spikes.spindices(:,2));
    spikes.spindices(isnan(spikes.spindices(:,2)),:) = [];
end

%% Channel and time stuff
%Time Window
windex = lfp.timestamps>=timewin(1) & lfp.timestamps<=timewin(2);
%Channel to data array index mapping
if strcmp(channels,'all')
    chindex = 1:length(lfp.channels);
    channels = lfp.channels;
else
    [~,~,chindex] = intersect(lfp.channels,channels,'stable');
end

winspikes = spikes.spindices(:,1)>=timewin(1) & spikes.spindices(:,1)<=timewin(2);
%% Calculate and implement spacing between channels

%Space based on median absolute deviation over entire recording - robust to outliers.
randtimes = randsample(size(lfp.data,1),1000);
channelrange = 12.*mad(single(lfp.data(randtimes,chindex)),1);
if isempty(lfpmidpoints)
    lfpmidpoints = -cumsum(channelrange);
end
lfp.plotdata = (bsxfun(@(X,Y) X+Y,single(lfp.data(windex,chindex)).*scaleLFP,lfpmidpoints));

switch spikeside
    case 'top'
        spikeplotrange = [0 -lfpmidpoints(1)];
    case 'bottom'
        spikeplotrange = lfpmidpoints(end)+[1.5 0.5].*lfpmidpoints(1);
end
spikes.plotdata = spikes.spindices(winspikes,:);
%spikes.plotdata(:,2) = (spikes.plotdata(:,2)./max(spikes.spindices(:,2))).*(diff(spikeplotrange));
spikes.plotdata(:,2) = bz_NormToRange(spikes.plotdata(:,2),spikeplotrange);
%% Do the plot
ywinrange = fliplr(lfpmidpoints([1 end])+1.*[1 -1].*max(channelrange));
if ~isnan(spikes.spindices)
    switch spikeside
        case 'top'
            ywinrange(2) = ywinrange(2)+max([spikes.plotdata(:,2);0]);
        case 'bottom'
            ywinrange(1) = min(spikes.plotdata(:,2));
    end

end

plot(ax,lfp.timestamps(windex),lfp.plotdata,'color',lfpcolor,'linewidth',lfpwidth)
hold on
plot(ax,spikes.plotdata(:,1),spikes.plotdata(:,2),'k.','markersize',scalespikes)
xlabel('t (s)')
ylabel('LFP Channel')
set(ax,'Ytick',fliplr(lfpmidpoints))

if isempty(LFPlabels)
    set(ax,'yticklabels',fliplr(channels))
else
    set(ax,'yticklabels',fliplr(LFPlabels))
end
ylim(ywinrange)
xlim(timewin)
box off

end


function cellInfo = StatesBus(varargin)
% STATESBUS returns a cell array containing bus object information
%
% Optional Input: 'false' will suppress a call to Simulink.Bus.cellToObject
%                 when the MATLAB file is executed.
% The order of bus element attributes is as follows:
%   ElementName, Dimensions, DataType, SampleTime, Complexity, SamplingMode, DimensionsMode, Min, Max, DocUnits, Description

suppressObject = false;
if nargin == 1 && islogical(varargin{1}) && varargin{1} == false
    suppressObject = true;
elseif nargin > 1
    error('Invalid input argument(s) encountered');
end

cellInfo = { ...
  { ...
    'StatesBus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'V_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'Omega_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'Euler', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'Accel_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'dOmega_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'V_ned', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'X_ned', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'LLA', [1 3], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Latitude, Longitude, Altitude')}; ...
{'DCM_be', [3 3], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
    } ...
  } ...
}';

if ~suppressObject
    % Create bus objects in the MATLAB base workspace
    Simulink.Bus.cellToObject(cellInfo)
end


classdef ConstantDragCoeffModel < AbstractDragCoefficientModel
    %ConstantDragCoeffModel Summary of this class goes here
    %   Detailed explanation goes here

    properties
        CdA(1,1) double
    end

    properties(Constant)
        enum = DragCoefficientModelEnum.Constant
    end

    methods
        function obj = ConstantDragCoeffModel(CdA)
            obj.CdA = CdA;
        end

        function CdA = getDragCoeff(obj, ut, rVect, vVect, bodyInfo, mass, altitude, pressure, density, vVectECEFMag, totalAoA, aoa, sideslip)
            arguments
                obj(1,1) ConstantDragCoeffModel
                ut(1,1) double
                rVect(3,1) double
                vVect(3,1) double
                bodyInfo(1,1) KSPTOT_BodyInfo
                mass(1,1) double
                altitude(1,1) double
                pressure(1,1) double
                density(1,1) double
                vVectECEFMag(1,1) double
                totalAoA(1,1) double = 0;
                aoa(1,1) double = 0;
                sideslip(1,1) double = 0;
            end

            CdA = obj.CdA;
        end

        function tf = usesTotalAoA(obj)
            tf = false;
        end

        function tf = usesAoaAndSideslip(obj)
            tf = false;
        end

        function useTf = openEditDialog(obj, lvdData)
            out = AppDesignerGUIOutput({false});
            lvd_EditConstDragPropertiesGUI_App(obj, lvdData, out);
            useTf = out.output{1};
        end
    end
end


function svmPlotConfusionMatrix(confusionImage,grouplabels,labelsoff)
% Function to plot a confusion image that was created in
% svmConfusionMatrix.

if notDefined('labelsoff'), labelsoff = 0; end
nConditions = length(grouplabels);

figure;
% Clean up the figure junk matlab generates
set(gcf, 'DockControls', 'off');
set(gcf, 'ToolBar', 'none');

% Plot data and begin tidying it up
imagesc(confusionImage);
axis square; % Correct for stretching
set(gca, 'TickLength', [0 0]); % No ticks

if ~labelsoff
    set(gca, 'YTickLabel', grouplabels);
else
    set(gca, 'YTickLabel',[]);
end

% Create rotated labels on the confusion matrix
% Inspired by a script from Andrew Bliss on MATLAB Central, nice!
% http://www.mathworks.com/matlabcentral/fileexchange/8722-rotate-tick-label
set(gca, 'XTickLabel', []); % Clear original x ticks, replace with text command
if ~labelsoff
    xVals = 1:nConditions;
    yVals = repmat(nConditions + (.1 * nConditions), nConditions, 1);
    text(xVals, yVals, grouplabels, 'HorizontalAlignment', 'right', 'rotation', 45, 'FontWeight', 'bold');
    set(gca, 'FontWeight', 'bold');
end

% Shift over and up a bit, to make room for axis labels and legend
set(gca, 'OuterPosition', [0 .05 1 1]);

xLabelPosition = get(get(gca, 'XLabel'), 'Position');
xLabelPosition(2) = nConditions + (.25 * nConditions); % Set position of x label lower than normal
xlabel('Prediction', 'FontSize', 15, 'FontWeight', 'bold', 'Position', xLabelPosition);
ylabel('Query', 'FontSize', 15, 'FontWeight', 'bold');
colorbar;
%colormap gray
colormap autumn


function [handle, image, region] = vot(format)
% vot Initialize communication and obtain communication structure
%
% This function is used to initialize communication with the toolkit.
%
% The resulting handle is a structure provides several functions for
% further interaction:
% - frame(handle): Get new frame from the sequence.
% - report(handle, region): Report region for current frame and advance.
% - quit(handle): Closes the communication and saves the data.
%
% Input:
% - format (string): Desired region input format.
%
% Output:
% - handle (structure): Updated communication handle structure.
% - image (string): Path to the first image file.
% - region (vector): Initial region encoded as a rectangle or as a polygon.

    if nargin < 1
       format = 'rectangle';
    end

    [handle, image, region] = tracker_initialize(format);
    handle.frame = @tracker_frame;
    handle.report = @tracker_report;
    handle.quit = @tracker_quit;

end

function [handle, image, region] = tracker_initialize(format)
% tracker_initialize Initialize communication structure
%
% This function is used to initialize communication with the toolkit.
%
% Input:
% - format (string): Desired region input format.
%
% Output:
% - handle (structure): Updated communication handle structure.
% - image (string): Path to the first image file.
% - region (vector): Initial region encoded as a rectangle or as a polygon.

    if ~ismember(format,  {'rectangle', 'polygon'})
        error('VOT: Illegal region format.');
    end;

    if ~isempty(getenv('TRAX'))
        % In case TraX can be used, we include the path to the server mex function.
        if ~isempty(getenv('TRAX_MEX'))
            addpath(getenv('TRAX_MEX'));
        end;
        traxserver('setup', format, 'path');

        [image, region] = traxserver('wait');

        handle = struct('trax', true);

        if isempty(image) || isempty(region)
            tracker_quit(handle);
            return;
        end;

        traxserver('status', region);

        return;
    end;

    handle.trax = false;

    % read the image file paths
    fid = fopen('images.txt','r');
    images = textscan(fid, '%s', 'delimiter', '\n');
    fclose(fid);
    handle.images = images{1};

    % read the region
    region = dlmread('region.txt');
    region = region(:);
    handle.format = format;
    handle.index = 2;
    handle.regions = cell(numel(handle.images), 1);

    if numel(region) == 4
        format = 'rectangle';
    elseif numel(region) >= 6 && mod(numel(region), 2) == 0
        format = 'polygon';
    else
        error('VOT: Illegal format of the input region.');
    end;

    switch handle.format
        case 'rectangle'
            if strcmp(format, 'polygon')
                x = region(1:2:end);
                y = region(2:2:end);
                region = [min(x), min(y), max(x) - min(x), max(y) - min(y)];
            end;
        case 'polygon'
            if strcmp(format, 'rectangle')
                x = [region(1), region(1), region(1) + region(3), ...
                     region(1) + region(3), region(1)];
                y = [region(2), region(2) + region(4), region(2) + ...
                     region(4), region(2), region(2)];
                region = zeros(8, 1);
                region(1:2:7) = x;
                region(2:2:8) = y;
            end;
    end;

    handle.position = 2;

    handle.regions{1} = region;
    image = handle.images{1};

end

function [handle, image] = tracker_frame(handle)
% tracker_frame Get new frame from the sequence
%
% This function is used to get new frame from the current sequence
%
% Input:
% - handle (structure): Communication handle structure.
%
% Output:
% - handle (structure): Updated communication handle structure.
% - image (string): Path to image file.

    if ~isstruct(handle)
        error('VOT: Handle should be a structure.');
    end;

    if handle.trax
        [image, region] = traxserver('wait');

        if isempty(image) || ~isempty(region)
            handle.quit(handle);
        end;

        return;
    end;

    if handle.position > numel(handle.images)
        image = [];
        return;
    end;

    image = handle.images{handle.position};

end

function handle = tracker_report(handle, region)
% tracker_report Report region for current frame and advance
%
% This function stores the region for the current frame and advances
% the internal counter to the next frame.
%
% Input:
% - handle (structure): Communication handle structure.
% - region (vector): Predicted region as a rectangle or a polygon.
%
% Output:
% - handle (structure): Updated communication handle structure.

    if isempty(region)
        region = 0;
    end;

    if ~isstruct(handle)
        error('VOT: Handle should be a structure.');
    end;

    if handle.trax
        traxserver('status', region);
        return;
    end;

    if handle.position > numel(handle.images)
        return;
    end;

    handle.regions{handle.position} = region;

    handle.position = handle.position + 1;
end

function tracker_quit(handle)
% tracker_quit Closes the communication and saves the data
%
% This function closes the communication with the toolkit and
% saves the remaining data.
%
% Input:
% - handle (structure): Communication handle structure.
%

    if ~isstruct(handle)
        error('VOT: Handle should be a structure.');
    end;

    if handle.trax
        traxserver('quit');
        return;
    end;

    if iscell(handle.regions)

        fid = fopen('output.txt', 'w');

        for i = 1:numel(handle.regions)
            region = handle.regions{i};

            if numel(region) == 1
                fprintf(fid, '%f\n', region);
            elseif numel(region) == 4
                fprintf(fid, '%f,%f,%f,%f\n', region(1), region(2), region(3), region(4));
            elseif numel(region) >= 6 && mod(numel(region), 2) == 0
                fprintf(fid, '%f,', region(1:end-1));
                fprintf(fid, '%f\n', region(end));
            else
                error('VOT: Illegal result format');
            end;

        end;

        fclose(fid);

        quit();
    else
        error('VOT: Unable to write results.');
    end

end


function H= plot_channel(epo, clab, varargin)
%PLOT_CHANNEL - Plot the classwise averages of one channel of 1D (time OR
% frequency) or 2D data (time x frequency)
%
%Synopsis:
% H= plot_channel(EPO, CLAB, <OPT>)
%
%Input:
% EPO:  Struct of epoched signals, see makeEpochs
% CLAB: Name (or index) of the channel to be plotted.
% OPT:  Struct or property/value list of optional
% properties, used to generate a plot of 1D or 2D data:
%  ----------------------------------
%   (1) 1D channel data plot:
%  .Butterfly    - Butterfly plot. Recommended when CLAB =  '*'. Only
%                  first class is considered for plotting. If ColorOrder is
%                  default, the current colormap is used.
%  .PlotStat     - plot additional statistic: 'std' for standard deviation,
%                  'sem' for standard error of the mean, 'perc' for percentiles
%                  or 'none' for nothing.
%  .Legend       - show Class legend (1, default), or not (0).
%  .LegendPos    - position of the legend, see help of function 'legend'.
%  .XUnit        - unit of x axis, default 'ms'
%  .YUnit        - unit of y axis, default epo.yUnit if this field
%                  exists, 'a.u.' otherwise
%  .YDir         - 'normal' (negative down) or 'reverse' (negative up)
%  .RefCol       -  Color of patch indicating the baseline interval
%  .RefVSize     - (value, default 0.05) controls the Height of the patch
%                  marking the Reference interval.
%  .ColorOrder   - specifies the Colors for drawing the curves of the
%                  different Classes. If not given the ColorOrder
%                  of the current axis is taken. As special gimmick
%                  you can use 'rainbow' as ColorOrder.
%  .LineWidthOrder - (numerical vector) analog to ColorOrder.
%  .LineStyleOrder - (cell array of strings) analog to ColorOrder.
%  .LineSpecOrder - (cell array of cell array) analog to ColorOrder,
%                  giving full control on the appearance of the curves.
%                  (If LineSpecOrder is defined, LineWidthOrder and
%                  LineStyleOrder are ignored, but ColorOrder is not.)
%  .XGrid, ...   - many axis properties can be used in the usual
%                  way
%  .YLim         - Define the y limits. If empty (default) an automatic
%                  selection according to 'YLimPolicy' is performed.
%  .YLimPolicy   - policy of how to select the YLim (only if 'YLim' is
%                  empty resp unspecified): 'auto' uses the
%                  usual mechanism of Matlab; 'tightest' selects YLim as the
%                  exact data range; 'tight' (default) takes the data range,
%                  adds a little border and selects 'nice' limit values.
%  .Title        - title of the plot to be displayed above the axis.
%                  If OPT.title equals 1, the channel label is used.
%  .Title*       - with * in {'Color', 'FontWeight', 'FontSize'}
%                  selects the appearance of the title.
%  .XZeroLine    - draw an axis along the x-axis at y=0
%  .YZeroLine    - draw an axis along the y-axis at x=0
%  .ZeroLine*    - with * in {'Color','Style'} selects the
%                  drawing style of the axes at x=0/y=0
%  .AxisTitle    - (string) title to be displayed *within* the axis.
%  .AxisTitle*   - with * in {'Color', 'HorizontalAlignment',
%                  'VerticalAlignment', 'FontWeight', 'FontSize'}
%                  selects the appearance of the subplot titles.
%  ----------------------------------
%   (2) 2D channel data plot:
%  .XUnit  - unit of x axis, default 'ms'
%  .YUnit  - unit of y axis, default epo.unit if this field
%                     exists, 'Hz' otherwise
%  .YDir     - 'normal' (low FreqLimuencies at bottom) or 'reverse'
%  .FreqLim     - A vector giving lowest and highest Frequency. If not specified,
%              [1 size(epo.x,2)] is taken.
%  .PlotRef  - if 1 plot Reference interval (default 0)
%  .RefYPos     - y position of Reference line
%  .RefWhisker - length of whiskers (vertical lines)
%  .Ref*     - with * in {'LineStyle', 'LineWidth', 'Color'}
%              selects the appearance of the Reference interval.
%  .Colormap - specifies the colormap for depicting amplitude. Give either
%              a string or a x by 3 Color matrix (default 'jet')
%  .CLim   - Define the Color (=amplitude) limits. If empty (default),
%              limits correspond to the data limits.
%  .CLimPolicy - if 'sym', Color limits are symmetric (so that 0
%              corresponds to the middle of the colormap) (default
%              'normal')
%  .XGrid, ... -  many axis properties can be used in the usual
%                 way
%  .GridOverPatches - if 1 plot grid (default 0)
%  .Title   - title of the plot to be displayed above the axis.
%             If OPT.title equals 1, the channel label is used.
%  .Title*  - with * in {'Color', 'FontWeight', 'FontSize'}
%             selects the appearance of the title.
%  .YTitle  - if set, the title is displayed within the axis, with its
%             Y position corresponding to Ytitle (default [])
%  .ZeroLine  - draw an axis along the y-axis at x=0
%  .ZeroLine*  - with * in {'Color','Style'} selects the
%                drawing style of the axes at x=0/y=0

%Output:
% H - Handle to several graphical objects.
%
% See also plotutil_channel1D, plotutil_channel2D

if nargin==0,
  H= opt_catProps(plotutil_channel1D, plotutil_channel2D);
  return
end

if nargin<2,
  clab= 1;
end

if util_getDataDimension(epo)==1
  if ~isempty(varargin)
    opt1D= plotutil_channel1D;
    opt= opt_structToProplist(opt_substruct(opt_proplistToStruct(varargin{:}),opt1D(:,1)));
  else
    opt=varargin;
  end
  H= plotutil_channel1D(epo, clab, opt{:});
else
  if ~isempty(varargin)
    opt2D= plotutil_channel2D;
    opt=opt_structToProplist( opt_substruct(opt_proplistToStruct(varargin{:}),opt2D(:,1)));
  else
    opt=varargin;
  end
  H= plotutil_channel2D(epo, clab, opt{:});
end


function G = gsp_update_coordinates(G, coords)
%GSP_UPDATE_COORDINATES Updates the coordinates of a graph structure
%   Usage: G = gsp_update_coordinates(G, coords);
%
%   Input parameters
%         G      : Graph
%         coords : New coordinates
%
%   Output parameters
%         G      : Output graph
%
%   Update the coordinates of a graph structure
%
%   See also: gsp_compute_coordinates

% Authors : Dion O. E. Tzamarias
% Date    : 20/11/2015

G.coords = coords;
G = rmfield(G,'plotting');
G = gsp_graph_default_plotting_parameters(G);

end


function wedge_monte_carlo_test ( )

%*****************************************************************************80
%
%% WEDGE_MONTE_CARLO_TEST tests the WEDGE_MONTE_CARLO library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 August 2014
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'WEDGE_MONTE_CARLO_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the WEDGE_MONTE_CARLO library.\n' );

  wedge_monte_carlo_test01 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'WEDGE_MONTE_CARLO_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function marginal = marginal_nodes(engine, nodes, t, add_ev)
% MARGINAL_NODES Compute the marginal on the specified query nodes (loopy_unrolled_dbn)
% marginal = marginal_nodes(engine, nodes, t)
%
% 't' specifies the time slice of the earliest node in 'nodes'.
% 'nodes' must occur in some clique.
%
% Example:
% Consider a DBN with 2 nodes per slice.
% Then t=2, nodes=[1 3] refers to node 1 in slice 2 and node 1 in slice 3,
% i.e., nodes 3 and 5 in the unrolled network,

if nargin < 3, t = 1; end
if nargin < 4, add_ev = 0; end

marginal = marginal_nodes(engine.unrolled_engine, nodes + (t-1)*engine.ss, add_ev);


% AXCOPY - Copy a Matlab figure axis and its graphic objects to a new pop-up window
%            using the left mouse button.
%
% Usage:  >> axcopy
%         >> axcopy(fig)
%         >> axcopy('noticks')
%         >> axcopy(fig, command)
%
% Notes:
%   1) Clicking the left mouse button on a Matlab figure axis copies the graphic objects
%      in the axis to a new (pop-up) figure window.
%   2) Option 'noticks' does not make x and y tickloabelmodes 'auto' in the pop-up.
%   2) The command option is an optional string that is evaluated in the new window
%      when it pops up. This allows the user to customize the pop-up display.
%   3) Deleting the pop-up window containing the copied axis leaves the selected axis
%      as the current graphic axis (gca).

% Authors: Tzyy-Ping Jung & Scott Makeig, SCCN/INC/UCSD, La Jolla, 2000

% Copyright (C) 2000 Tzyy-Ping Jung & Scott Makeig, SCCN/INC/UCSD, 3-16-00
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

% requires copyaxes.m
% 4-2-00 added 'noticks' -sm
% 01-25-02 reformated help & license -ad
% 02-16-02 debuged exist('fig') -> exist('fig') == 1 -ad
% 02-16-02 added the ignore parent size option -ad
% 03-11-02 remove size option and added command option -ad

function axcopy(fig, command)

if (exist('fig') == 1) && strcmp(fig,'noticks')
   noticks = 1;
   if nargin> 1
     shift
   else
     fig = [];
   end
end
if ~(exist('fig') ==1) || isempty(fig) || fig == 0
   fig = gcf;
end

if ~strcmpi(get(fig, 'type'), 'axes')
    %hndl= findobj('parent',fig,'type','axes');
    %--
    childs = get(fig,'Children');
    hndl   = childs(find(strcmpi(get(childs,'Type'),'axes')));
else
    hndl=fig;
end
offidx=[];
if exist('command') ~= 1
    comstr = 'copyaxis';
else
   command_dbl = double(command);
   comstr = double(['copyaxis(''' char(command_dbl) ''')']);
end
for a=1:length(hndl)                    % make all axes visible
    %allobjs = findobj('parent',hndl(a));
    %--
    allobjs = get(hndl(a),'Children');
    for index = 1:length(allobjs)
        if isempty(get(allobjs(index), 'ButtonDownFcn'))
            set(allobjs(index), 'ButtonDownFcn', char(comstr));
        end
    end
end
if ~strcmpi(get(fig, 'type'), 'axes')
    figure(fig);
else
    figure(get(fig, 'parent'));
end
if exist('command') ~= 1
    set(hndl(a),'ButtonDownFcn','copyaxis');
else
    % set(hndl,'ButtonDownFcn',['copyaxis(''' command ''')']);
    comstr = double(['copyaxis(''' char(command_dbl) ''')']);
    set(hndl,'ButtonDownFcn',char(comstr));
end;
%set(hndl,'ButtonDownFcn','copyaxis');
%if ~exist('noticks')
  %axis on
  %set(gca,'xticklabelmode','auto')
  %set(gca,'yticklabelmode','auto')
%end


% ty_axes stores all information necessary to generate a nice looking
% ty-Plot for possible multiple timeseries datasets. It provides methods
% to generate this plot if a target axes is given.
%
% It expects the following interface:
% ty_axes(ts_list, yaxis_string)
% with ts_list being a cell array of multiple time series to display and
% yaxis_string being the label placed at the y axis.
classdef ty_axes
   properties
    % cell array which holds multiple timeseries, arrangement does not matter
    ts_list
    % stores the y axis label shared by all timeseries
    yaxis_string
   end
   methods
    % constructor
    function obj = ty_axes(ts_list, yaxis_string)
      obj.ts_list = ts_list;
      obj.yaxis_string = yaxis_string;
    end
    % plots all timeseries objects and setups the axes properties right
    function plot_all(obj, ax, tStart, tEnd)
      % setup general properties
      grid(ax, 'on');
      hold(ax, 'on');
      xlabel(ax, 'Time in s');
      ylabel(ax, obj.yaxis_string{1});
      % initialize plot handles which store the resulting plots to match
      % with the legends later
      ph = [];
      legend_bool = [];
      ph_idx = 1;
      % iterate via all timeseries
      for i = 1:1:numel(obj.ts_list)
        if(nargin==4)
          % if time points are given, specify them
          ph = [ph, obj.plot_ts(obj.ts_list{i}, ax, tStart, tEnd)];
          legend_bool(ph_idx) = 1;
        else
          % otherwise plot complete timeseries by suppression of time points
          ph = [ph, obj.plot_ts(obj.ts_list{i}, ax)];
          legend_bool(ph_idx) = 1;
        end
        ph_idx = ph_idx + 1;
      end
      % tidy up
      if(numel(obj.ts_list) > 1)
        % only display legend if more than one signal is present
        legend(ax, ph(logical(legend_bool)), 'Location', 'best');
      end
      box(ax, 'on');
      hold(ax, 'off');
    end
   % helper function which takes care of time management
   function ph = plot_ts(obj, ts, ax, tStart, tEnd)
    if(nargin~=5)
      % if not all aguments are given, assume that the timeseries is plotted completly
      tStart = ts.Time(1);
      tEnd = ts.Time(end);
    end
    try
      [idxStart, idxEnd] = find_ts_idx(ts, tStart, tEnd);
      % plot data and configure axes
      ph = stairs(ax, ts.Time(idxStart:idxEnd), ts.Data(idxStart:idxEnd), 'DisplayName', strrep(ts.Name,'_',' '));
    catch
      warning(['Error during plotting of ' ts.Name]);
    end
   end
 end
end


function alpha = p10_alpha ( )

%*****************************************************************************80
%
%% P10_ALPHA returns ALPHA for problem 10.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 July 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real ALPHA, the value of ALPHA.
%
  alpha = 0.0;

  return
end


% Make list of used BNT parameters in file
%
% This function parses input file or script for entries like `<pattern>name = value`,
% and prints out the list of names. An example of such entry is: p.imageFormat = 'png'.
% It can be used to quickly check what BNT parameters are used in the script.
%
%  USAGE
%   helpers.extractParametersList(filename, pattern)
%   filename    - Path to the file to parse or script name. If script name is provided,
%                 then Matlab's function which is used to find out the corresponding
%                 file name.
%   pattern     - Begin of BNT parameters pattern. If omitted, then 'p.' is used.
%
function extractParametersList(filename, pattern)
    if nargin < 2
        pattern = 'p.';
    end
    existCode = exist(filename, 'file');
    if existCode == 0 || existCode == 2
        filename = which(filename);
    end
    parameters = containers.Map('KeyType', 'char', 'ValueType', 'char');

    fid = data.safefopen(filename, 'r');

    while ~feof(fid)
        str = fgetl(fid);
        patternPos = strfind(str, pattern);
        if ~isempty(patternPos)
            originalPos = patternPos;
            for i = 1:length(originalPos)
                patternPos = originalPos(i);

                wholeWord = regexp(str(patternPos-1:patternPos-1), '\w', 'once');
                if ~isempty(wholeWord)
                    continue;
                end
                commentsPos = strfind(str, '%');
                if ~isempty(commentsPos) && commentsPos(1) < patternPos
                    % this string is commented out, skip it
                    continue;
                end
                parameterName = regexp(str(patternPos+2:end), '\w*', 'match');
                parameterName = sprintf('%s%s', pattern, parameterName{1});

                parameters(parameterName) = parameterName;
            end
        end
    end

    cellfun(@(x) fprintf('%%  %s\n', x), values(parameters));
end


function loadInputFileCallback(grfBlockHandle)
% This function runs an input file and loads the contents into the block
% masks.

    %% Run the input file selected in the global reference frame
    % Find input filename
    mask = Simulink.Mask.get(grfBlockHandle);
    InputFile = mask.getParameter('InputFile');
    inputFilePath = InputFile.Value;

    %% Set class parameters in block mask
    % Get all simulink blocks
    blocks = find_system(bdroot,'Type','Block');

    % Loop through blocks, writing each to the input file
    for i=1:length(blocks)
        % Variable names and values of a block
        names = get_param(blocks{i},'MaskNames');
        blockHandle = getSimulinkBlockHandle(blocks{i});

        % Check if the block is from the WEC-Sim library
        if any(contains(names,{'simu','waves'})) % Global reference frame
            type = 0;
        elseif any(contains(names,{'body'})) % flexible or rigid body
            type = 1;
        elseif any(contains(names,{'pto'})) % pto
            type = 2;
        elseif any(contains(names,{'constraint'})) % constraint
            type = 3;
        elseif any(contains(names,{'mooring'})) && any(contains(names,{'stiffness'})) % mooring matrix
            type = 4;
        elseif any(contains(names,{'mooring'})) && any(contains(names,{'moorDynLines'})) % moorDyn
            type = 5;
        elseif any(contains(names,{'cable'}))
            type = 6;
        end

        writeBlocksFromInput(blockHandle,type,inputFilePath);
        % write blocks again to account for read only params that are now open
        if type==1 || type==0
            writeBlocksFromInput(blockHandle,type,inputFilePath);
        end
    end
end


function [lfp] = bz_GetLFP(varargin)
% bz_GetLFP - Get local field potentials.
%
%  Load local field potentials from disk. No longer dependent on
%  FMAT/SetCurrentSession.
%
%  USAGE
%
%    [lfp] = bz_GetLFP(channels,<options>)
%
%  INPUTS
%
%    channels(required) -must be first input, numeric
%                        list of channels to load (use keyword 'all' for all)
%                        channID is 0-indexing, a la neuroscope
%  Name-value paired inputs:
%    'basepath'           - folder in which .lfp file will be found (default
%                           is pwd)
%                           folder should follow buzcode standard:
%                           whateverPath/baseName
%                           and contain file baseName.lfp
%    'basename'           -base file name to load
%    'intervals'          -list of time intervals [0 10; 20 30] to read from
%                           the LFP file (default is [0 inf])
%    'downsample'         -factor to downsample the LFP (i.e. 'downsample',5
%                           will load a 1250Hz .lfp file at 250Hz)
%    'noPrompts'          -logical (default) to supress any user prompts
%
%  OUTPUT
%
%    lfp             struct of lfp data. Can be a single struct or an array
%                    of structs for different intervals.  lfp(1), lfp(2),
%                    etc for intervals(1,:), intervals(2,:), etc
%    .data           [Nt x Nd] matrix of the LFP data
%    .timestamps     [Nt x 1] vector of timestamps to match LFP data
%    .interval       [1 x 2] vector of start/stop times of LFP interval
%    .channels       [Nd X 1] vector of channel ID's
%    .samplingRate   LFP sampling rate [default = 1250]
%    .duration       duration, in seconds, of LFP interval
%
%
%  EXAMPLES
%
%    % channel ID 5 (= # 6), from 0 to 120 seconds
%    lfp = bz_GetLFP(5,'restrict',[0 120]);
%    % same, plus from 240.2 to 265.23 seconds
%    lfp = bz_GetLFP(5,'restrict',[0 120;240.2 265.23]);
%    % multiple channels
%    lfp = bz_GetLFP([1 2 3 4 10 17],'restrict',[0 120]);
%    % channel # 3 (= ID 2), from 0 to 120 seconds
%    lfp = bz_GetLFP(3,'restrict',[0 120],'select','number');

% Copyright (C) 2004-2011 by Michaël Zugaro
% editied by David Tingley, 2017
%
% NOTES
% -'select' option has been removed, it allowed switching between 0 and 1
%   indexing.  This should no longer be necessary with .lfp.mat structs
%
% TODO
% add saveMat input
% expand channel selection options (i.e. region or spikegroup)
% add forcereload
%% Parse the inputs!

channelsValidation = @(x) isnumeric(x) || strcmp(x,'all');

% parse args
p = inputParser;
addRequired(p,'channels',channelsValidation)
addParameter(p,'basename','',@isstr)
addParameter(p,'intervals',[],@isnumeric)
addParameter(p,'restrict',[],@isnumeric)
addParameter(p,'basepath',pwd,@isstr);
addParameter(p,'downsample',1,@isnumeric);
addParameter(p,'saveMat',false,@islogical);
addParameter(p,'forceReload',false,@islogical);
addParameter(p,'noPrompts',false,@islogical);

parse(p,varargin{:})
basename = p.Results.basename;
channels = p.Results.channels;
downsamplefactor = p.Results.downsample;
basepath = p.Results.basepath;
noPrompts = p.Results.noPrompts;

% doing this so you can use either 'intervals' or 'restrict' as parameters to do the same thing
intervals = p.Results.intervals;
restrict = p.Results.restrict;
if isempty(intervals) && isempty(restrict) % both empty
    intervals = [0 Inf];
elseif isempty(intervals) && ~isempty(restrict) % intervals empty, restrict isn't
    intervals = restrict;
end

%% let's check that there is an appropriate LFP file
if isempty(basename)
   %disp('No basename given, so we look for a *lfp/*eeg file...')
   d = dir([basepath filesep '*lfp']);
   if length(d) > 1 % we assume one .lfp file or this should break
       error('there is more than one .lfp file in this directory?');
   elseif length(d) == 0
       d = dir([basepath filesep '*eeg']);
       if isempty(d)
           error('could not find an lfp/eeg file..')
       end
   end
   lfp.Filename = d.name;
   basename = strsplit(lfp.Filename,'.');
   if length(basename) > 2
       base = [];
       for i=1:length(basename)-1
          base = [base basename{i} '.'];
       end
       basename = base(1:end-1);  % this is an fugly hack to make things work with Kenji's naming system...
   else
       basename = basename{1};
   end

else
   d = dir([basepath filesep basename '.lfp']);
   if length(d) > 1 % we assume one .lfp file or this should break
       error('there is more than one .lfp file in this directory?');
   elseif length(d) == 0
       d = dir([basepath filesep basename '.eeg']);
       if isempty(d)
           error('could not find an lfp/eeg file..')
       end
   end
   lfp.Filename = d.name;
end

%% things we can parse from sessionInfo or xml file

sessionInfo = bz_getSessionInfo(basepath, 'noPrompts', noPrompts);

try
    samplingRate = sessionInfo.lfpSampleRate;
catch
    samplingRate = sessionInfo.rates.lfp; % old ugliness we need to get rid of
end
samplingRateLFP = samplingRate./downsamplefactor;

if mod(samplingRateLFP,1)~=0
    error('samplingRate/downsamplefactor must be an integer')
end
%% Channel load options
%Right now this assumes that all means channels 0:nunchannels-1 (neuroscope
%indexing), we could also add options for this to be select region or spike
%group from the xml...
if strcmp(channels,'all')
    channels = sessionInfo.channels;
else
    %Put in something here to collapse into X-Y for consecutive channels...
    display(['Loading Channels ',num2str(channels),' (0-indexing, a la Neuroscope)'])
end

%% get the data
disp('loading LFP file...')
nIntervals = size(intervals,1);
% returns lfp/bz format
for i = 1:nIntervals
    lfp(i).duration = (intervals(i,2)-intervals(i,1));
    lfp(i).interval = [intervals(i,1) intervals(i,2)];

    % Load data and put into struct
    % we assume 0-indexing like neuroscope, but bz_LoadBinary uses 1-indexing to
    % load....
    lfp(i).data = bz_LoadBinary([basepath filesep lfp.Filename],...
        'duration',double(lfp(i).duration),...
                  'frequency',samplingRate,'nchannels',sessionInfo.nChannels,...
                  'start',double(lfp(i).interval(1)),'channels',channels+1,...
                  'downsample',downsamplefactor);
    lfp(i).timestamps = [lfp(i).interval(1):(1/samplingRateLFP):...
                        (lfp(i).interval(1)+(length(lfp(i).data)-1)/...
                        samplingRateLFP)]';
    lfp(i).channels = channels;
    lfp(i).samplingRate = samplingRateLFP;
    % check if duration is inf, and reset to actual duration...
    if lfp(i).interval(2) == inf
        lfp(i).interval(2) = length(lfp(i).timestamps)/lfp(i).samplingRate;
        lfp(i).duration = (lfp(i).interval(i,2)-lfp(i).interval(i,1));
    end

    if isfield(sessionInfo,'region') && isfield(sessionInfo,'channels')
        [~,~,regionidx] = intersect(lfp(i).channels,sessionInfo.channels,'stable');
        lfp(i).region = sessionInfo.region(regionidx); % match region order to channel order..
    end
end


function [ compressIndex_new ] = anal_reindex_last(compressDir,  reIndexFile )
%ANAL_REINDEX_LAST Summary of this function goes here
%   Detailed explanation goes here

    fileExt = '*.txt';
    compress_files = dir(fullfile(compressDir,fileExt));
    compressIndex = [];
    for i = 0:length(compress_files)-1

        fileCnt = num2str(i);
        fileName = [compressDir, fileCnt, '.txt'];

        file_t = fopen(fileName);
        point_ID = fscanf(file_t, '%d');
        fclose(file_t);

        compressIndex = union(compressIndex, point_ID);

    end

    reIndex = dlmread(reIndexFile);

    isInIndex = ismember(reIndex(:,2), compressIndex);
    isSaved = find(isInIndex==1);
    old_index = reIndex(:,1);
    compressIndex_new = old_index(isSaved);

end


%% Visualization with MATLAB Builder for .NET
% Copyright (c) 2009, The MathWorks, Inc.
%
% This demo / example shows how to implement an C# application that uses
% MATLAB built components as a visualization engine.
% The main window can be resized, and there is a movable slitter between
% the textbox and the picturebox.
% After the functions are called for the first time, visualization
% should be fast enough to enable a real-time experience when
% resizing the figure.

% There is a compiled exe and related DLLs in the folder bin\release

%%
% 1. Compile the dll with
mcc  -B 'dotnet:NETSquare,NETSquareclass,2.0,Private,local' makesquare.m ...
    makebitmap.m makefigure.m

% 2. Add generated DLL and MWArray DLL to project references

% 3. Compile and run the project


function ok=checkScans(vw,scanList)
%
% Check that all scans in scanList have the same slices, numFrames, cropSizes
for iscan = 2:length(scanList)
    if find(sliceList(vw,scanList(1)) ~= sliceList(vw,scanList(iscan)))
        mrErrorDlg('Can not average these scans; they have different slices.');
    end
    if (numFrames(vw,scanList(1)) ~= numFrames(vw,scanList(iscan)))
        mrErrorDlg('Can not average these scans; they have different numFrames.');
    end
    if find(viewGet(vw,'slice dims', scanList(1)) ~= viewGet(vw,'slice dims', scanList(iscan)))
        mrErrorDlg('Can not average these scans; they have different cropSizes.');
    end
end

ok = true;

return;


function [n, npw, ts, wave] = plx_waves_v(filename, channel, unit)
% plx_waves_v(filename, channel, unit): read waveform data from a .plx or .pl2 file
%
% [n, npw, ts, wave] = plx_waves_v(filename, channel, unit)
%
% INPUT:
%   filename - if empty string, will use File Open dialog
%   channel - 1-based channel number or channel name
%   unit  - unit number (0- unsorted, 1-4 units a-d)
%
% OUTPUT:
%   n - number of waveforms
%   npw - number of points in each waveform
%   ts - array of timestamps (in seconds)
%   wave - array of waveforms [npw, n] converted to mV

n = 0;
npw = 32;
ts = -1;
wave = -1;

if nargin ~= 3
    error 'expected 3 input arguments';
end

[ filename, isPl2 ] = internalPL2ResolveFilenamePlx( filename );
if isPl2 == 1
    w = PL2Waves( filename, channel, unit );
    if numel(w.Ts) > 0
        n = numel(w.Ts);
        ts = w.Ts;
        npw = w.NumPointsWave;
        wave = w.Waves;
    else
		% we need to return number of points per wave the way it is done by mexPlex
		if channel > -1
			npw = 0;
			pl2 = PL2GetFileIndex(filename);
			% find the first channel with data and get its number of points per wave
			for i=1:numel(pl2.SpikeChannels)
				if pl2.SpikeChannels{i}.SamplesPerSpike > 0
					npw = pl2.SpikeChannels{i}.SamplesPerSpike;
					break;
				end
			end
		end
    end
    return;
end

channelNumber = plx_resolve_channel(filename, channel);
if channelNumber == -1
    %fprintf('\n plx_waves_v: no header for the specified spike channel.\n');
    return
end

[n, npw, ts, wave] = mexPlex(19, filename, channelNumber, unit);

end


function FillBetween(Xdata,YLower,YUpper,AreaColor,Alpha)

if size(Xdata) == size(YLower)
    fill([vertcat(Xdata,Xdata(end:-1:1))],[vertcat(YLower,YUpper(end:-1:1))],AreaColor,'FaceAlpha',Alpha);
else
    warning('MATLAB:InvlaidArgumentSize','The size of the input is not consistent');
end


function varargout=wrsamp(varargin)
%
% wrsamp(tm,data,fileName,Fs,gain,format)
%
%    Wrapper to WFDB WRSAMP:
%         http://www.physionet.org/physiotools/wag/wrsamp-1.htm
%
% Writes data into a WFDB compatible *.dat and *.hea files. The files will be saved at
% the current directory (if the record is in the current directory) or, if a using
% a PhysioNet web record , a subdirectory in the current directory, with
% the relative path determined by recordName. You can use RDSAMP to
% verify that the write was completed successfully (see example below). For
% detailed information on the parameters described below, please see:
% http://www.physionet.org/physiotools/wag/header-5.htm
%
%
%
% LIMITATIONS:
%        The input variables 'tm' and 'data' should be integer values.
%		 Currently the MATLAB/Octave wrappers do take into account Baseline values.
%        Signals that have baseline values will not be converted properly to physical units.
%        You will have to edit the generated header files manually to include baseline variables and update the checksums.
%
%
% Required Parameters:
%
% tm
%       Nx1 vector of integers representing sample index.
%
% data
%       NxM vector of integers (M channels) that will be written to file.
%
% fileName
%
%       String specifying the file name. WRSAMP will write the signal file in
%       the current directory as "fileName.dat", and create a header file in the
%       current directory "fileName.hea" for the specified record.
%
% Optional Parameters:
%
% Fs
%       A 1x1 double specifying the sampling frequency (in samples per second per
%       signal) for the output signals (default: 250). It affects the output header
%       file only. This option has no effect on the output signal file, which
%       contains one sample per signal for each line of input.
%
% gain
%       A 1x1 or Mx1 vector of doubles specifying gain value in A/D units per millivolt
%       for the output signals (default: 200).  This option the output header file only.
%       This option has no effect on the output signal file.
%
% format
%       String specifying the signal's default format (default: "16"). For
%       information on the available WFDB formats please see:
%       http://www.physionet.org/physiotools/wag/signal-5.htm
%
%%Example-
%%Read signal in raw units
%[signal,Fs,tm]=rdsamp('challenge/2013/set-a/a01',[],[],[],4);
%[siginfo,Fs]=wfdbdesc('challenge/2013/set-a/a01');
%%Write a copy to file
%wrsamp(tm,signal(:,1),'a01Copy',Fs(1),200,siginfo(1).Format)
%%Check that the signals match
%[signalCopy,Fs,tm]=rdsamp('a01Copy',[],[],[],4);
%err=sum(signalCopy ~= signal(:,1))
%
%
% Written by Ikaro Silva, 2013
% Last Modified: April 10, 2015
% Since 0.0.1
%
%
% See also rdsamp, wfdbdesc, mat2wfdb
%

%endOfHelp

javaWfdbExec=getWfdbClass('wrsamp');

%Set default pararamter values
inputs={'tm','data','fileName','Fs','gain','format'};
Fs=[];
gain=[];
format=[];
for n=1:nargin
    if(~isempty(varargin{n}))
        eval([inputs{n} '=varargin{n};']);
    end
end

wfdb_argument={'-c','-z','-o',fileName};

if(~isempty(Fs))
    wfdb_argument{end+1}='-F';
    wfdb_argument{end+1}=num2str(Fs);
end

if(~isempty(gain))
    wfdb_argument{end+1}='-G';
    wfdb_argument{end+1}=num2str(gain);
end

if(~isempty(format))
    wfdb_argument{end+1}='-O';
    wfdb_argument{end+1}=format;
end

del=repmat([' '],size(tm));
data=[num2str(tm) del num2str(data)];
javaWfdbExec.setArguments(wfdb_argument);
javaWfdbExec.execWithStandardInput(cellstr(data));


function f = transpose( f )
% .'   SEPARABLEAPPROX transpose.
%    F.' is the non-conjugate transpose of a F.
%
% See also CTRANSPOSE.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Empty check:
if ( isempty( f ) )
    return
end

% Swap columns and rows.
temp = f.cols;
f.cols = f.rows;
f.rows = temp;

% Adjust the domain
f.domain = [f.domain(3:4) f.domain(1:2)];

end


function ctranspose(x)
%CTRANSPOSE is not defined for tensors.
%
%   See also TENSOR/PERMUTE.
%
%MATLAB Tensor Toolbox.
%Copyright 2015, Sandia Corporation.

% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2015) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt

error('Transpose on tensor is not defined');


function engine = dv_unrolled_dbn_inf_engine(bnet, T, varargin)
% JTREE_UNROLLED_DBN_INF_ENGINE Unroll the DBN for T time-slices and apply jtree to the resulting static net
% engine = jtree_unrolled_dbn_inf_engine(bnet, T, ...)
%
% The following optional arguments can be specified in the form of name/value pairs:
% [default value in brackets]
%
% useC      - 1 means use jtree_C_inf_engine instead of jtree_inf_engine [0]
% constrained - 1 means we constrain ourselves to eliminate slice t before t+1 [1]
%
% e.g., engine = jtree_unrolled_inf_engine(bnet, 'useC', 1);

% set default params
N = length(bnet.intra);
useC = 0;
constrained = 1;

if nargin >= 3
  args = varargin;
  nargs = length(args);
  if isstr(args{1})
    for i=1:2:nargs
      switch args{i},
       case 'useC',   useC = args{i+1};
       case 'constrained',  constrained = args{i+1};
       otherwise,
	error(['invalid argument name ' args{i}]);
      end
    end
  else
    error(['invalid argument name ' args{1}]);
  end
end

bnet2 = hodbn_to_bnet(bnet, T);
ss = length(bnet.intra);
engine.ss = ss;

% If constrained_order = 1 we constrain ourselves to eliminate slice t before t+1.
% This prevents cliques containing nodes from far-apart time-slices.
if constrained
  stages = num2cell(unroll_set(1:ss, ss, T), 1);
else
  stages = { 1:length(bnet2.dag) };
end
if useC
  %jengine = jtree_C_inf_engine(bnet2, 'stages', stages);
  %function is not implemented
  assert(0)
else
  jengine = stab_cond_gauss_inf_engine(bnet2);
end

engine.unrolled_engine = jengine;
% we don't inherit from jtree_inf_engine, because that would only store bnet2,
% and we would lose access to the DBN-specific fields like intra/inter

engine.nslices = T;
engine = class(engine, 'stable_ho_inf_engine', inf_engine(bnet));


function results = CCR3_enterFunc(gamma, inputPath)
     %% ======================================================================
    %%STEP 1: load the data
    fprintf('start load the data...\n');
    load(inputPath);
%     TrainLabel(TrainLabel==0) = -1;

    if strcmp(class(TrainData),'cell')
        for x = 1:size(TrainData,2)
            TrainData{1,x} = TrainData{1,x}';
            tem = TrainLabel{1,x};
            TrainLabel{1,x}(tem==0) = -1;
        end
        traindata = TrainData;
        trainlabel = TrainLabel;
    else
        TrainData = TrainData';
        TrainLabel(TrainLabel==0) = -1;
        traindata{1,1} = TrainData;
        trainlabel{1,1} = TrainLabel;
    end
    if strcmp(class(TestData),'cell')
        tem = TestLabel{1,1};
        TestLabel{1,1}(tem==0) = -1;
        testdata = TestData;
        testlabel = TestLabel;
    else
        TestLabel(TestLabel==0) = -1;
        testdata{1,1} = TestData;
        testlabel{1,1} = TestLabel;
    end

     %% ======================================================================
    %%STEP 2: train the model
    results=CCR(traindata, testdata, trainlabel, testlabel, gamma);
end


function cs = load(fname,varargin)
% import crystal symmetry from phl or cif files
%
% if cif file not found and input name is a valid COD entry, this function
% tries to download the file from
% <http://www.crystallography.net/cif/ http://www.crystallography.net/cif/>
%
% Syntax
%   cs = crystalSymmetry.load('5000035.cif') % load from cif file
%   cs = crystalSymmetry.load('copper.phl') % load from phl file
%   cs = crystalSymmetry.load(5000035) % lookup online
%
% See also
% crystalSymmetry/crystalSymmetry
%

[~, ~, ext] = fileparts(char(fname));

if strcmpi(ext,'.phl')
  cs = loadPHL(fname,varargin{:});
else
  cs = loadCIF(fname,varargin{:});
end


% [INPUT]
% f = A valid figure instance.
% t = A string representing the figure title.
%
% [OUTPUT]
% t = The handler of the figure title.

function t = figure_title(varargin)

    persistent ip;

    if (isempty(ip))
        ip = inputParser();
		ip.addRequired('f',@(x)validateattributes(x,{'matlab.ui.Figure'},{'scalar'}));
        ip.addRequired('s',@(x)validateattributes(x,{'char'},{'nonempty' 'size' [1 NaN]}));
    end

    ip.parse(varargin{:});

    ipr = ip.Results;
    f = ipr.f;
    s = ipr.s;

    nargoutchk(0,1);

    if (nargout == 0)
        figure_title_internal(f,s);
    else
        t = figure_title_internal(f,s);
    end

end

function t = figure_title_internal(f,s)

    f_font_size = get(f,'DefaultAxesFontSize') + 4;
    f_units = get(f,'Units');

    if (~strcmp(f_units,'pixels'))
        set(f,'Units','pixels');
        f_position = get(f,'Position');
        set(f,'Units',f_units);
    else
        f_position = get(f,'Position');
    end

    adjustment = ((f_font_size - 4) * 6.35) / f_position(4);
    title = NaN;
    y_max = 0;
    y_min = 1;

    handles = findobj(f,'Type','axes');
    handles_len = length(handles);
    handles_position = zeros(handles_len,4);

    for i = 1:handles_len
        h_current = handles(i);

        f_position = get(h_current,'Position');
        handles_position(i,:) = f_position;

        if (~strcmp(get(h_current,'Tag'),'FigureTitle'))
            f_y = f_position(2);
            f_height = f_position(4);

            if (f_y < y_min)
                y_min = f_y - (adjustment / 15);
            end

            if ((f_height + f_y) > y_max)
                y_max = f_height + f_y + (adjustment / 10);
            end
        else
            title = h_current;
        end
    end

    if (y_max > 0.92)
        scale = (0.92 - y_min) / (y_max - y_min);

        for i = 1:handles_len
            f_position = handles_position(i,:);
            f_position(2) = ((f_position(2) - y_min) * scale) + y_min;
            f_position(4) = (f_position(4) * scale) - ((1 - scale) * (adjustment / 15));

            set(handles(i),'Position',f_position);
        end
    end

    next_plot = get(f,'NextPlot');
    set(f,'NextPlot','add');

    if (ishghandle(title))
        delete(title);
    end

    axes('Position',[0 1 1 1],'Tag','FigureTitle','Visible','off');
    t_internal = text(0.5000,-0.0157,s,'FontSize',f_font_size,'HorizontalAlignment','center');

    set(f,'NextPlot',next_plot);

    axes(gca());

    if (nargout == 1)
        t = t_internal;
    end

end


function self = seisan(varargin)
    % READ_CATALOG.SEISAN Read a Seisan event database - consisting of
    % S-files. Gathers a list of S-files matching the request and then uses
    % the read_sfile function, to return a structure for each S-file.

    debug.printfunctionstack('>')

    % Process input arguments
    % Process input arguments
    p = inputParser;
    p.addParameter('dbpath', '', @isstr);
    p.addParameter('startTime', -Inf);
    p.addParameter('endTime', Inf);
    p.addParameter('minimumMagnitude', -Inf, @isnumeric);
    p.addParameter('maximumMagnitude', Inf, @isnumeric);
    p.addParameter('minimumLatitude', -90., @isnumeric);
    p.addParameter('maximumLatitude', 90., @isnumeric);
    p.addParameter('minimumLongitude', -180., @isnumeric);
    p.addParameter('maximumLongitude', 180., @isnumeric);
    p.addParameter('minimumDepth', -12, @isnumeric);
    p.addParameter('maximumDepth', 6400., @isnumeric);
    p.addParameter('minimumRadius', 0., @isnumeric);
    p.addParameter('maximumRadius', deg2km(180.0), @isnumeric);
    p.addParameter('boxcoordinates', [], @isnumeric);    %[minLat, maxLat, minLon, maxLon]   % use NaN as a wildcard
    p.addParameter('radialcoordinates', [], @isnumeric); % [Lat, Lon, MaxRadius, MinRadius]   % MinRadius is optional
    p.addParameter('addarrivals', false, @islogical);

    % CUSTOM PARAMETERS
    p.addParameter('subclass', '*', @ischar);

    p.parse(varargin{:});
    fields = fieldnames(p.Results);
    for i=1:length(fields)
        field=fields{i};
        % val = eval(sprintf('p.Results.%s;',field));
        val = p.Results.(field);
        eval(sprintf('%s = val;',field));
    end

    self.request.dbpath = dbpath;
    self.request.startTime = startTime;
    self.request.endTime = endTime;

%     % SCAFFOLD: might have deleted something here. These 2 lines might not
%     % be correct
%     self.request.minimumMagnitude = minimumMagnitude;
%     p.addParameter('minimumMagnitude', [], @isnumeric);
%
%     p.addParameter('maximumMagnitude', [], @isnumeric);
%     p.addParameter('minimumLatitude', [], @isnumeric);
%     p.addParameter('maximumLatitude', [], @isnumeric);
%     p.addParameter('minimumLongitude', [], @isnumeric);
%     p.addParameter('maximumLongitude', [], @isnumeric);
%     p.addParameter('minimumDepth', [], @isnumeric);
%     p.addParameter('maximumDepth', [], @isnumeric);
%     p.addParameter('minimumRadius', [], @isnumeric);
%     p.addParameter('maximumRadius', [], @isnumeric);
%     p.addParameter('boxcoordinates', @isnumeric);    %[minLat, maxLat, minLon, maxLon]   % use NaN as a wildcard
%     p.addParameter('radialcoordinates', @isnumeric); % [Lat, Lon, MaxRadius, MinRadius]   % MinRadius is optional
%     p.addParameter('addarrivals', false, @islogical);

    if numel(boxcoordinates)==4
        minimumLatitude = boxcoordinates(1);
        maximumLatitude = boxcoordinates(2);
        minimumLongitude = boxcoordinates(3);
        maximumLongitude = boxcoordinates(4);
    end

    if numel(radialcoordinates)==4
        centerLatitude = radialcoordinates(1);
        centerLongitude = radialcoordinates(2);
        maximumRadius = radialcoordinates(3);
        %minimumRadius = radialcoordinates(4);
    end

    % Check start & end times
    snum = Catalog.read_catalog.ensure_dateformat(startTime);
    enum = Catalog.read_catalog.ensure_dateformat(endTime);

    if ~exist(dbpath, 'dir')
        fprintf('Directory %s not found\n',dbpath);
        self = struct;
        return;
    end

    % get dir list of matching sfilesSfile.list_sfiles
    sfiles = Sfile.list_sfiles(dbpath, snum, enum);

    % loop over sfiles
    for i=1:length(sfiles)
        % read
        fprintf('Processing %s\n',fullfile(sfiles(i).dir, sfiles(i).name));
        thiss = Sfile(fileread(fullfile(sfiles(i).dir, sfiles(i).name)));
        try
            s(i)=thiss;
        catch
            s(i)
            thiss
            error('Wrong number of fields?')
        end

        % add to catalog
        dnum(i)  = s(i).otime;
        etype{i} = s(i).subclass;
        lat(i) = s(i).latitude;
        lon(i) = s(i).longitude;
        depth(i) = s(i).depth;

        % SCAFFOLD
        mag(i) = NaN;
        try
            sfile_mags = [s(i).magnitude.value];
            if ~isempty(sfile_mags)
                disp('**************** ********************')
                mag(i) = max(sfile_mags);
            end
        end

        % SCAFFOLD also use durations (bbdur) and ampengfft info
        % Compute a magnitude from amp & eng, but need to know where
        % stations are. I can save these as MA and ME, to distinguish from
        % Ml, Ms, Mb, Mw if those exist
    end
    magtype = {};

    % save request
    fields = fieldnames(p.Results);
    for i=1:length(fields)
        field=fields{i};
        eval(sprintf('request.%s = eval(field);',field));
    end

    % create Catalog object
    self = Catalog(dnum', lon', lat', depth', mag', magtype', etype', 'request', request);
    request.startTime = snum;
    request.endTime = enum;
    self.request = request;
    debug.printfunctionstack('<')
end


%% function to get rcnn detected part boxes
%% Written by Ning Zhang

function detect_boxes = get_rcnn_detections(config)
try
  load('caches/rcnn_detect_boxes.mat');
catch
  try
    load('caches/rcnn_part_models.mat');
  catch
    disp('Train part detectors in rcnn and save it in the caches');
    exit(-1);
  end
  detect_boxes = test_rcnn_parts(part_models, config);
  save('caches/rcnn_detect_boxes.mat', 'detect_boxes');
end
end


function varargout = drawBox(box, varargin)
%DRAWBOX Draw a box defined by coordinate extents
%
%   drawBox(BOX)
%   Draws a box defined by its extent: BOX = [XMIN XMAX YMIN YMAX].
%
%   drawBox(..., NAME, VALUE)
%   Specifies drawing parameters using parameter name and value. See plot
%   function for syntax.
%
%   drawBox(AX, ...)
%   Specifies the handle of the axis to draw on.
%
%   Example
%     % define some points, compute their box, display everything
%     points = [10 30; 20 50; 20 20; 30 10;40 30;50 20];
%     box = pointSetBounds(points);
%     figure; hold on;
%     drawPoint(points, 's');
%     drawBox(box);
%     axis([0 60 0 60]);
%
%   See Also:
%   drawOrientedBox, drawRect
%
%   ---------
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 10/12/2003.
%

%   HISTORY
%   2010-02-22 creation
%   2011-04-01 add support for drawing option, fix bug for several boxes
%   2011-10-11 add management of axes handle

% extract handle of axis to draw on
if isAxisHandle(box)
    ax = box;
    box = varargin{1};
    varargin(1) = [];
else
    ax = gca;
end

% default values
xmin = box(:,1);
xmax = box(:,2);
ymin = box(:,3);
ymax = box(:,4);

nBoxes = size(box, 1);
r = zeros(nBoxes, 1);

% iterate on boxes
for i = 1:nBoxes
    % exract min and max values
    tx(1) = xmin(i);
    ty(1) = ymin(i);
    tx(2) = xmax(i);
    ty(2) = ymin(i);
    tx(3) = xmax(i);
    ty(3) = ymax(i);
    tx(4) = xmin(i);
    ty(4) = ymax(i);
    tx(5) = xmin(i);
    ty(5) = ymin(i);

    % display polygon
    r(i) = plot(ax, tx, ty, varargin{:});
end

% format output
if nargout > 0
    varargout = {r};
end