function [tstop,res] = testProblem(optObj,solvers)
%TESTPROBLEM  Test an OPTI Problem against all available solvers
%
%   [times,results] = testProblem(optObj) runs the supplied OPTI problem
%   against all available solvers for the given problem type.
%
%   [times,results] = testProblems(optObj,solvers) runs only the selected
%   solvers across the supplied problem.

%   Copyright (C) 2011 Jonathan Currie (IPL)

%Setup default arguments
if(~exist('solvers','var') || isempty(solvers))
    solvers = optiSolver(['all_' optObj.prob.type]);
end
if(~iscell(solvers))
    solvers = {solvers};
end

%Remove troublesome solvers
ind = strcmpi(solvers,'lipsol');
if(any(ind))
    solvers(ind) = [];
end

%Setup problem generation function (for warm up)
switch(lower(optObj.prob.type))
    case 'lp'
        testSet = @lp_prob;
    case 'milp'
        testSet = @milp_prob;
    case 'bilp'
        testSet = @bilp_prob;
    case 'qp'
        testSet = @qp_prob;
    case 'qcqp'
        testSet = @qcqp_prob;
    case 'sdp'
        testSet = @sdp_prob;
    case 'miqp'
        testSet = @miqp_prob;
    case 'nlp'
        testSet = @nlp_prob;
        if(isempty(optObj.prob.x0))
            error('Please include x0 in optiprob when using this function on NLPs');
        end
    case 'minlp'
        testSet = @minlp_prob;
        if(isempty(optObj.prob.x0))
            error('Please include x0 in optiprob when using this function on MINLPs');
        end
    otherwise
        error('Unknown problem type: %s',optObj.prob.type);
end

%Remove troublesome solvers
if(strcmpi(optObj.prob.type,'lp'))
    ind = strcmpi(solvers,'SEDUMI'); solvers(ind) = []; %no good with neq = nvar
end

%Setup no runs
len = length(solvers);
%confirm solver exists!
for i = 1:len
    rub = optiSolver(solvers{i}); %#ok<NASGU>
end

%Setup wait bar
h = waitbar(0,['Solver: ' upper(solvers{1})],'name','OPTI Problem Test','CreateCancelBtn','setappdata(gcbf,''canceling'',1)');

%Preallocate
tstop = zeros(len,1);
res = struct('sol',{cell(len,1)},'fval',zeros(len,1),'ok',zeros(len,1),'msg',{cell(len,1)});

%Clear display warnings etc
opts = optiset(optObj.prob,'display','off','warnings','off');

try
    for i = 1:len
        %Check Cancel
        if getappdata(h,'canceling')
            break;
        end
        %Assign the new solver
        solver = solvers{i};
        opts = optiset(opts,'solver',solver);
        %Initialize with two solves of problem 1
        prob = testSet(1);
        Opt = opti(prob,opts);
        solve(Opt); solve(Opt);
        %Now run our problem
        Opt = opti(getProb(optObj),opts);
        [x,sval,~,stat] = solve(Opt);
        res.sol{i} = x;
        res.fval(i) = sval;
        res.ok(i) = checkSol(Opt);
        res.msg{i} = stat.Status;
        tstop(i) = stat.Time;
        %Update Waitbar
        waitbar(i/len,h,['Solver: ' upper(solvers{min(len,i+1)})]);
    end
catch ME
    delete(h);
    rethrow(ME);
end

delete(h);

%Draw Table
fprintf('\nTest Problem [%s] Result\n',Opt.prob.type);
fprintf('--------------------------------------------------\n');
fprintf('  Solver    Status        Fval         Time\n');
for i = 1:len
    fprintf('%8s    %4s    %+12.4f     %1.4fs\n',solvers{i},status(res.ok(i)),res.fval(i),tstop(i));
end
fprintf('--------------------------------------------------\n');

function msg = status(ok)

if(ok)
    msg = 'OK';
else
    msg = 'FAIL';
end


classdef SubcellsMesher_Boundary < SubcellsMesher

    properties (GetAccess = protected, SetAccess = private)
        nCellNodes
    end

    methods (Access = protected, Abstract)

        computeFacetsConnectivities(obj)

    end

    methods (Access = protected)

        function computeCoordinates(obj)
            obj.coord_iso = obj.cutPoints.ISO;
            obj.coord_global = obj.cutPoints.GLOBAL;
        end

        function computeConnectivities(obj)
            obj.computeFacetsConnectivities();
        end

        function computeLevelSet(obj)
            obj.levelSet = obj.boundary_levelSet;
        end

    end

    methods

        function nCellNodes = get.nCellNodes(obj)
            nCellNodes = size(obj.posNodes,1);
        end

    end
end


function printFluxVector(model, fluxData, nonZeroFlag, excFlag, sortCol, fileName, headerRow, formulaFlag, gprFlag)
% Prints a flux vector with reaction labels
%
% USAGE:
%    printFluxVector(model, fluxData, nonZeroFlag, excFlag, sortCol, fileName, headerRow, formulaFlag, gprFlag)
%
% INPUTS:
%    model:          COBRA model structure
%    fluxData:       Data matrix/vector (for example, solution.v)
%
% OPTIONAL INPUTS:
%    nonZeroFlag:    Only print nonzero rows (Default = false)
%    excFlag:        Only print exchange fluxes (Default = false)
%    sortCol:        Column used for sorting (-1, none; 0, labels; >0, data
%                    columns;) (Default = -1)
%    fileName:       Name of output file (Default = [])
%    headerRow:      Header (Default = [])
%    formulaFlag:    Print reaction formulas (Default = false)
%    gprFlag:        Print reaction GPR (Default = false)
%

% .. Authors:
%       - Markus Herrgard, Ronan Fleming

if isempty(fluxData)
    return
end
if nargin < 3
    nonZeroFlag = false;
end
if nargin < 4
    excFlag = false;
end
if nargin < 5
    sortCol = -1;
end
if nargin < 6
    fileName = [];
end
if nargin < 7
    headerRow = [];
end
if nargin < 8
    formulaFlag = false;
end
if nargin < 9
    gprFlag = false;
end

if excFlag
    bool = findExcRxns(model, true, false);
else
    bool = true(size(model.S,2),1);
    labels = model.rxns;
end

if length(nonZeroFlag)==size(model.S,2)
    bool = bool & nonZeroFlag;
    nonZeroFlag = 1;
else
    if nonZeroFlag
        bool = bool & fluxData(:,1)~=0;
    end
end

% Add reaction formulas
if formulaFlag
    if nonZeroFlag
        labels = [model.rxns,model.rxns];
        %only generate the formulas for the nonzero entries
        formulas = printRxnFormula(model, labels(bool), false, false);
        labels(bool,2) = formulas;
    else
        formulas = printRxnFormula(model, labels, false, false);
        labels = [labels, formulas];
    end
end

% Add GPR
if gprFlag
    if nonZeroFlag
        %only generate the gprs for the nonzero entries
        labels(bool,end+1) = model.grRules(bool);
    else
        labels = [labels, model.grRules];
    end
end

%only print the nonzeros
if nonZeroFlag
    labels = labels(bool,:);
    fluxData = fluxData(bool,:);
end

labels(:,2) = pad(labels(:,2));

%print the labeled data
printLabeledData(labels, fluxData, 0, sortCol, fileName, headerRow)


% END - last index to memmapdata array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008

% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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.

function s = end(a, k, n);

    s = size(a, k);


function lorenz_cluster_test ( )

%*****************************************************************************80
%
%% LORENZ_CLUSTER_TEST tests the LORENZ_CLUSTER library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 October 2013
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LORENZ_CLUSTER_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the LORENZ_CLUSTER library.\n' );

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

  return
end


function complex_mat = getComplexesFromGeneRules(grRules)
%getComplexesFromGeneRules  Extract enzyme complex info from model grRules.
%
% getComplexesFromGeneRules uses the logic in grRules to identify which
% genes are treated as belonging to an enzyme complex, and returns a binary
% matrix describing all identified complexes and their gene constituents.
%
% USAGE:
%
%   complex_mat = getComplexesFromGeneRules(grRules);
%
% INPUT:
%
%   grRules      grRules from a genome-scale metabolic model structure.
%
% OUTPUT:
%
%   complex_mat  A (GxC) binary matrix, where G is the number of genes
%                appearing in grRules, and C is the number of complexes
%                idenditied. Each column of the matrix represents a unique
%                enzyme complex, with 1s indicating which genes belong to
%                the complex. Although the complexes are unique, they can
%                be subsets of one another.
%


function value = p22_r8 ( action, name, value )

%*****************************************************************************80
%
%% P22_R8 sets or gets R8 parameters for problem 22.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string ACTION,
%    'D' sets the parameter to its default value;
%    'G' gets a parameter.
%    'R' sets the parameter to a random value.
%    'S' sets a parameter,
%
%    Input, string NAME, the name of the parameter.
%    'C' is the coefficient.
%    'R' is the radius of the sphere.
%
%    Input/output, real VALUE.
%    * If ACTION = 'S', then VALUE is an input quantity, and is the
%      new value to be assigned to NAME.
%    * If ACTION = 'D' or 'G' or 'R', then VALUE is an output quantity,
%      and is the current value of NAME.
%
  persistent c;
  persistent r;

  if ( action == 'D' | action == 'd' )

    if ( name == 'C' | name == 'c' | name == '*' )
      c = 1.0;
    end

    if ( name == 'R' | name == 'r' | name == '*' )
      r = 1.0;
     end

  elseif ( action == 'G' | action == 'g' )

    if ( name == 'C' | name == 'c' )
      value = c;
    elseif ( name == 'R' | name == 'r' )
      value = r;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P22_R8 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P22_R8 - Fatal error!' );
    end

  elseif ( action == 'R' | action == 'r' )

    if ( name == 'C' | name == 'c' )
      c = rand ( 1, 1 );
      value = c;
    elseif ( name == 'R' | name == 'r' )
      r = rand ( 1, 1 );
      value = r;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P22_R8 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P22_R8 - Fatal error!' );
    end

  elseif ( action == 'S' | action == 's' )

    if ( name == 'C' | name == 'c' )
      c = value;
    elseif ( name == 'R' | name == 'r' )
      r = value;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P22_R8 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P22_R8 - Fatal error!' );
    end

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'P22_R8 - Fatal error!\n' );
    fprintf ( 1, '  Unrecognized action = "%s".\n', action );
    error ( 'P22_R8 - Fatal error!' );

  end

  return
end


% Copyright 2018 Marc René Schädler
%
% This file is part of the mobile hearing aid prototype project
% The the mobile hearing aid prototype project 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.
%
% The mobile hearing aid prototype project 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 the mobile hearing aid prototype project. If not, see http://www.gnu.org/licenses/.

function writegaintable(filename, gt_data)
  fid = fopen(filename,'w');
  gt_min = -10;
  gt_step = 1;
  if fid > 0
    fprintf(fid,'gtdata = [');
    [num_rows, num_cols] = size(gt_data);
    for i=1:num_rows
      fprintf(fid,'[');
      for j=1:num_cols
        fprintf(fid,'%.2f',gt_data(i,j));
        if j < num_cols
          fprintf(fid,' ');
        else
          fprintf(fid,']');
        end
      end
      if i < num_rows
        fprintf(fid,';');
      else
        fprintf(fid,']');
      end
    end
    fprintf(fid,'\n');
    fprintf(fid,'gtmin = [');
    for i=1:num_rows
      fprintf(fid,'%.2f',gt_min);
      if i < num_rows
        fprintf(fid,' ');
      else
        fprintf(fid,']');
      end
    end
    fprintf(fid,'\n');
    fprintf(fid,'gtstep = [');
    for i=1:num_rows
      fprintf(fid,'%.2f',gt_step);
      if i < num_rows
        fprintf(fid,' ');
      else
        fprintf(fid,']');
      end
    end
    fprintf(fid,'\n');
    fclose(fid);
  end
end


function out = cplexoptimget (options, name, default)
%%
% Purpose
% Retrieve optimization options values.
%
% Syntax
%    out = cplexoptimget(options,'param')
%    out = cplexoptimget(options,'param',default)
%
% Description
% val = cplexoptimget(options,'param') returns the value of the specified
% option in the optimization options structure options.
%
% val = cplexoptimget(options,'param',default) returns default if the
% specified option is not defined in the optimization options structure
% options.
%
%  See also cplexoptimset
%

% ---------------------------------------------------------------------------
% File: cplexoptimget.m
% ---------------------------------------------------------------------------
% Licensed Materials - Property of IBM
% 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55
% Copyright IBM Corporation 2008, 2010. All Rights Reserved.
%
% US Government Users Restricted Rights - Use, duplication or
% disclosure restricted by GSA ADP Schedule Contract with
% IBM Corp.
% ---------------------------------------------------------------------------


function a = imag(a)
%IMAG         imaginary part of hessians
%
%   c = imag(a)
%

% written  04/04/04     S.M. Rump
% modified 04/06/05     S.M. Rump  rounding unchanged
%

  a.x = imag(a.x);
  a.dx = imag(a.dx);
  a.hx = imag(a.hx);


function varargout = mapn(array, start, varargin)
% [OUTPUT] = MAPN(ARRAY, START, FUNC, OPTIONS)
%   This is MAP(ARRAY, FUNC', OPTIONS) where FUNC' takes the ordinal
%   position of the array element we are mapping across instead of the
%   actual value.  Positions start counting at start.
%

  [funclist, varargin] = select(varargin, @islambda);

  if nargin < 2, start = 1; end
  if nargin == 0
    error('MapN:Arguments', 'Array argument to MapN is required.');
  end

  if isempty(funclist)
    varargout{1} = start:(numel(array) - 1 + start);
    return;
  end

  if numel(funclist) > 1
    error('MapN:Arguments', 'Too many functions to mapn.');
  end

  func = funclist{1};
  function varargout = mapNFunc(index, varargin)
    [varargout{1:(max([nargout, 1]))}] = func(index);
  end

  [varargout{1:(max([nargout, 1]))}] = map(array, indexer(@mapNFunc, start, 1, 1), varargin{:});
end


%MAKEFIGS_TRACKEXTRACT  Makes a sample figure for TRACKEXTRACT.

load tpjaos
use tpjaos

region=[-66 -41 52 67];
[lat,lon,ssh,mss,atd]=trackextract(lat,lon,ssh,mss,atd,region);

figure
axis(region)
topoplot continents
plot(lon,lat,'linewidth',2)
latratio(58.5)


function moveWaitForDTWhenInterrupted( t_Kuka ,...
     Pos, VEL,joints_indices,max_torque,min_torque, w)
 %% Perform line motion the motion is interruptile through a collision with the environment
 % After a collision the robot waits for a double touch on the end-effector
 % along the Z axes, upon which the robot returns to its motion again.

 % Copyright: Mohammad SAFEEA, 11th-April-2018

 while true
    [ res ] = movePTP_ConditionalTorque_LineEEF( t_Kuka ,...
     Pos, VEL,joints_indices,max_torque,min_torque);
    if(res==1)
        disp('Motion completed successfully');
        break;
    elseif(res==0)
        disp('Motion interrupted');
        detectDoubleTouch(t_Kuka,w);
        pause(0.5);
    elseif(res==-1)
        disp('Error while performing the motion');
        break;
    end
end
end

function x=detectDoubleTouch(t_Kuka,w)
%% Detect double touch at the EEF along the Z axes
buffer=zeros(50,1);
daSum=0;
while true
    [ f ] = getEEF_Force( t_Kuka );
    normForce=(f{3}*f{3})^0.5;
    buffer(1)=[];
    buffer=[buffer;normForce];
    pause(0.04);
    temp=buffer>(5+w);
    for i=2:50
        if (temp(i)-temp(i-1))==1
            daSum=daSum+1;
        end
    end
    if daSum==2
        x=1;
        return;
    end
end
end


%DEMOHISTOGRAMRGB  One-line description here, please.
%
%   output = demoHistogramRGB(input)
%
%   Example
%   demoHistogramRGB
%
%   See also
%

% ------
% Author: David Legland
% e-mail: david.legland@inra.fr
% Created: 2018-10-08,    using Matlab 9.4.0.813654 (R2018a)
% Copyright 2018 INRA - Cepia Software Platform.

%% Read Color image

img = Image.read('peppers.png');
figure; show(img);
print(gcf, 'peppers-show.png', '-dpng');

%% Compute histogram

figure; histogram(img);
print(gcf, 'peppers-histogram.png', '-dpng');

%% Compute line profile

lineProfile(img, [150 50], [150 300]);
print(gcf, 'peppers-lineProfile.png', '-dpng');

% overlay line profile on original image
img(149:151, 50:300, :) = 255;
write(img, 'peppers-lineOverlay.png');


% --------------------------------------------------------
% MDP Tracking
% Copyright (c) 2015 CVGL Stanford
% Licensed under The MIT License [see LICENSE for details]
% Written by Yu Xiang
% --------------------------------------------------------
%
% generate training data
function [dres_train, dres_det, labels] = generate_training_data(seq_idx, dres_image, opt)

% is_show = 0;

seq_name = opt.mot2d_train_seqs{seq_idx};
seq_set = 'train';

% read detections
filename = fullfile(opt.mot, opt.mot2d, seq_set, seq_name, 'det', 'det.txt');
dres_det = read_mot2dres(filename);

% read ground truth
filename = fullfile(opt.mot, opt.mot2d, seq_set, seq_name, 'gt', 'gt.txt');
dres_gt = read_mot2dres(filename);
dres_gt = fix_groundtruth(seq_name, dres_gt);
y_gt = dres_gt.y + dres_gt.h;

% collect true positives and false alarms from detections
num = numel(dres_det.fr);
labels = zeros(num, 1);
overlaps = zeros(num, 1);
for i = 1:num
    fr = dres_det.fr(i);
    index = find(dres_gt.fr == fr);
    if isempty(index) == 0
        overlap = calc_overlap(dres_det, i, dres_gt, index);
        o = max(overlap);
        if o < opt.overlap_neg
            labels(i) = -1;
        elseif o > opt.overlap_pos
            labels(i) = 1;
        else
            labels(i) = 0;
        end
        overlaps(i) = o;
    else
        overlaps(i) = 0;
        labels(i) = -1;
    end
end

% build the training sequences
ids = unique(dres_gt.id);
dres_train = [];
count = 0;
for i = 1:numel(ids)
    index = find(dres_gt.id == ids(i));
    dres = sub(dres_gt, index);

    % check if the target is occluded or not
    num = numel(dres.fr);
    dres.occluded = zeros(num, 1);
    dres.covered = zeros(num, 1);
    dres.overlap = zeros(num, 1);
    dres.r = zeros(num, 1);
    dres.area_inside = zeros(num, 1);
    y = dres.y + dres.h;
    for j = 1:num
        fr = dres.fr(j);
        index = find(dres_gt.fr == fr & dres_gt.id ~= ids(i));

        if isempty(index) == 0
            [~, ov] = calc_overlap(dres, j, dres_gt, index);
            ov(y(j) > y_gt(index)) = 0;
            dres.covered(j) = max(ov);
        end

        if dres.covered(j) > opt.overlap_occ
            dres.occluded(j) = 1;
        end

        % overlap with detections
        index = find(dres_det.fr == fr);
        if isempty(index) == 0
            overlap = calc_overlap(dres, j, dres_det, index);
            [o, ind] = max(overlap);
            dres.overlap(j) = o;
            dres.r(j) = dres_det.r(index(ind));

            % area inside image
            [~, overlap] = calc_overlap(dres_det, index(ind), dres_image, fr);
            dres.area_inside(j) = overlap;
        end
    end

    % start with bounding overlap > opt.overlap_pos and non-occluded box
    index = find(dres.overlap > opt.overlap_pos & dres.covered == 0 & dres.area_inside > opt.exit_threshold);
    if isempty(index) == 0
        index_start = index(1);
        count = count + 1;
        dres_train{count} = sub(dres, index_start:num);
    end

    % show gt
%      if is_show
%         for j = 1:numel(dres_train{i}.fr)
%             fr = dres_train{i}.fr(j);
%             filename = fullfile(opt.mot, opt.mot2d, seq_set, seq_name, 'img1', sprintf('%06d.jpg', fr));
%             disp(filename);
%             I = imread(filename);
%             figure(1);
%             show_dres(fr, I, 'GT', dres_train{i});
%             pause;
%         end
%     end
end

% handle occlusion by a pole in PETS09-S2L1
if strcmp(seq_name, 'PETS09-S2L1') == 1
    dres_train([9, 15, 19]) = [];
    pole = [409.0000, 102.0000, 39.0000, 294.0000];
    dres_pole.x = pole(1);
    dres_pole.y = pole(2);
    dres_pole.w = pole(3);
    dres_pole.h = pole(4);
    for i = 1:numel(dres_train)
        dres = dres_train{i};
        [~, ~, overlap] = calc_overlap(dres_pole, 1, dres, 1:numel(dres.fr));
        dres.covered = max([dres.covered, overlap'], [], 2);
        dres.occluded(dres.covered > opt.overlap_occ) = 1;
        dres_train{i} = dres;
    end
end

fprintf('%s: %d positive sequences\n', seq_name, numel(dres_train));


function model = addMissingReactions(SampledModel, completeModel)
% Verify the consistency between the sampled model and the
% complete reference model by checking that all reactions from complete
% model are in the sampled model
%
% USAGE:
%
%    model = addMissingReactions(SampledModel, completeModel)
%
% INPUTS:
%    SampledModel:     Sampled model
%    completeModel:    The complete reference model
%
% OUTPUTS:
%    model:            Consistent sampled model wrt the complete model
%
% .. Authors:
%       - Nathan E. Lewis, May 2010-May 2011
%       - Anne Richelle, May 2017

model = completeModel;

% find all nonmissing reactions and make a new points matrix
NonMissingRxns = completeModel.rxns(ismember(completeModel.rxns,SampledModel.rxns));
model.points = zeros(length(model.rxns),length(SampledModel.points(1,:)));

% Move all sampled model points to the new model, and leave missing reaction points as zeros
SM_Ind = findRxnIDs(SampledModel,NonMissingRxns);
CM_Ind = findRxnIDs(model,NonMissingRxns);
model.points(CM_Ind,:) = SampledModel.points(SM_Ind,:);
end


% File conversion
% Reading images from CASIA database and converting to 'jpg' format
% Author: Qingbao Guo
% Gj?vik University College, GUC, Norway

clear all;

path='CASIA Iris Image Database (version 1.0)\00'; %please update to your directory
subpath='00'; %please update to your directory
for i=1:108

            if i>=10
                path='CASIA Iris Image Database (version 1.0)\0';
                subpath='0';
            end

            if i>=100
                 path='CASIA Iris Image Database (version 1.0)\';
                 subpath='';
            end

    for j=1:2

        if j==1
        for k=1:3

        filesrcpath1 = strcat(path,num2str(i),'\',num2str(j),'\',subpath,num2str(i),'_',num2str(j),'_',num2str(k),'.bmp');
        filedespath1 = strcat(path,num2str(i),'_',num2str(j),'_',num2str(k),'.jpg');
        im = imread(filesrcpath1,'bmp');
        data(:,7*(i-1)+k) = reshape(im,1,280*320);
        imwrite(im,filedespath1,'jpg');
        end
        end

        if j==2
        for h=1:4
        filesrcpath2 = strcat(path,num2str(i),'\',num2str(j),'\',subpath,num2str(i),'_',num2str(j),'_',num2str(h),'.bmp');
        filedespath2 = strcat(path,num2str(i),'_',num2str(j),'_',num2str(h),'.jpg');
        im = imread(filesrcpath2,'bmp');
        data(:,7*i-4+h) = reshape(im,1,280*320);
        imwrite(im,filedespath2,'jpg');
        end
        end

    end
end
save data.mat data;


function st_to_mm_test ( )

%*****************************************************************************80
%
%% ST_TO_MM_TEST tests the ST_TO_MM library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 November 2008
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'ST_TO_MM_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the ST_TO_MM library.\n' );

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

  return
end


%% QUAD_SCRIPT is a script to call QUAD_FUN.
%
%  Discussion:
%
%    The BATCH command runs scripts, not functions.  So we have to write
%    this short script if we want to work with BATCH!
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 March 2010
%
%  Author:
%
%    John Burkardt
%
  n = 100000;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'QUAD_SCRIPT\n' );
  fprintf ( 1, '  Estimate integral using %d points\n', n );

  value = quad_fun ( n );


 function y = fatrix2_def_forw(M, x)
%function y = fatrix2_def_forw(M, x)
%| basic default 'forw' function: M * x
y = M * x;


function [errorCode] = pco_sdk_example_live_add(looptime,exposure_time,triggermode)
% grab and display images in a loop
%
%   [errorCode] = pco_sdk_example_live_add(looptime,triggermode)
%
% * Input parameters :
%    looptime                time the loop is running (default=10 seconds)
%    exposure_time           camera exposure time (default=10ms)
%    triggermode             camera trigger mode (default=AUTO)
%
% * Output parameters :
%    errorCode               ErrorCode returned from pco.camera SDK-functions
%
%grab images from a recording pco.camera
%using functions PCO_AddBufferEx and PCO_WaitforBuffer
%display the grabbed images
%
%
%break loop either after waittime or nr_of_images images are done
%

glvar=struct('do_libunload',1,'do_close',0,'camera_open',0,'out_ptr',[]);

if(~exist('looptime','var'))
 looptime = 10;
end

if(~exist('exposure_time','var'))
 exposure_time = 10;
end

if(~exist('triggermode','var'))
 triggermode = 0;
end

%reduce_display_size=1: display only top-left corner 800x600Pixel
reduce_display_size=1;

pco_camera_load_defines();
subfunc=pco_camera_subfunction();

[errorCode,glvar]=pco_camera_open_close(glvar);
pco_errdisp('pco_camera_setup',errorCode);
disp(['camera_open should be 1 is ',int2str(glvar.camera_open)]);
if(errorCode~=PCO_NOERROR)
 commandwindow;
 return;
end

out_ptr=glvar.out_ptr;

try

act_recstate = uint16(10);
[errorCode,~,act_recstate] = calllib('PCO_CAM_SDK', 'PCO_GetRecordingState',out_ptr,act_recstate);
if(errorCode)
  pco_errdisp('PCO_GetRecordingState',errorCode);
else
 disp(['actual recording state is ',int2str(act_recstate)]);
end

%stop camera
subfunc.fh_stop_camera(out_ptr);

cam_desc=libstruct('PCO_Description');
set(cam_desc,'wSize',cam_desc.structsize);
[errorCode,~,cam_desc] = calllib('PCO_CAM_SDK', 'PCO_GetCameraDescription', out_ptr,cam_desc);
cam_desc
pco_errdisp('PCO_GetCameraDescription',errorCode);

bitpix=uint16(cam_desc.wDynResDESC);

%set bitalignment LSB
bitalign=uint16(BIT_ALIGNMENT_LSB);
errorCode = calllib('PCO_CAM_SDK', 'PCO_SetBitAlignment', out_ptr,bitalign);
pco_errdisp('PCO_SetBitAlignment',errorCode);

errorCode = calllib('PCO_CAM_SDK', 'PCO_SetRecorderSubmode',out_ptr,RECORDER_SUBMODE_RINGBUFFER);
pco_errdisp('PCO_SetRecorderSubmode',errorCode);

%enable ASCII and binary timestamp
if(bitand(cam_desc.dwGeneralCapsDESC1,GENERALCAPS1_NO_TIMESTAMP)==0)
 subfunc.fh_enable_timestamp(out_ptr,TIMESTAMP_MODE_BINARYANDASCII);
end

%enable MetaData if available
if(bitand(cam_desc.dwGeneralCapsDESC1,GENERALCAPS1_METADATA))
 subfunc.fh_set_metadata_mode(out_ptr,0);
end

	%{
	%Pixel Binning
	%binning funktioniert nur wenn gleichzeitig ROI gesetzt wird.
	h_binning=1; %1,2,4
	v_binning=1; %1,2,4

	v_ROI_reduction = 4
	[errorCode] = calllib('PCO_CAM_SDK', 'PCO_SetBinning', out_ptr,h_binning,v_binning); %2,4, etc.
	%ROI selection
	[errorCode] = calllib('PCO_CAM_SDK', 'PCO_SetROI', out_ptr,1,1,5120/h_binning/4,5120/v_binning/v_ROI_reduction); %does this work for the panda...?

%}

%set default Pixelrate
subfunc.fh_set_pixelrate(out_ptr,2);

subfunc.fh_set_triggermode(out_ptr,triggermode);
subfunc.fh_set_exposure_times(out_ptr,exposure_time,2,0,2);

%if PCO_ArmCamera does fail no images can be grabbed
errorCode = calllib('PCO_CAM_SDK', 'PCO_ArmCamera', out_ptr);
if(errorCode~=PCO_NOERROR)
 pco_errdisp('PCO_ArmCamera',errorCode);
 ME = MException('PCO_ERROR:ArmCamera','Cannot continue script with not armed camera');
 subfunc.fh_lasterr(errorCode);
 throw(ME);
end

%adjust transfer parameter if necessary
subfunc.fh_set_transferparameter(out_ptr);

triggermode=subfunc.fh_get_triggermode(out_ptr);

%display actual image time and maximal frequency
imatime=subfunc.fh_show_frametime(out_ptr)

%%
%% Measure time to acquire 1 image
		dwSec=uint32(0);
		dwNanoSec=uint32(0);
		[errorCode,~,dwSec,dwNanoSec] = calllib('PCO_CAM_SDK', 'PCO_GetCOCRuntime', out_ptr,dwSec,dwNanoSec);
		if(errorCode)
			pco_errdisp('PCO_GetCOCRuntime',errorCode);
		end
		disp(['Max double image capture freq: ' num2str(round(1/(double(dwNanoSec)/1000/1000/1000),3)) ' Hz.'])
%%

metadatasize=0;
if(bitand(cam_desc.dwGeneralCapsDESC1,GENERALCAPS1_METADATA))
 wMetaDataMode=uint16(0);
 wMetaDataSize=uint16(0);
 wMetaDataVersion=uint16(0);

 [errorCode,~,wMetaDataMode,wMetaDataSize,wMetaDataVersion] = calllib('PCO_CAM_SDK', 'PCO_GetMetaDataMode',out_ptr,wMetaDataMode,wMetaDataSize,wMetaDataVersion);
 pco_errdisp('PCO_GetMetaDataMode',errorCode);
 if(errorCode)
  pco_errdisp('PCO_GetMetaDataMode',errorCode);
  return;
 end

 disp(['Camera supports Metadata Version: ',num2str(wMetaDataVersion)]);

 if(wMetaDataMode~=0)
  metadatasize=wMetaDataSize;
  disp(['Metadata is enabled. Number of Bytes: ',num2str(metadatasize)]);
 end
end

%calculate images to grab
nr_of_images=uint32(fix(looptime/imatime)+1);
disp(['maximal ',num2str(nr_of_images),' images will be grabbed in ',num2str(looptime),' seconds' ]);

act_xsize=uint16(0);
act_ysize=uint16(0);
ccd_xsize=uint16(0);
ccd_ysize=uint16(0);

%use PCO_GetSizes because this always returns accurate image size for next recording
[errorCode,~,act_xsize,act_ysize]  = calllib('PCO_CAM_SDK', 'PCO_GetSizes', out_ptr,act_xsize,act_ysize,ccd_xsize,ccd_ysize);
if(errorCode)
 pco_errdisp('PCO_GetSizes',errorCode);
end

disp(['sizes: horizontal ',int2str(act_xsize),' vertical ',int2str(act_ysize)]);

flags=2; %IMAGEPARAMETERS_READ_WHILE_RECORDING;
errorCode = calllib('PCO_CAM_SDK', 'PCO_SetImageParameters', out_ptr,act_xsize,act_ysize,flags,[],0);
pco_errdisp('PCO_SetImageParameters',errorCode);

lineadd=0;
if(metadatasize>0)
 xs=uint32(fix((double(bitpix)+7)/8));
 xs=xs*uint32(act_xsize);
 i=uint16(floor((metadatasize*2)/double(xs)));
 lineadd=i+1;
end

disp(['lines added: ',int2str(lineadd)]);

%allocate memory for display, 4 buffers are used
bufcount=4;
bufnum=zeros(4,1,'int16');

imas=uint32(fix((double(bitpix)+7)/8));
imas= imas*uint32(act_xsize)* uint32(act_ysize);
imasize=imas;

image_stack=zeros(act_xsize,(act_ysize+lineadd),bufcount,'uint16');

%Allocate 4 SDK buffer and set address of buffers from image_stack
ev_ptr(bufcount) = libpointer('voidPtr');
im_ptr(bufcount) = libpointer('voidPtr');

buflist=libstruct('PCO_Buflist');
names=fieldnames(buflist);
x=1:4:length(names);
bufnr=names(x);
x=3:4:length(names);
statusdll=names(x);
x=4:4:length(names);
statusdrv=names(x);

for n=1:bufcount
 sBufNri=int16(-1);
 im_ptr(n) = libpointer('uint16Ptr',image_stack(:,:,n));
 ev_ptr(n) = libpointer('voidPtr');

 [errorCode,~,sBufNri]  = calllib('PCO_CAM_SDK','PCO_AllocateBuffer', out_ptr,sBufNri,imasize,im_ptr(n),ev_ptr(n));
 if(errorCode~=PCO_NOERROR)
  pco_errdisp('PCO_AllocateBuffer',errorCode);
  ME = MException('PCO_ERROR:AllocateBuffer','Cannot continue script without allocated Buffers');
  subfunc.fh_lasterr(errorCode);
  throw(ME);
 end
 buflist.(bufnr{n})=int16(sBufNri);
 bufnum(n)=int16(sBufNri);
 e=bitor(buflist.(statusdll{n}),uint32(PCO_BUFFER_EVAUTORES),'uint32');
 buflist.(statusdll{n})=e;
end

%show figure
ima=image_stack(:,1:act_ysize,1);
if(reduce_display_size~=0)
 [xs,ys]=size(ima);
 xmax=800;
 ymax=600;
 if((xs>xmax)&&(ys>ymax))
  ima=ima(1:xmax,1:ymax);
 elseif(xs>xmax)
  ima=ima(1:xmax,:);
 elseif(ys>ymax)
  ima=ima(:,1:ymax);
 end
end
ima=ima';

imah=draw_image(ima,[0 100]);
axish=gca;
set(axish,'CLim',[0 1000]);

pause(0.0001);

%grab preimage to get actual image value range and set limits
errorCode=subfunc.fh_start_camera(out_ptr);
if(errorCode~=PCO_NOERROR)
 ME = MException('PCO_ERROR:StartCamera','Cannot continue script with stopped camera');
 subfunc.fh_lasterr(errorCode);
 throw(ME);
end

errorCode  = calllib('PCO_CAM_SDK','PCO_AddBufferEx', out_ptr,0,0,bufnum(1),act_xsize,act_ysize,bitpix);
if(errorCode~=PCO_NOERROR)
 pco_errdisp('PCO_AddBufferEx',errorCode);
 ME = MException('PCO_ERROR:AddBufferEx','Cannot continue script without added Buffers');
 subfunc.fh_lasterr(errorCode);
 throw(ME);
end

disp('get pre images');
trigdone=int16(1);
if((triggermode==1)||(triggermode==2))
 [errorCode,~,trigdone]  = calllib('PCO_CAM_SDK','PCO_ForceTrigger',out_ptr,trigdone);
 if(errorCode)
  pco_errdisp('PCO_ForceTrigger',errorCode);
 else
  disp([int2str(trigdone),' trigger done return: ',int2str(trigdone)]);
 end
elseif(triggermode>2)
 disp('send external trigger pulse within 1 second');
 pause(0.001);
end

[errorCode,~,buflist]  = calllib('PCO_CAM_SDK','PCO_WaitforBuffer', out_ptr,1,buflist,1000);
if(errorCode)
 pco_errdisp('PCO_WaitforBuffer',errorCode);
else
 disp(['PCO_WaitforBuffer done bufnr: ',int2str(bufnum(1))]);
end

if((bitand(buflist.dwStatusDll_1,hex2dec('00008000')))&&(buflist.dwStatusDrv_1==0))
 disp(['Event buf',int2str(1),' pre image done, StatusDrv 0x',num2str(buflist.dwStatusDrv_1,'%08X'),' Statusdll 0x',num2str(buflist.dwStatusDll_1,'%08X')]);
%get data and show image
 ima=get(im_ptr(1),'Value');
 if(bitand(cam_desc.dwGeneralCapsDESC1,GENERALCAPS1_NO_TIMESTAMP)==0)
  [imanum,~]=subfunc.fh_get_timestamp(ima,bitalign,bitpix);
  disp(['get_timestamp imacount: ',int2str(imanum),' done ']);
  txt=subfunc.fh_print_timestamp(ima,bitalign,bitpix);
  disp(['timestamp ima:  ',txt]);
  str_time=subfunc.fh_get_struct_timestamp(ima,bitalign,bitpix);
  txt=subfunc.fh_print_struct_timestamp(str_time);
  disp(['timestamp str:  ',txt]);
 end

 if(metadatasize>0)
  metaline=ima(1:metadatasize,act_ysize+1:end);
  [errorCode_m,metastruct]=subfunc.fh_get_struct_metadata(metaline,metadatasize);
  if(errorCode_m)
   pco_errdisp('get_struct_metadata',errorCode_m);
  else
   txt=subfunc.fh_print_meta_timestamp(metastruct);
   disp(['timestamp meta: ',txt]);
  end
 end

 if(metadatasize>0)
  ima=ima(:,1:act_ysize);
 end

 if(reduce_display_size~=0)
  [xs,ys]=size(ima);
  xmax=800;
  ymax=600;
  if((xs>xmax)&&(ys>ymax))
   ima=ima(1:xmax,1:ymax);
  elseif(xs>xmax)
   ima=ima(1:xmax,:);
  elseif(ys>ymax)
   ima=ima(:,1:ymax);
  end
 end
 ima=ima';
 if(bitalign==BIT_ALIGNMENT_MSB)
  s=int16(16-bitpix);
  s=s*-1;
  ima=bitshift(ima,s);
 end

 m=max(max(ima(10:end-10,10:end-10)));
 set(axish,'CLim',[0 m+100]);
 disp(['pre image done maxvalue: ',int2str(m)]);
 set(imah,'CData',ima,'CDataMapping','scaled');
 pause(0.0001);
end

subfunc.fh_stop_camera(out_ptr);

%this will remove all pending buffers in the queue and does reset grabber
errorCode = calllib('PCO_CAM_SDK', 'PCO_CancelImages', out_ptr);
pco_errdisp('PCO_CancelImages',errorCode);

pause(0.01);
%variable to reduce amount of messages
d=10;
if(nr_of_images>100)
 if(nr_of_images<500)
  d=50;
 else
  d=100;
 end
end

errorCode=subfunc.fh_start_camera(out_ptr);
if(errorCode~=PCO_NOERROR)
 ME = MException('PCO_ERROR:StartCamera','Cannot continue script with stopped camera');
 subfunc.fh_lasterr(errorCode);
 throw(ME);
end

%setup loop
for n=1:bufcount
 errorCode = calllib('PCO_CAM_SDK','PCO_AddBufferEx', out_ptr,0,0,bufnum(n),act_xsize,act_ysize,bitpix);
 if(errorCode~=PCO_NOERROR)
  pco_errdisp('PCO_AddBufferEx',errorCode);
  ME = MException('PCO_ERROR:AddBufferEx','Cannot continue script without added buffers');
  subfunc.fh_lasterr(errorCode);
  throw(ME);
 end
end

[errorCode,~,act_recstate] = calllib('PCO_CAM_SDK', 'PCO_GetRecordingState',glvar.out_ptr,act_recstate);
if(errorCode)
  pco_errdisp('PCO_GetRecordingState',errorCode);
else
 disp(['Actual recording state is ',int2str(act_recstate)]);
end

if(act_recstate==1)
 disp('get images');

 trigdone=int16(1);
 trigcount=0;
 if(triggermode==1)
  [errorCode,~,trigdone]  = calllib('PCO_CAM_SDK','PCO_ForceTrigger',out_ptr,trigdone);
  if(errorCode)
   pco_errdisp('PCO_ForceTrigger',errorCode);
  else
   trigcount=trigcount+1;
   disp(['first trigger done return: ',int2str(trigdone)]);
  end
 elseif(triggermode>=2)
  disp('send external trigger pulses within 1 second');
 end
 pause(0.0001);
 tic;

%grab and display loop
 ima_nr=0;
 last_ok=0;
 while(ima_nr<nr_of_images)
%wait for buffers
  [errorCode,~,buflist]  = calllib('PCO_CAM_SDK','PCO_WaitforBuffer', out_ptr,bufcount,buflist,1000);
  if(errorCode)
   pco_errdisp('PCO_WaitforBuffer',errorCode);
   break;
  end
%  disp(['After wait image ',int2str(ima_nr),' last_ok ',num2str(last_ok)]);
%first image done trigger next
  if(triggermode==1)
   [errorCode,~,trigdone]  = calllib('PCO_CAM_SDK','PCO_ForceTrigger',out_ptr,trigdone);
   if(errorCode)
    pco_errdisp('PCO_ForceTrigger',errorCode);
   else
    trigcount=trigcount+1;
   end
  end

%test and display buffer
  next=last_ok+1;
  multi=0;
  for n=1:bufcount
   if(next>bufcount)
    next=1;
   end
%   disp(['Status buf',int2str(next),' StatusDll ',num2str(buflist.(statusdll{next}),'%08X'),' StatusDrv ',num2str(buflist.(statusdrv{next}),'%08X')]);
   if((bitand(buflist.(statusdll{next}),hex2dec('00008000')))&&(buflist.(statusdrv{next})==0))
%get data and show image
    last_ok=next;
    ima=get(im_ptr(next),'Value');
    ima_nr=ima_nr+1;
    multi=multi+1;

    if(rem(ima_nr,d)==0)
     disp(['Status buf',int2str(next),' ok  image ',int2str(ima_nr),' done, last_ok ',num2str(last_ok)]);
     if(bitand(cam_desc.dwGeneralCapsDESC1,GENERALCAPS1_NO_TIMESTAMP)==0)
      txt=subfunc.fh_print_timestamp(ima,bitalign,bitpix);
      disp(['Timestamp of image(',num2str(ima_nr,'%04d'),'): ',txt]);
     end

     if(metadatasize>0)
      metaline=ima(1:metadatasize,act_ysize+1:end);
      [errorCode_m,metastruct]=subfunc.fh_get_struct_metadata(metaline,metadatasize);
      if(errorCode_m)
       pco_errdisp('get_struct_metadata',errorCode_m);
      else
       txt=subfunc.fh_print_meta_timestamp(metastruct);
       disp(['Timestamp of meta (',num2str(ima_nr,'%04d'),'): ',txt]);
      end
     end
    end

    if(metadatasize>0)
     ima=ima(:,1:act_ysize);
    end

    if(reduce_display_size~=0)
     [xs,ys]=size(ima);
     xmax=800;
     ymax=600;
     if((xs>xmax)&&(ys>ymax))
      ima=ima(1:xmax,1:ymax);
     elseif(xs>xmax)
      ima=ima(1:xmax,:);
     elseif(ys>ymax)
      ima=ima(:,1:ymax);
     end
    end
    ima=ima';
    if(bitalign==BIT_ALIGNMENT_MSB)
     s=int16(16-bitpix);
     s=s*-1;
     ima=bitshift(ima,s);
    end
    set(imah,'CData',ima,'CDataMapping','scaled');
	pause(0.0001);
	assignin('base','letztes_bild',ima);

    errorCode = calllib('PCO_CAM_SDK','PCO_AddBufferEx', out_ptr,0,0,bufnum(next),act_xsize,act_ysize,bitpix);
    if(errorCode)
     pco_errdisp('PCO_AddBufferEx',errorCode);
     break;
    end
   end
   next=next+1;
  end

  if(multi>1)
   disp(['Multi Buffers found after wait:',num2str(multi)]);
  end
  t=toc;
  if(t>looptime)
   break;
  end
 end

 disp(['Last image ',int2str(ima_nr),' done ']);
 disp([int2str(ima_nr),' images done in ',num2str(t),' seconds. time per image is ',num2str(t/double(ima_nr),'%.3f'),'s']);
 if(bitand(cam_desc.dwGeneralCapsDESC1,GENERALCAPS1_NO_TIMESTAMP)==0)
  subfunc.fh_print_timestamp_t(ima,1,bitpix); %image is already shifted
 end

%this will remove all pending buffers in the queue
 errorCode = calllib('PCO_CAM_SDK', 'PCO_CancelImages', out_ptr);
 pco_errdisp('PCO_CancelImages',errorCode);

 [errorCode,~,buflist] = calllib('PCO_CAM_SDK','PCO_WaitforBuffer', out_ptr,bufcount,buflist,500);
 pco_errdisp('PCO_WaitforBuffer',errorCode);

 for next=1:bufcount
  disp(['Event buf',int2str(next),' StatusDll ',num2str(buflist.(statusdll{next}),'%08X'),' StatusDrv ',num2str(buflist.(statusdrv{next}),'%08X')]);
 end

 %disp('Press "Enter" to close window and proceed')
 %pause();
 %close();
 %pause(1);
end

subfunc.fh_stop_camera(out_ptr);

for n=1:bufcount
 errorCode = calllib('PCO_CAM_SDK','PCO_FreeBuffer',out_ptr,bufnum(n));
 if(errorCode)
  pco_errdisp('PCO_FreeBuffer',errorCode);
 else
  disp(['PCO_FreeBuffer',num2str(n),' done ']);
 end
end

catch ME
 errorCode=subfunc.fh_lasterr();
 txt=blanks(101);
 txt=calllib('PCO_CAM_SDK','PCO_GetErrorTextSDK',pco_uint32err(errorCode),txt,100);

 calllib('PCO_CAM_SDK', 'PCO_CancelImages', out_ptr);
 for n=1:bufcount
  calllib('PCO_CAM_SDK','PCO_FreeBuffer',out_ptr,bufnum(n));
 end

 clearvars -except ME glvar errorCode txt;

 if(glvar.camera_open==1)
  glvar.do_close=1;
  glvar.do_libunload=1;
  pco_camera_open_close(glvar);
 end

 if strfind(ME.identifier,'PCO_ERROR:')
  msg=[ME.identifier,' ',ME.message];
  warning('off','backtrace')
  warning(msg)
  disp(txt);
  for k=1:length(ME.stack)
    disp(['from file ',ME.stack(k).file,' at line ',num2str(ME.stack(k).line)]);
  end
  close();
  clearvars -except errorCode;
  commandwindow;
  return;
 else
  close();
  clearvars -except ME;
  rethrow(ME)
 end
end

clearvars -except glvar errorCode;

if(glvar.camera_open==1)
 glvar.do_close=1;
 glvar.do_libunload=1;
 pco_camera_open_close(glvar);
end

clearvars glvar;
commandwindow;

end


function test_convert_event

% WALLTIME 00:10:00
% MEM 2gb
% DEPENDENCY artifact2boolvec artifact2event artifact2trl boolvec2artifact boolvec2event boolvec2trl event2artifact event2boolvec event2trl trl2artifact trl2boolvec trl2event

% The functionality of converting between representations used to be covered by
% fieldtrip/private/convert_event but has been split over multiple functions to
% provide a better overview of the different conversions.

[ftver, ftpath] = ft_version;
cd(fullfile(ftpath, 'private'));

if false
  % this section helps to get all files opened in the editor
  edit	artifact2boolvec.m
  edit	artifact2event.m
  edit	artifact2trl.m
  edit	boolvec2artifact.m
  edit	boolvec2event.m
  edit	boolvec2trl.m
  edit	event2artifact.m
  edit	event2boolvec.m
  edit	event2trl.m
  edit	trl2artifact.m
  edit	trl2boolvec.m
  edit	trl2event.m
end

% there are 4 representations, hence there are 4x3=12 conversions to be tested

%%

artifact = [
  1 9
  11 19
  21 29
  31 39
  41 49
  ];

if true
  artifact = array2table(artifact);
  artifact.Properties.VariableNames = {'begsample', 'endsample'};
  artifact.type = {'a', 'b', 'c', 'd', 'e'}';
  artifact.value = {1, '2', 3, 4, 5}';
end

boolvec   = artifact2boolvec(artifact, 'endsample', 100)
event     = artifact2event(artifact)
trl       = artifact2trl(artifact)

% convert back
artifact1  = boolvec2artifact(boolvec)
artifact2  = event2artifact(event)
artifact3  = trl2artifact(trl)

%%

boolvec = zeros(1,100);
boolvec(1:10)  = 1;
boolvec(21)    = 2;

artifact  = boolvec2artifact(boolvec)
event     = boolvec2event(boolvec)
trl       = boolvec2trl(boolvec)

% convert back
boolvec1 = artifact2boolvec(artifact, 'endsample', 100)
boolvec2 = event2boolvec(event, 'endsample', 100)
boolvec3 = trl2boolvec(trl, 'endsample', 100)

%%

event = [];

event(1).type     = 'trigger';
event(1).value    = 1;
event(1).sample   = 1;
event(1).duration = [];
event(1).offset   = 0;

event(2).type     = 'trigger';
event(2).value    = 2;
event(2).sample   = 10;
event(2).duration = 2;
event(2).offset   = [];

artifact  = event2artifact(event)
boolvec   = event2boolvec(event, 'endsample', 100)
trl       = event2trl(event)

% convert back
event1 = artifact2event(artifact)
event2 = boolvec2event(boolvec)
event3 = trl2event(trl)

%%

trl = [
  1 9 0
  11 19 0
  21 29 0
  31 39 0
  41 49 0
  ];

if false
  trl = array2table(trl);
  trl.Properties.VariableNames = {'begsample', 'endsample', 'offset'};
  trl.type = {'a', 'b', 'c', 'd', 'e'}';
  trl.value = {1, '2', 3, 4, 5}';
end

artifact  = trl2artifact(trl)
boolvec   = trl2boolvec(trl, 'endsample', 100)
event     = trl2event(trl)

% convert back
trl1 = artifact2trl(artifact)
trl2 = boolvec2trl(boolvec)
trl3 = event2trl(event)


function models = loadUncModels(modPath, organisms, objre, printLevel)
% This function loads and unconstrains metabolic models from a specific folder
%
% USAGE:
%
%   models = loadUncModels(modPath, organisms, objre)
%
% INPUTS:
%   organisms:           nx1 cell array cell array with names of organisms in the study
%   modPath:             char with path of directory where models are stored
%   objre:               char with reaction name of objective function of organisms
%   printLevel:          Verbose level (default: printLevel = 1)
%
% OUTPUT:
%   models:              nx1 cell array cell array with models of organisms in the study
%
% .. Author: Federico Baldini 2017-2018

    if ~exist('modPath', 'var') || ~exist(modPath, 'dir')  % check if the modPath is set
        error('modPath is not defined. Please set the path of the model directory.');
    else
        if ~exist(modPath, 'dir')
            error(['modPath (' modPath ') does not exist.']);
        end
    end

    % check if the organisms are defined
    if ~exist('organisms', 'var') || isempty(organisms)
        error('organisms are not defined. Please check your input file.');
    end

    if ~exist('objre', 'var')
        objre = {'EX_biomass(e)'};
        warning(['The default objective (objre) has been set to ' objre{1}]);
    end

    % check if a printLevel is present
    if ~exist('printLevel', 'var')
        printLevel = 0;
    end

    % add an extra file separator if missing
    if strcmpi(modPath(end), filesep)
        modPath = modPath(1:end-1);
    end

    environment = getEnvironment();

    models = {[]};  % empty cell array to be filled with models
    for i = 1:length(organisms)

        restoreEnvironment(environment);

        % adding the file extension
        fileEnding = '';
        tmpOrganism = organisms(i, 1);
        tmpOrganism = tmpOrganism{1};
        if ~strcmpi(tmpOrganism(end-4:end), '.mat')
            fileEnding = '.mat';
        end

        ldm = readCbModel([modPath filesep tmpOrganism fileEnding]);

        % removing possible constraints of the bacs
        selExc = findExcRxns(ldm);
        Reactions2 = ldm.rxns(find(selExc));
        allex = Reactions2(strmatch('EX', Reactions2));
        biomass = allex(strmatch(objre, allex));
        finrex = setdiff(allex, biomass);
        ldm = changeRxnBounds(ldm, finrex, -1000, 'l');
        ldm = changeRxnBounds(ldm, finrex, 1000, 'u');

        % removing blocked reactions from the bacs
        %BlockedRxns = identifyFastBlockedRxns(ldm,ldm.rxns, printLevel);
        %ldm= removeRxns(ldm, BlockedRxns);
        %BlockedReaction = findBlockedReaction(ldm,'L2')

        % creating array with models as required as input from the following functions
        models(i, 1) = {ldm};
    end
end


function [out] = read_tmsi_poly5(filename, varargin)

% READ_TMSI_POLY5
%
% Use as
%   hdr = read_tmri_poly5(filename)
%   dat = read_tmsi_poly5(filename, hdr, begblock, endblock)
%
% This implementation is as closely as possible based on the original "tms_read",
% which contains the comments
%
%   Changed on 08-10-2014 by TL, TMSi
%   - Now supports loading a file from different directory than the script file
%   - Feedback on the validity of arguments and whether a file could be found or not.
%   - Dialogue is opened when no argument was given.
%
%   Changed on 18-10-2022 by JMS, DCCN
%   - Massive speed up: no intermediate double->single->double conversion ,and
%   - Don't store metadata that is not broadcasted to outside function in a struct array, and
%   - Allow for a selection of channels to be read, reducing memory footprint, and calibration step
%
% 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.

needhdr = (nargin==1);
needdat = (nargin>1);

if needdat
  signal = varargin{1};
  begblock = varargin{2};
  endblock = varargin{3};
end

if numel(varargin)==4
  chanindx = varargin{4};
else
  chanindx = [];
end

fid = fopen_or_error(filename, 'rb');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the header
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if needhdr
  pos = 31;
  fseek(fid,pos,'bof');
  version = fread(fid,1,'int16');
  if version == 203
    frewind(fid);
    signal.header.FID                   = fread(fid,31,'uchar');
    signal.header.VersionNumber         = fread(fid, 1,'int16');
  else % version 204
    frewind(fid);
    signal.header.FID                   = fread(fid,32,'uchar');
    signal.header.VersionNumber         = fread(fid, 1,'int16');
  end
  signal.header.MeasurementName       = fread(fid,81,'uchar');
  signal.header.FS                    = fread(fid, 1,'int16');
  signal.header.StorageRate           = fread(fid, 1,'int16');
  signal.header.StorageType           = fread(fid, 1,'uchar');
  signal.header.NumberOfSignals       = fread(fid, 1,'int16');
  signal.header.NumberOfSamplePeriods = fread(fid, 1,'int32');
  signal.header.EMPTYBYTES            = fread(fid, 4,'uchar');
  signal.header.StartMeasurement      = fread(fid,14,'uchar');
  signal.header.NumberSampleBlocks    = fread(fid, 1,'int32');
  signal.header.SamplePeriodsPerBlock = fread(fid, 1,'uint16');
  signal.header.SizeSignalDataBlock   = fread(fid, 1,'uint16');
  signal.header.DeltaCompressionFlag  = fread(fid, 1,'int16');
  signal.header.TrailingZeros         = fread(fid,64,'uchar');

  %conversion to char of text values
  signal.header.FID               = char(signal.header.FID);
  signal.header.MeasurementName   = char(signal.header.MeasurementName(2:signal.header.MeasurementName(1)+1));
  %    signal.header.StartMeasurement  = typecast(int8(signal.header.StartMeasurement),'int16'); % commented by RS 1feb11

  signal.fs = signal.header.FS;

  %check for right fileversion
  % if signal.header.VersionNumber ~= 203
  %    disp('Wrong file version! Imput file must be a Poly5/TMS version 2.03 file!');
  %    return;
  % end

  % Signal description
  for g=1:signal.header.NumberOfSignals
    signal.description(g).SignalName        = fread(fid,41,'uchar');
    signal.description(g).Reserved          = fread(fid, 4,'uchar');
    signal.description(g).UnitName          = fread(fid,11,'uchar');
    signal.description(g).UnitLow           = fread(fid, 1,'float32');
    signal.description(g).UnitHigh          = fread(fid, 1,'float32');
    signal.description(g).ADCLow            = fread(fid, 1,'float32');
    signal.description(g).ADCHigh           = fread(fid, 1,'float32');
    signal.description(g).IndexSignalList   = fread(fid, 1,'int16');
    signal.description(g).CacheOffset       = fread(fid, 1,'int16');
    signal.description(g).Reserved2         = fread(fid,60,'uchar');

    % conversion of char values (to right format)
    signal.description(g).SignalName = char(signal.description(g).SignalName(2:signal.description(g).SignalName(1)+1));
    signal.description(g).UnitName   = char(signal.description(g).UnitName(2:signal.description(g).UnitName(1)+1));
  end

  % return the header details
  out = signal;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%read data blocks
NB = signal.header.NumberSampleBlocks;
SD = signal.header.SizeSignalDataBlock;
NS = signal.header.NumberOfSignals;
NS_32bit = NS/2;

if isempty(chanindx)
  chanindx = 1:NS_32bit;
end

if needdat
  nblock = endblock + 1 - begblock;
  nsmp = SD/(NS_32bit*4); % number of samples per data block
  on  = 1;
  off = nsmp;
  dat = nan(numel(chanindx), nsmp*nblock);
  PI  = nan(1,NB);
  BT  = nan(7,NB);
  for g=begblock:endblock

    % jump to right position in file
    if signal.header.VersionNumber == 203
      pos = 217 + NS*136 + (g-1) *(86+SD);
    else
      pos = 218 + NS*136 + (g-1) *(86+SD);
    end
    fseek(fid,pos,'bof');

    PI(g) = fread(fid,1,'int32'); % if no struct array is created, this saves a lot of time, data is not broadcasted anyway
    fread(fid,4,'uchar'); %reserved for extension of previous field to 8 bytes
    BT(:,g) = fread(fid,14/2,'int16'); %dostime
    fread(fid,64,'uchar'); %reserved
    data = fread(fid,SD/4,'float32'); % no reason to convert to single, and back to double downstairs

    % Convert data to 32bit values.
    % In case also 16bit values have to be measured, these values are typecasted below:
    % data = fread(fid,SD/2,'int16'); %read data
    % data = int16(data);
    % data = typecast(data,'int32');
    % signal.block(g).DATA = data;
    % signal.data{g} = reshape(data,NS_32bit,SD/(NS_32bit*4));
    tmp = reshape(data, [NS_32bit, nsmp]);
    dat(:, on:off) = tmp(chanindx, :);
    on  = off+1;
    off = off+nsmp;
  end % for

  % Converting data to a usable format
  ADCLow   = [signal.description(1:2:end).ADCLow];   ADCLow   = ADCLow(chanindx);
  ADCHigh  = [signal.description(1:2:end).ADCHigh];  ADCHigh  = ADCHigh(chanindx);
  UnitLow  = [signal.description(1:2:end).UnitLow];  UnitLow  = UnitLow(chanindx);
  UnitHigh = [signal.description(1:2:end).UnitHigh]; UnitHigh = UnitHigh(chanindx);
  for g = 1:size(dat,1)  % represent data in [uV]
    dat(g,:) = (dat(g,:) - ADCLow(g))./(ADCHigh(g) - ADCLow(g))  .* (UnitHigh(g) - UnitLow(g)) + UnitLow(g) ; %correction for uV
  end

  % return the data
  out = dat;
end

fclose(fid);


function [adfreq, n, ts, fn, ad] = plx_ad(filename, channel)
% plx_ad(filename, channel): read all a/d data for the specified channel from a .plx or .pl2 file
%              returns raw a/d values
%
% [adfreq, n, ts, fn, ad] = plx_ad(filename, channel)
% [adfreq, n, ts, fn, ad] = plx_ad(filename, 0)
% [adfreq, n, ts, fn, ad] = plx_ad(filename, 'FP01')
%
% INPUT:
%   filename - if empty string, will use File Open dialog
%   channel - 0-based channel number or channel name
%
%           a/d data come in fragments. Each fragment has a timestamp
%           and a number of a/d data points. The timestamp corresponds to
%           the time of recording of the first a/d value in this fragment.
%           All the data values stored in the vector ad.
%
% OUTPUT:
%   adfreq - digitization frequency for this channel
%   n - total number of data points
%   ts - array of fragment timestamps (one timestamp per fragment, in seconds)
%   fn - number of data points in each fragment
%   ad - array of raw a/d values

adfreq = 0;
n = 0;
ts = -1;
fn = -1;
ad = -1;

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

[ filename, isPl2 ] = internalPL2ResolveFilenamePlx( filename );
if isPl2 == 1
    % return data from .pl2 file
    pl2Channel = channel;
    % PL2 uses 1-based channel numbers
    if ischar(channel) == 0
        pl2Channel = channel+1;
    end
    pl2ad = PL2Ad(filename, pl2Channel);
    if numel(pl2ad.Values) > 0
        adfreq = pl2ad.ADFreq;
        n = numel(pl2ad.Values);
        ts = pl2ad.FragTs;
        fn = pl2ad.FragCounts;
        ad = pl2ad.Values;
        % convert millivolts to raw a/d values
        pl2 = PL2GetFileIndex(filename);
        channelNumber = internalPL2ResolveChannel(pl2.AnalogChannels, pl2Channel);
        ad = round(ad/(pl2.AnalogChannels{channelNumber}.CoeffToConvertToUnits * 1000));
    end
    return;
end

% return plx data
channelNumber = plx_ad_resolve_channel(filename, channel);
if channelNumber == -1
    fprintf('\n plx_ad: no header for the specified A/D channel.');
    fprintf('\n    use plx_ad_info(filename) to print the list of a/d channels\n');
    return
end
[adfreq, n, ts, fn, ad] = mexPlex(2, filename, channelNumber);
end


function handle = xyzankurVisualise2(pos,fid)

% XYZANKURVISUALISE2
%
% COPYRIGHT : Carl Henrik Ek and Neil Lawrence, 2008

% MOCAP

if(nargin<2)
  fid = 1;
end

figure(fid);

joint = xyzankur2joint(pos);
handle{1} = xyzankurDraw(joint);axis equal;view([1 0 0]);
set(gca,'XLim',[-20 20],'YLim',[-20 20],'ZLim',[-5 70]);

figure(fid+2);
joint = xyzankur2joint(pos);
handle{2} = xyzankurDraw(joint);axis equal;view([1 1 1]);
set(gca,'XLim',[-20 20],'YLim',[-20 20],'ZLim',[-5 70]);

return;


function strings = GetParameterStrings(modelname)
%
% function strings = GetParameterStrings(modelname)
%
% Given an input modelname, this function returns the names of the model
% parameters
%
% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)
%

if (strcmp(modelname, 'StickIsoV_B0'))
    strings = {'ficvf', 'di', 'dh', 'fiso', 'diso', 'b0', 'theta', 'phi'};
elseif (strcmp(modelname, 'StickTortIsoV_B0'))
    strings = {'ficvf', 'di', 'fiso', 'diso', 'b0', 'theta', 'phi'};
elseif (strcmp(modelname, 'WatsonSHStick'))
    strings = {'ficvf', 'di', 'dh', 'kappa', 'theta', 'phi'};
elseif (strcmp(modelname, 'WatsonSHStickIsoV_B0'))
    strings = {'ficvf', 'di', 'dh', 'kappa', 'fiso', 'diso', 'b0', 'theta', 'phi'};
elseif (strcmp(modelname, 'WatsonSHStickIsoVIsoDot_B0'))
    strings = {'ficvf', 'di', 'dh', 'kappa', 'fiso', 'diso', 'irfrac', 'b0', 'theta', 'phi'};
elseif (strcmp(modelname, 'WatsonSHStickTortIsoV_B0'))
    strings = {'ficvf', 'di', 'kappa', 'fiso', 'diso', 'b0', 'theta', 'phi'};
elseif (strcmp(modelname, 'WatsonSHStickTortIsoVIsoDot_B0'))
    strings = {'ficvf', 'di', 'kappa', 'fiso', 'diso', 'irfrac', 'b0', 'theta', 'phi'};
elseif (strcmp(modelname, 'BinghamStickTortIsoV_B0'))
    strings = {'ficvf', 'di', 'kappa', 'beta', 'psi', 'fiso', 'diso', 'b0', 'theta', 'phi'};
elseif (strcmp(modelname, 'WatsonSHCylSingleRadTortIsoV_GPD_B0'))
    strings = {'ficvf', 'di', 'rad', 'kappa', 'fiso', 'diso', 'b0', 'theta', 'phi'};
elseif (strcmp(modelname, 'CylSingleRadIsoDotTortIsoV_GPD_B0'))
    strings = {'ficvf', 'di', 'rad', 'irfrac', 'fiso', 'diso', 'b0', 'theta', 'phi'};
else
    error(['Parameter strings yet to be defined for this model:', modelname]);
end


% std_dipplot() - Commandline function to plot cluster component dipoles. Dipoles for each
%                 named cluster is displayed in a separate figure. To view all the clustered
%                 components in the STUDY on the same figure (in a separate subplot), all
%                 STUDY clusters must be requested.
%                 To visualize dipoles, they first must be stored in the EEG dataset structures
%                 using dipfit(). Only components that have dipole locations will be displayed,
%                 along with the cluster mean dipole (in red).
% Usage:
%                 >> [STUDY] = std_dipplot(STUDY, ALLEEG, clusters);
% Inputs:
%   STUDY      - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
%   ALLEEG     - global EEGLAB vector of EEG structures for the dataset(s) included in
%                the STUDY. ALLEEG for a STUDY set is typically created using load_ALLEEG().
%
% Optional inputs:
%   'clusters' - [numeric vector | 'all']  -> specific cluster numbers to plot.
%                'all'  -> plot all clusters in STUDY.
%                {default: 'all'}.
%   'comps'    - [numeric vector]  -> indices of the cluster components to plot.
%                'all'  -> plot all the components in the cluster
%                {default: 'all'}.
%   'mode'     - ['together'|'apart'] Display all requested cluster on one
%                figure ('together') or separate figures ('apart').
%                'together'-> plot all 'clusters' in one figure (without the gui).
%                'apart'   -> plot each cluster in a separate figure. Note that
%                this parameter has no effect if the 'comps' option (above) is used.
%                {default: 'together'}
%   'figure'   - ['on'|'off'] plots on a new figure ('on')  or plots on current
%                figure ('off'). If 'figure','off' does not display gui controls,
%                Useful for incomporating a cluster dipplot into a complex figure.
%                {default: 'on'}.
% Outputs:
%   STUDY      - the input STUDY set structure modified with plotted cluster
%                mean dipole, to allow quick replotting (unless cluster means
%                already exists in the STUDY).
%   Example:
%   >> [STUDY] = std_dipplot(STUDY,ALLEEG, 'clusters', 5, 'mode', 'apart', 'figure', 'off');
%                % Plot cluster-5 component dipoles (in blue), plus ther mean dipole (in red),
%                % on an exisiting (gui-less) figure.
%
%  See also  pop_clustedit(), dipplot()
%
% Authors:  Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005

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

function STUDY = std_dipplot(STUDY, ALLEEG, varargin)

% Set default values
cls = []; % plot all clusters in STUDY
figureon = 1; % plot on a new figure
mode = 'apart';
opt_dipplot = {'projlines','off', 'normlen', 'on', 'pointout', 'on', 'verbose', 'off', 'dipolelength', 0,'spheres','on'};
%, 'spheres', 'on'
for k = 3:2:nargin
    switch varargin{k-2}
        case 'clusters'
            if isnumeric(varargin{k-1})
                cls = varargin{k-1};
                if isempty(cls)
                    cls = 2:length(STUDY.cluster);
                end
            else
                if isstr(varargin{k-1}) & strcmpi(varargin{k-1}, 'all')
                    cls = 2:length(STUDY.cluster);
                else
                    error('std_dipplot: ''clusters'' input takes either specific clusters (numeric vector) or keyword ''all''.');
                end
            end
            if length(cls) == 1, mode = 'apart'; else mode = 'together'; end;
        case 'comps'
            STUDY = std_plotcompdip(STUDY, ALLEEG,  cls, varargin{k-1});
            return;
        case 'plotsubjects', % do nothing
        case 'mode', mode = varargin{k-1};
        case 'figure'
            if strcmpi(varargin{k-1},'off')
                opt_dipplot{end + 1} = 'gui';
                opt_dipplot{end + 1} = 'off';
                figureon = 0;
            else
                opt_dipplot{end + 1} = 'projimg';
                opt_dipplot{end + 1} = 'on';
            end
    end
end

% select clusters to plot
% -----------------------
if isempty(cls)
    tmp =[];
    cls = 2:length(STUDY.cluster); % plot all clusters in STUDY
    for k = 1: length(cls)
        % don't include 'Notclust' clusters
        if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) & ~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)
            tmp = [tmp cls(k)];
        end
    end
    cls = tmp;
end;

if strcmpi(mode, 'apart')  % case each cluster on a separate figure
    for clus = 1: length(cls) % For each cluster requested
        if length(STUDY.cluster(cls(clus)).comps) > 0  % check there are comps in cluster
            max_r = 0;
            clear cluster_dip_models;
            len = length(STUDY.cluster(cls(clus)).comps);
            ndip = 0;
            dip_ind = [];
            if ~isfield(STUDY.cluster(cls(clus)),'dipole')
                STUDY = std_centroid(STUDY,ALLEEG, cls(clus) , 'dipole');
            elseif isempty(STUDY.cluster(cls(clus)).dipole)
                STUDY = std_centroid(STUDY,ALLEEG, cls(clus) , 'dipole');
            end
            for k = 1:len
                abset   = STUDY.datasetinfo(STUDY.cluster(cls(clus)).sets(1,k)).index;
                subject = STUDY.datasetinfo(STUDY.cluster(cls(clus)).sets(1,k)).subject;
               if ~isfield(ALLEEG(abset), 'dipfit')
                   warndlg2(['No dipole information available in dataset ' ALLEEG(abset).filename ' , abort plotting'], 'Aborting plot dipoles');
                   return;
               end
               comp = STUDY.cluster(cls(clus)).comps(k);
               cluster_dip_models(k).posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;
               cluster_dip_models(k).momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;
               cluster_dip_models(k).rv = ALLEEG(abset).dipfit.model(comp).rv;
               if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
                   if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model
                       load('-mat', ALLEEG(abset).dipfit.hdmfile);
                       max_r = max(max_r, max(vol.r));
                   else % old version of dipfit
                       max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));
                   end
               end
               comp_to_disp{k} = [subject  ', ' 'IC' num2str(comp) ];
               if ~isempty(cluster_dip_models(k).posxyz)
                   ndip = ndip +1;
                   dip_ind = [dip_ind k];
               end
            end % finished going over cluster comps
            STUDY.cluster(cls(clus)).dipole = computecentroid(cluster_dip_models);
            cluster_dip_models(end + 1) = STUDY.cluster(cls(clus)).dipole;

           % additional options
           % ------------------
           dip_color = cell(1,ndip+1);
           dip_color(1:ndip) = {'b'};
           dip_color(end) = {'r'};
           options = opt_dipplot;
           options{end+1} =  'mri';
           options{end+1} =  ALLEEG(abset).dipfit.mrifile;
           options{end+1} =  'coordformat';
           options{end+1} =  ALLEEG(abset).dipfit.coordformat;
           options{end+1} =  'dipnames';
           options{end+1} = {comp_to_disp{dip_ind } [STUDY.cluster(cls(clus)).name ' mean']};
           options{end+1} = 'color';
           options{end+1} = dip_color;
           if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
               options{end+1} = 'sphere';
               options{end+1} = max_r;
           else
               options{end+1} = 'meshdata';
               options{end+1} = ALLEEG(abset).dipfit.hdmfile;
           end
           if ndip < 6 && strcmpi(options{1}, 'projlines') && length(cls) == 1 % less than 6 dipoles, project lines
               options{2} = 'on';
           end

           if figureon
               dipplot(cluster_dip_models, options{:});
               fig_h = gcf;
               set(fig_h,'Name', [STUDY.cluster(cls(clus)).name ' - ' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) ...
                       ' sets - ' num2str(length(STUDY.cluster(cls(clus)).comps)) ' components (' num2str(ndip) ' dipoles)' ],'NumberTitle','off');
           else
               dipplot(cluster_dip_models, options{:},'view', [0.5 -0.5 0.5],'spheres', 'on', 'projlines', 'on');
               for gind = 1:length(options) % remove the 'gui' 'off' option
                   if isstr(options{gind})
                       if strfind(options{gind}, 'gui')
                           break;
                       end
                   end
               end
               options(gind:gind+1) = [];
               dipinfo.dipmod =  cluster_dip_models;
               dipinfo.op = options;
               diptitle = [STUDY.cluster(cls(clus)).name ', ' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) ' sets -' ...
                   num2str(length(STUDY.cluster(cls(clus)).comps)) ' components (' num2str(ndip) ' dipoles)' ];
               dipinfo.title = diptitle;
               set(gcf, 'UserData', dipinfo);
               set(gca,'UserData', dipinfo);
               rotate3d off;
               axcopy(gca, ['dipinfo = get(gca, ''''UserData''''); dipplot(dipinfo.dipmod, dipinfo.op{:}); set(gcf, ''''Name'''', dipinfo.title,''''NumberTitle'''',''''off''''); ']);
           end
        end % finished the if condition that cluster isn't empty
    end % finished going over requested clusters
end

if strcmpi(mode, 'together')  % case all clusters are plotted in the same figure (must be a new figure)
    N = length(cls);
    rowcols(2) = ceil(sqrt(N)); % Number of rows in the subplot figure.
    rowcols(1) = ceil(N/rowcols(2));
    fig_h = figure;
    orient tall
    set(fig_h,'Color', 'black');
    set(fig_h,'Name', 'All clusters dipoles','NumberTitle','off');
    set(fig_h, 'resize','off');
    for l = 1:N
        len = length(STUDY.cluster(cls(l)).comps);
        max_r = 0;
        clear cluster_dip_models;
        if ~isfield(STUDY.cluster(cls(l)),'dipole')
            STUDY = std_centroid(STUDY,ALLEEG, cls(l), 'dipole');
        elseif isempty(STUDY.cluster(cls(l)).dipole)
            STUDY = std_centroid(STUDY,ALLEEG, cls(l), 'dipole');
        end
        for k = 1: len
            abset = STUDY.datasetinfo(STUDY.cluster(cls(l)).sets(1,k)).index;
           if ~isfield(ALLEEG(abset), 'dipfit')
               warndlg2(['No dipole information available in dataset ' num2str(abset) ' , abort plotting'], 'Aborting plot dipoles');
               return;
           end
           comp = STUDY.cluster(cls(l)).comps(k);
           cluster_dip_models(k).posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;
           cluster_dip_models(k).momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;
           cluster_dip_models(k).rv = ALLEEG(abset).dipfit.model(comp).rv;
           if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
                if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model
                   load('-mat', ALLEEG(abset).dipfit.hdmfile);
                   max_r = max(max_r, max(vol.r));
               else % old version of dipfit
                   max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));
               end
           end
        end % finished going over cluster comps
        STUDY.cluster(cls(l)).dipole = computecentroid(cluster_dip_models);
        cluster_dip_models(end + 1) = STUDY.cluster(cls(l)).dipole;
        dip_color = cell(1,length(cluster_dip_models));
        dip_color(1:end-1) = {'b'};
        dip_color(end) = {'r'};
        options = opt_dipplot;
        options{end + 1} =  'gui';
        options{end + 1} =  'off';
        options{end+1} =  'mri';
        options{end+1} =  ALLEEG(abset).dipfit.mrifile;
        options{end+1} =  'coordformat';
        options{end+1} =  ALLEEG(abset).dipfit.coordformat;
        options{end+1} = 'color';
        options{end+1} = dip_color;
        if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
            options{end+1} = 'sphere';
            options{end+1} = max_r;
        else
            options{end+1} = 'meshdata';
            options{end+1} = ALLEEG(abset).dipfit.hdmfile;
        end
        subplot(rowcols(1),rowcols(2),l) ,
        dipplot(cluster_dip_models, options{:});
        title([ STUDY.cluster(cls(l)).name ' (' num2str(length(unique(STUDY.cluster(cls(l)).sets(1,:)))) ' Ss, '  num2str(length(STUDY.cluster(cls(l)).comps)),' ICs)'],'color','white');
        %diptitle = [STUDY.cluster(cls(l)).name ', ' num2str(length(unique(STUDY.cluster(cls(l)).sets(1,:)))) 'Ss'];
        %title(diptitle, 'Color', 'white');
        % Complex axcopy
        %if l == 1
        %    for gind = 1:length(options) % remove the 'gui' 'off' option
        %        if isstr(options{gind})
        %            if strfind(options{gind}, 'gui')
        %                break;
        %            end
        %        end
        %    end
        %    options(gind:gind+1) = [];
        %end
        %dipinfo.dipmod =  cluster_dip_models;
        %dipinfo.op = options;
        %dipinfo.title = diptitle;
        %set(gcf, 'UserData', dipinfo);
        %set(gca,'UserData', dipinfo);
        %axcopy(gcf, ['dipinfo = get(gca, ''''UserData''''); dipplot(dipinfo.dipmod, dipinfo.op{:}); set(gcf, ''''Name'''', dipinfo.title,''''NumberTitle'''',''''off'''');']);
   end %finished going over all clusters
   set(fig_h, 'resize','on');
end % finished case of 'all' clusters
% std_plotcompdip() - Commandline function, to visualizing cluster components dipoles.
%                   Displays the dipoles of specified cluster components with the cluster mean
%                   dipole on separate figures.
%                   To visualize dipoles they first must be stored in the EEG dataset structures
%                   using dipfit(). Only components that have a dipole locations will be displayed,
%                   along with the cluster mean dipole in red.
% Usage:
%                   >> [STUDY] = std_plotcompdip(STUDY, ALLEEG, cluster, comps);
% Inputs:
%   STUDY      - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
%   ALLEEG     - global EEGLAB vector of EEG structures for the dataset(s) included in the STUDY.
%                     ALLEEG for a STUDY set is typically created using load_ALLEEG().
%   cluster     - single cluster number.
%
% Optional inputs:
%   comps      - [numeric vector]  -> indices of the cluster components to plot.
%                       'all'                       -> plot all the components in the cluster {default: 'all'}.
%
% Outputs:
%   STUDY    - the input STUDY set structure modified with plotted cluster
%                     dipole mean, to allow quick replotting (unless cluster mean
%                     already existed in the STUDY).
%
%   Example:
%                         >> cluster = 4; comps= 1;
%                         >> [STUDY] = std_plotcompdip(STUDY,ALLEEG, cluster, comps);
%                    Plots component 1 dipole in blue with the cluster 4 mean dipole in red.
%
%  See also  pop_clustedit, dipfit, std_dipplot
%
% Authors:  Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005

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

function STUDY = std_plotcompdip(STUDY, ALLEEG, cls, varargin)
if ~exist('cls')
    error('std_plotcompdip: you must provide a cluster number as an input.');
end
if isempty(cls)
   error('std_plotcompdip: you must provide a cluster number as an input.');
end
if nargin == 3 % no components indices were given
    % Default plot all components of the cluster
    [STUDY] = std_dipplot(STUDY, ALLEEG, 'clusters', cls);
    return
else
    comp_ind = varargin{1};
end

for ci = 1:length(comp_ind)
    abset = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).index;
    comp = STUDY.cluster(cls).comps(comp_ind(ci));
    subject = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).subject;
    if ~isfield(ALLEEG(abset), 'dipfit')
        warndlg2(['No dipole information available in dataset ' num2str(abset) ' , abort plotting'], 'Aborting plot dipoles');
        return;
    end
    if length(comp_ind) == 1 & isempty(ALLEEG(abset).dipfit.model(comp).posxyz)
        warndlg2(strvcat('There is no dipole information available in', ...
                       [ 'dataset ' num2str(abset) ' for this component, abort plotting']), 'Aborting plot dipoles');
        return;
    end;
    if ~isfield(STUDY.cluster(cls),'dipole')
        STUDY = std_centroid(STUDY,ALLEEG, cls , 'dipole');
    elseif isempty(STUDY.cluster(cls).dipole)
        STUDY = std_centroid(STUDY,ALLEEG, cls , 'dipole');
    end
    comp_to_disp = [subject  ' / ' 'IC' num2str(comp) ];
    cluster_dip_models.posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;
    cluster_dip_models.momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;
    cluster_dip_models.rv = ALLEEG(abset).dipfit.model(comp).rv;
    cluster_dip_models(2) = STUDY.cluster(cls).dipole;
    if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
        if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model
            load('-mat', ALLEEG(abset).dipfit.hdmfile);
            max_r = max(vol.r);
        else
            max_r = max(ALLEEG(abset).dipfit.vol.r);
        end
        dipplot(cluster_dip_models, 'sphere', max_r, 'mri', ALLEEG(abset).dipfit.mrifile,'coordformat', ALLEEG(abset).dipfit.coordformat , ...
           'normlen' ,'on', 'pointout' ,'on','color', {'b', 'r'}, 'dipnames', {comp_to_disp [ STUDY.cluster(cls).name ' mean' ] },...
            'spheres', 'on', 'verbose', 'off', 'projlines', 'on');
    else
       dipplot(cluster_dip_models, 'meshdata', ALLEEG(abset).dipfit.hdmfile, 'mri', ALLEEG(abset).dipfit.mrifile,'coordformat', ALLEEG(abset).dipfit.coordformat , ...
          'normlen' ,'on', 'pointout' ,'on','color', {'b', 'r'}, 'dipnames', {comp_to_disp [STUDY.cluster(cls).name ' mean']}, ...
          'spheres', 'on', 'verbose', 'off', 'projlines', 'on');
    end
    fig_h = gcf;
    set(fig_h,'Name', [subject ' / ' 'IC' num2str(comp) ', ' STUDY.cluster(cls).name],'NumberTitle','off');
end

% -----------------------
% load all dipoles and
% compute dipole centroid
% DEVELOPMENT: this function
% should be the only one to
% access dipole information
% -----------------------
function STUDY = std_centroid(STUDY,ALLEEG, clsind, tmp);

    for clust = 1:length(clsind)
        max_r = 0;
        len = length(STUDY.cluster(clsind(clust)).comps);
        tmppos = [ 0 0 0 ];
        tmpmom = [ 0 0 0 ];
        tmprv = 0;
        ndip = 0;
        for k = 1:len
            fprintf('.');
            comp  = STUDY.cluster(clsind(clust)).comps(k);
            abset = STUDY.cluster(clsind(clust)).sets(1,k);
            if ~isfield(ALLEEG(abset), 'dipfit')
               warndlg2(['No dipole information available in dataset ' num2str(abset) ], 'Aborting compute centroid dipole');
               return;
            end
            if ~isempty(ALLEEG(abset).dipfit.model(comp).posxyz)
                ndip   = ndip +1;
                posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;
                momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;
                if size(posxyz,1) == 2
                    if all(posxyz(2,:) == [ 0 0 0 ])
                        posxyz(2,:) = [];
                        momxyz(2,:) = [];
                    end;
                end;
                tmppos = tmppos + mean(posxyz,1);
                tmpmom = tmpmom + mean(momxyz,1);
                tmprv = tmprv + ALLEEG(abset).dipfit.model(comp).rv;
                if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
                   if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model
                       load('-mat', ALLEEG(abset).dipfit.hdmfile);
                       max_r = max(max_r, max(vol.r));
                   else % old version of dipfit
                       max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));
                   end
               end
            end
        end
        centroid{clust}.dipole.posxyz =  tmppos/ndip;
        centroid{clust}.dipole.momxyz =  tmpmom/ndip;
        centroid{clust}.dipole.rv =  tmprv/ndip;
        if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') & (~isfield(ALLEEG(abset).dipfit, 'hdmfile')) %old dipfit
            centroid{clust}.dipole.maxr = max_r;
        end
        STUDY.cluster(clsind(clust)).dipole = centroid{clust}.dipole;
    end
    fprintf('\n');

% --------------------------------
% new function to compute centroid
% was programmed to debug the function
% above but is now used in the code
% --------------------------------
function dipole = computecentroid(alldipoles)

        max_r = 0;
        len = length(alldipoles);
        dipole.posxyz = [ 0 0 0 ];
        dipole.momxyz = [ 0 0 0 ];
        dipole.rv = 0;
        ndip = 0;
        count = 0;
        warningon = 1;
        for k = 1:len
            if size(alldipoles(k).posxyz,1) == 2
                if all(alldipoles(k).posxyz(2,:) == [ 0 0 0 ])
                    alldipoles(k).posxyz(2,:) = [];
                    alldipoles(k).momxyz(2,:) = [];
                end;
            end;
            if ~isempty(alldipoles(k).posxyz)
                dipole.posxyz = dipole.posxyz + mean(alldipoles(k).posxyz,1);
                dipole.momxyz = dipole.momxyz + mean(alldipoles(k).momxyz,1);
                dipole.rv     = dipole.rv     + alldipoles(k).rv;
                count = count+1;
            elseif warningon
                disp('Some components do not have dipole information');
                warningon = 0;
            end;
        end
        dipole.posxyz = dipole.posxyz/count;
        dipole.momxyz = dipole.momxyz/count;
        dipole.rv     = dipole.rv/count;
        if isfield(alldipoles, 'maxr')
            dipole.maxr = alldipoles(1).max_r;
        end;


function a = r8cvv_rset ( mn, a, m, roff, i, ai )

%*****************************************************************************80
%
%% R8CVV_RSET sets row I from an R8CVV.
%
%  Discussion:
%
%    An R8CVV is a "vector of vectors" of R8's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 November 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer MN, the size of the cell array.
%
%    Input, real A(MN), the cell array.
%
%    Input, integer M, the number of rows in the array.
%
%    Input, integer ROFF(M+1), the row offsets.
%
%    Input, integer I, the row.
%    1 <= I <= M.
%
%    Input, real AI(NR(I)), the new value of A(I,*).
%
%    Output, real A(MN), the cell array.
%
  k1 = roff(i) + 1;
  k2 = roff(i+1);
  nv = k2 + 1 - k1;
  a(k1:k2) = ai(1:nv);

  return
end


%GRIDBDRX Reconstruct interior boundaries.
%
%   [ GRID ] = GRIDBDRX( GRID, ORDER ) Reconstructs interior
%   boundaries and updates the GRID.B field. ORDER (default true)
%   changes the order of boundaries so external boundaries are first,
%   and internal last.
%
%   See also GRIDBDR

% Copyright 2013-2022 Precise Simulation, Ltd.


function [grad] = scaleGrad(grad, scale)
% scaleGrad just scales the gradint with the scalar
    if strcmp(grad.type,'trap')
        grad.amplitude=grad.amplitude*scale;
        grad.area=grad.area*scale;
        grad.flatArea=grad.flatArea*scale;
    else
        grad.waveform=grad.waveform*scale;
        grad.first=grad.first*scale;
        grad.last=grad.last*scale;
    end
    if isfield(grad,'id')
        grad = rmfield(grad,'id');
    end
end


function out = cellflat(celllist)
% CELLFLAT is a helper function to flatten nested cell arrays.
%
% CELLFLAT(celllist) searches every cell element in cellist and put them on
% the top most level. Therefore, CELLFLAT linearizes a cell array tree
% structure.
%
% Example: cellflat({[1 2 3], [4 5 6],{[7 8 9 10],[11 12 13 14 15]},{'abc',{'defg','hijk'},'lmnop'}})
%
% Output:
%Columns 1 through 7
%     [1x3 double]    [1x3 double]    [1x4 double]    [1x5 double]    'abc'    'defg'    'hijk'
%   Column 8
%     'lmnop'
%
% cellflat(({{1 {2 3}} 'z' {'y' 'x' 'w'} {4 @iscell 5} 6}) )
% Output:
% [1]    [2]    [3]    'z'    'y'    'x'    'w'    [4]    @iscell    [5]    [6]
%
% Version: 1.0
% Author: Yung-Yeh Chang, Ph.D. (yungyeh@hotmail.com)
% Date: 12/31/2014
% Copyright 2015, Yung-Yeh Chang, Ph.D.
% See Also: cell
if ~iscell(celllist)
    error('CELLFLAT:ImproperInputAugument','Input argument must be a cell array');
end
out = {};
for idx_c = 1:numel(celllist)
    if iscell(celllist{idx_c})
        out = [out cellflat(celllist{idx_c})];
    else
        out = [out celllist(idx_c)];
    end
end


function s = y_to_s_persian ( y )

%*****************************************************************************80
%
%% Y_TO_S_PERSIAN writes a Persian year into a string.
%
%  Format:
%
%    AP YearNumber
%
%  Discussion:
%
%    "AP" stands for "anno Persico".
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, the year.
%
%    Output, string S, a representation of the year.
%
  s = sprintf ( 'AP %d', y );

  return
end


function options = gpnddisimOptions

% GPNDDISIMOPTIONS Creates a set of default options for a GPNDDISIM model.
% FORMAT
% DESC returns a default options stucture for a GPNDDISIM model.
% RETURN options : the options structure.
%
% SEEALSO : gpnddisimCreate
%
% COPYRIGHT : Neil D. Lawrence, 2006, 2008
%
% COPYRIGHT : Pei Gao, 2008
%
% COPYRIGHT :  Jaakko Peltonen, 2011

% GPNDDISIM

options=struct();
options.includeNoise=1;
options.addPriors=0;
options.optimiser='quasinew';
options.use_disimstartmean=1;
options.use_fixedrnavariance=0;
options.fix=[];


s = 256;
mkdir flickr30k-images-256
p = dir('./flickr30k-images/*.jpg');
wp = sprintf('./flickr30k-images-%d/',s);
h1 = [];
w1 = [];
for i = 1:numel(p)
    %disp(i);
    str = [ './flickr30k-images/',p(i).name];
    im = imread(str);
    [h,w,~] = size(im);
    h1 = cat(1,h1,h);
    w1 = cat(1,w1,w);

    if(h<w)
        rate = s/h;
        imr = imresize(im,[s,w*rate]);
    else
        rate = s/w;
        imr = imresize(im,[h*rate,s]);
    end
    imwrite(imr,[ wp,p(i).name]);
    %}
end

disp( mean(h1) );  % 395
disp( mean(w1) );  % 460


function i4mat_write ( output_filename, m, n, table )

%*****************************************************************************80
%
%% I4MAT_WRITE writes an I4MAT file.
%
%  Discussion:
%
%    An I4MAT is an array of I4's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 June 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string OUTPUT_FILENAME, the output filename.
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N, the number of points.
%
%    Input, integer TABLE(M,N), the points.
%

%
%  Open the file.
%
  output_unit = fopen ( output_filename, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4MAT_WRITE - Error!\n' );
    fprintf ( 1, '  Could not open the output file.\n' );
    error ( 'I4MAT_WRITE - Error!' );
  end
%
%  Write the data.
%
  for j = 1 : n
    for i = 1 : m
      fprintf ( output_unit, '  %12d', round ( table(i,j) ) );
    end
    fprintf ( output_unit, '\n' );
  end
%
%  Close the file.
%
  fclose ( output_unit );

  return
end


function [] = writefort19( fort19dat, finame )
%
%

if ( nargin == 1 )
  finputname = 'fort.19_1' ;
else
  finputname = finame ;
end

fid = fopen(finputname,'w') ;

fprintf( fid, '%d\n', fort19dat.ETIMINC ) ;

valpernode = size( fort19dat.Val,2 ) ;
str = [];
for ll = 1: valpernode
    str = [str '%.8f '] ;
end
str = [str '\n' ] ;

fprintf( fid, str, fort19dat.Val' ) ;

fclose(fid) ;
%EOF
end


function M = rmCompareModelsGUI_selectVoxels(M, whichVoxels, plotFlag);
% Sub-select voxels in the ROI of rmCompareModelsGUI.
%
% M = rmCompareModelsGUI_selectVoxels([M=get from cur figure], [whichVoxels=dialog], [plotFlag=2]);
%
%
% INPUTS:
%	M: rmCompareModelsGUI structure. See rmCompareModelsGUI_getData. Can also be the handle
%	to an rmCompareModelsGUI figure.
%
%	whichVoxels: index of voxels within M.coords to select.
%	[default: open a dialog allowing the user to select voxels based on
%	basic pRF parameter ranges (e.g., varexp, eccentricity, polar angle,
%	sigma)].
%
%	plotFlag: flag indicating where to show the new analysis on the
%	restricted set of voxels. Values are:
%		0 -- just return the M structure and don't make/update a GUI.
%		1 -- replace the existing GUI with the new data (throw out the
%			 eliminated voxels).
%		2 -- open a new GUI for the restricted subset.
%		[default 2, open a new figure]
%
% Returns a modified version of M.
%
% ras, 04/2009.
if notDefined('M'),			M = get(gcf, 'UserData');		end
if ishandle(M),				M = get(M, 'UserData');			end
if notDefined('plotFlag'),	plotFlag = 2;					end
if notDefined('whichVoxels'),
	whichVoxels = selectVoxelsDialog(M);
end

% is M the proper structure?
if ~checkfields(M, 'modelList') | ~checkfields(M, 'tSeries')
	error('Need an rmCompareModelsGUI structure. See rmCompareModelsGUI.')
end

% are the coordinates empty? If so, warn and do nothing, but don't error.
if isempty(whichVoxels)
	warning('No voxels selected.')
	return
end

% sub-select the voxels
M.roi.coords = M.roi.coords(:,whichVoxels);
for m = 1:M.nModels
	for f = {'tSeries' 'x0' 'y0' 'sigma' 'pol' 'ecc' 'varexp'}
		M.(f{1}){m} = M.(f{1}){m}(:,whichVoxels);
	end
	M.beta{m} = M.beta{m}(whichVoxels,:);
end
M.roi.name = ['Subset of ' M.roi.name];
M.nVoxels = length(whichVoxels);

% update the GUI as desired
switch plotFlag
	case 0, % do nothing

	case 1, % replace data in existing GUI
		set(M.fig, 'UserData', M);

	case 2,
		M = rmCompareModelsGUI_openFig(M);

	otherwise, error('Invalid plot flag.')
end

return
% /-----------------------------------------------------------/ %

% /-----------------------------------------------------------/ %
function whichVoxels = selectVoxelsDialog(M);
%% put up a dialog to get pRF criteria for the voxels to keep, then find
%% the voxels which satisfy these criteria.

% build the dialog
dlg(1).fieldName = 'modelNum';
dlg(end).style = 'popup';
dlg(end).value = 1;
dlg(end).list  = M.dtList;
dlg(end).string = 'Select based on which model''s parameters?';

dlg(end+1).fieldName = 'notes';
dlg(end).style = 'text';
dlg(end).value = '';
dlg(end).string = 'Leave a field empty to omit thresholding:';

dlg(end+1).fieldName = 'varexp';
dlg(end).style = 'number';
dlg(end).value = 0.10;
dlg(end).string = 'Variance explained threshold:';

dlg(end+1).fieldName = 'ecc';
dlg(end).style = 'number';
dlg(end).value = [0 30];
dlg(end).string = 'Eccentricity range (blank for all values):';

dlg(end+1).fieldName = 'pol';
dlg(end).style = 'number';
dlg(end).value = [0 360];
dlg(end).string = 'Polar Angle range (deg CW from up):';

dlg(end+1).fieldName = 'sigma';
dlg(end).style = 'number';
dlg(end).value = [0 30];
dlg(end).string = 'pRF Diameter (major axis) range:';

% put up the dialog
resp = generalDialog(dlg, 'rmCompareModelsGUI: Select Voxels');

% get the model number
m = cellfind(M.dtList, resp.modelNum);
m = m(1); % in case 2 models from the same data type

% find voxels which pass the crtieria
ok = ones(1, size(M.roi.coords, 2));

if ~isempty(resp.varexp)
	ok = ok & (M.varexp{m} >= resp.varexp);
end

if length(resp.pol) > 1
	ok = ok & (M.pol{m} >= resp.pol(1) & M.pol{m} <= resp.pol(2));
end

if length(resp.ecc) > 1
	ok = ok & (M.ecc{m} >= resp.ecc(1) & M.ecc{m} <= resp.ecc(2));
end

if length(resp.sigma) > 1
	ok = ok & (M.sigma{m} >= resp.sigma(1) & M.sigma{m} <= resp.sigma(2));
end

whichVoxels = find(ok);

return


% Small technical example.
% Demonstrates an expedient for showing an image.
%
disp('Small technical example.');
disp('Demonstrates an expedient for showing an image.');
disp('FOR MORE INFORMATION:  help printshop');
disp(' ');
disp('See also the report http://repository.cwi.nl:8888/cwi_repository/docs/IV/04/04178D.pdf');
disp('Dr. Paul M. de Zeeuw <Paul.de.Zeeuw@cwi.nl>');
disp(' (C) 1998-2006 Stichting CWI, Amsterdam, The Netherlands');
disp(' ');
%------------------------------------------------------------------------------
load zenithgray; Orig = zenithgray; clear zenithgray;
printshop('original','Nice watch', Orig, 3, 0, []);


function test_bug1359

% MEM 3gb
% WALLTIME 00:10:00
% DEPENDENCY ft_read_header ft_read_data loadcnt

% the data is shared with test script 1490
filename = dccnpath('/home/common/matlab/fieldtrip/data/test/bug1490/sub1E3a.cnt');

hdr = ft_read_header(filename);
dat = ft_read_data(filename);

% The report is that the data looks weird and does not contain any
% negative values. I have not checked with old reading functions, but
% with FieldTrip revision 5913 (just after fixing the related bug 1490)
% the data looks meaningful. The channels have large offsets, some appear
% to have clipped, but there are channels that show a physiological signal
% with electrode drift. So it seems that the problem has disappeared.

assert(any(dat(:)>0) && any(dat(:)<0));


function mprob = convBaron(prob,opts)
%CONVBARON Convert OPTI problem to BARON Nonlinear problem
%
%   mprob = convBaron(prob,opts)

%   Copyright (C) 2013 Jonathan Currie (I2C2)

%Ensure all args passed
if(nargin < 2)
    error('You must supply both the problem + options');
end
if(~isstruct(prob) || ~isstruct(opts))
    error('Both prob + opts must be structures!');
end

%Get Warning Level
if(strcmpi(opts.warnings,'all'))
    warn = 2;
elseif(strcmpi(opts.warnings,'critical'))
    warn = 1;
else
    warn = 0;
end

%Assign Common Args
mprob.A = prob.A;
mprob.rl = prob.rl;
mprob.ru = prob.ru;
mprob.lb = prob.lb;
mprob.ub = prob.ub;
mprob.xtype = prob.int.str;

%Check if the user wants to use BARON LP/QP/QCQP solver
switch(lower(prob.type))
    case {'lp','milp','bilp','qp','qcqp','miqp','miqcqp'}
        if(warn > 1)
            optiwarn('OPTI:QCQP2NLP','Quadratic Program converted to (MI)NLP to suit BARON interface');
        end
        [prob,opts] = QCQP2NLP(prob,opts);
    case {'uno','nlp','minlp'}
        %nothing
    otherwise
        error('Problem type ''%s'' is not supported by BARON',prob.type);
end

%Assign remaining args
mprob.fun = prob.fun;
mprob.nlcon = prob.nlcon;
mprob.cl = prob.cl;
mprob.cu = prob.cu;
mprob.x0 = prob.x0;

% Set BARON options (optiset options override common ones)
%Build baronset struct, adding any passed options (ignored by baronset if not recognised)
options = baronset(opts.solverOpts);
%Add OPTISET options
options.epsa = opts.tolafun;
options.epsr = opts.tolrfun;
options.inttol = opts.tolint;
options.maxiter = opts.maxnodes;
options.maxtime = opts.maxtime;
options.prlevel = dispLevel(opts.display);
%Save Options Structure
mprob.options = options;

function  print_level = dispLevel(lev)
%Return IPOPT compatible display level
switch(lower(lev))
    case'off'
        print_level = 0;
    case 'iter'
        print_level = 1;
    case 'final'
        print_level = 1;
end


% sweep MasterThres param: percent cells included in Auto0.7, as a function
% of masterthres. for fig4 main.


classdef MimWindowLevelBone < MimGuiPlugin
    % MimWindowLevelBone. Gui Plugin for using a preset bone window/level
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimWindowLevelBone is a Gui Plugin for the MIM Toolkit.
    %     The gui will create a button for the user to run this plugin.
    %     Running this plugin will change the window and level of the viewing
    %     panel to standard soft tissue values.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        ButtonText = 'Bone'
        SelectedText = 'Bone'
        ToolTip = 'Changes the window and level settings to standard bone values (Window 2000HU Level 300HU)'
        Category = 'Window/Level Presets'
        Visibility = 'Dataset'
        Mode = 'Toolbar'

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 6
        ButtonHeight = 1
        Icon = 'wl_bone.png'
        Location = 22
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            gui_app.ImagePanel.Window = 2000;
            gui_app.ImagePanel.Level = 300;
        end

        function enabled = IsEnabled(gui_app)
            enabled = gui_app.IsDatasetLoaded && gui_app.IsCT && ~strcmp(gui_app.ImagePanel.Mode, MimModes.View3DMode);
        end

        function is_selected = IsSelected(gui_app)
            is_selected = gui_app.ImagePanel.Window == 2000 && gui_app.ImagePanel.Level == 300;
        end

    end
end