function savebinstack(bin, fname)
% Save an binary stack to a file, as an RGB Image.
%
%  If file name contains '??', then image is saved into a serie
%  of files, with increasing index.
%
%   See also:
%   savestack, imread
%

%   ---------
%   author: David Legland, david.legland(at)inrae.fr
%   INRA - Cepia Software Platform
%   created the 10/09/2003.
%   http://www.pfl-cepia.inra.fr/index.php?page=slicer

dim = size(bin);

if contains(fname, '??')
    % save a serie file, one file per slice of images
    disp('save slices - not yet implemented');

else
    % save one file containing all slices of image
    disp('save a stack');
    if length(dim)==3
        img = uint8(zeros([dim(1) dim(2) 3]));
        for i=1:dim(3)
            img(:,:,1) = uint8(bin(:,:,i)*255);
            img(:,:,2) = uint8(bin(:,:,i)*255);
            img(:,:,3) = uint8(bin(:,:,i)*255);
            imwrite(img, fname, 'tif', 'Compression', 'none', ...
                'WriteMode', 'append');
        end
    else
        for i=1:dim(4)
            imwrite(bin(:,:,:,i), fname, 'tif', 'Compression', 'none', ...
                'WriteMode', 'append');
        end
    end
end


function obj = rejection(obj, mode, varargin)

% Input parsing ----------------------------------------------------------------

validMode = {'Attribute' 'dAlphaNaN'};

p = inputParser;
p.addRequired( 'mode'                , @(x) any(strcmpi(x, validMode)));
p.addParameter('AttributeName'  , '' , @ischar);          % for mode 'Attribute'
p.addParameter('AttributeMinMax', [] , @(x) numel(x)==2); % for mode 'Attribute'
p.parse(mode, varargin{:});
p = p.Results;
% Clear required inputs to avoid confusion
clear mode

% Start ------------------------------------------------------------------------

procHierarchy = {'CORRPOINTS' 'REJECTION'};
msg('S', procHierarchy);
msg('I', procHierarchy, sprintf('Corr. points label = ''%s''', obj.label));
msg('I', procHierarchy, sprintf('IN: Mode = ''%s''', p.mode));
if strcmpi(p.mode, 'Attribute')
    msg('I', procHierarchy, sprintf('IN: AttributeName = ''%s''', p.AttributeName));
    msg('V', p.AttributeMinMax(1), 'IN: AttributeMinMax(1)', 'Prec', 3);
    msg('V', p.AttributeMinMax(2), 'IN: AttributeMinMax(2)', 'Prec', 3);
end

% Correspondences present? -----------------------------------------------------

if obj.noCP == 0
    msg('I', procHierarchy, 'no correspondences present!');
    msg('E', procHierarchy);
    return;
end

% Rejection of all correspondences where isnan(dAlpha) -------------------------

if strcmpi(p.mode, 'dAlphaNaN')

    idxRejection = isnan(obj.dAlpha);

end

% Rejection based on an attribute ----------------------------------------------

if strcmpi(p.mode, 'Attribute')

    att = obj.getAttribute(p.AttributeName);

    idxRejection = att >= min(p.AttributeMinMax) & att <= max(p.AttributeMinMax);

end

% Rejection --------------------------------------------------------------------

msg('V', sum(idxRejection), 'no. of rejected correspondences', 'Prec', 0);

obj.X1  = obj.X1(~idxRejection,:);
obj.X2  = obj.X2(~idxRejection,:);

% Rejection of attributes
if ~isempty(obj.A) , att  = fields(obj.A) ; else att  = []; end
if ~isempty(obj.A1), att1 = fields(obj.A1); else att1 = []; end
if ~isempty(obj.A2), att2 = fields(obj.A2); else att2 = []; end
for a = 1:numel(att) , obj.A.(att{a})   = obj.A.(att{a})(~idxRejection);   end
for a = 1:numel(att1), obj.A1.(att1{a}) = obj.A1.(att1{a})(~idxRejection); end
for a = 1:numel(att2), obj.A2.(att2{a}) = obj.A2.(att2{a})(~idxRejection); end

if ~isempty(obj.idxPC1), obj.idxPC1 = obj.idxPC1(~idxRejection,:); end
if ~isempty(obj.idxPC2), obj.idxPC2 = obj.idxPC2(~idxRejection,:); end

% End --------------------------------------------------------------------------

msg('E', procHierarchy);
obj.info

end


function afni_fig_interface(src, evnt)
   cf = gcf;
   figure(src);
   % evnt
   ud = get(src,'UserData');
   if (isempty(ud) | ~isfield(ud,'axes_lock')),
      ud = default_ud();
      set(src,'UserData',ud);
   end

   if (  lower(evnt.Character) == 'l'  ),
      ud.axes_lock = ~ud.axes_lock;
      set (src,'UserData',ud);
      if ud.axes_lock, set (src,'Name','L');
      else set (src,'Name','');
      end
   elseif (  lower(evnt.Character) == 'a'  ),
      if (ud.axes_lock),
         reset_axis(evnt.Character, get_all_axes(src));
      else
         reset_axis(evnt.Character,gca); %can send arrays for characters and axes
      end
   elseif (  lower(evnt.Character) == 'x'  |...
         lower(evnt.Character) == 'y'  |...
         lower(evnt.Character) == 'z' ),
      if (ud.axes_lock),
         zoom_axis(evnt.Character, get_all_axes(src));
      else
         zoom_axis(evnt.Character,gca); %can send arrays for characters and axes
      end
   elseif ( strcmp(evnt.Key , 'leftarrow') |...
            strcmp(evnt.Key , 'rightarrow') |...
            strcmp(evnt.Key , 'uparrow') |...
            strcmp(evnt.Key , 'downarrow')),
      if (ud.axes_lock),
         shift_axis(evnt, get_all_axes(src));
      else
         shift_axis(evnt, gca);
      end
   end
   figure(cf);
return;

function reset_axis(a,h)
   ca = gca;
   for (ih=1:1:length(h)),
      axes(h(ih));
      axis auto;
   end
   axes(ca);
return

function zoom_axis(a,h)
   ca = gca;
   for (ia=1:1:length(a)),
      for (ih=1:1:length(h)),
         axes(h(ih));
         dv = 4;
         if (  ~(a(ia) - lower(a(ia))) ),
            dv = 1;
         end
         if (~(lower(a(ia)) - 'x')), se = [1 2];
         elseif (~(lower(a(ia)) - 'y')), se = [3 4];
         elseif (~(lower(a(ia)) - 'z')), se = [5 6];
         else
            return;
         end
         v = axis;
         if (length(v) < max(se)), return; end
         vc = (v(se(1))+v(se(2)))/2;
         vd = v(se(2))-v(se(1));
         v(se(1)) = vc-vd/dv;
         v(se(2)) = vc+vd/dv;
         axis(v);
      end
   end
   axes(gca);
return;

function shift_axis(e,h)
   ca = gca;
   for (ie=1:1:length(e)),
      for (ih=1:1:length(h)),
         axes(h(ih));
         if (strcmp(e(ie).Key , 'leftarrow')),
            se = [1 2]; dv = +0.1;
         elseif (strcmp(e(ie).Key , 'rightarrow')),
            se = [1 2]; dv = -0.1;
         elseif (strcmp(e(ie).Key , 'downarrow')),
            se = [3 4]; dv = -0.1;
         elseif (strcmp(e(ie).Key , 'uparrow')),
            se = [3 4]; dv = 0.1;
         else
            return;
         end
         v = axis
         vd = v(se(2))-v(se(1));
         v(se(1)) = v(se(1))+vd*dv;
         v(se(2)) = v(se(2))+vd*dv;
         axis(v);
      end
   end
   axes(gca);
return;

function v = get_all_axes(f)
   l = get(f, 'Children');
   v = [];
   for (i=1:1:length(l)),
      if (strcmp(get(l(i),'Type'),'axes')), v = [v l(i)]; end
   end
return

function ud = default_ud()
   ud = struct('axes_lock', 0);
return


% Support only 2 dim array
classdef CMatrix
   properties (Constant)
      mex = CMatrix.mexSelector();
   end

   methods (Static)
      function func = mexSelector()
         if isarm()
            func = @CMatrixArmMex;
         else
            func = @CMatrixMex;
         end
      end
   end

   properties
      x;
   end

   methods
      function o = CMatrix(a)
         if iscell(a) || isa(a, 'uint8')
            o.x = a;
         else
            o.x = CMatrix.toMex(a);
         end
      end

      %% Sizes
      function [m, n] = size(a, dim)
         a = a.x;
         if (iscell(a))
            s = double(size(a{1}));
         else
            s = [size(a, 2) size(a, 3)];
         end

         if (nargin == 1)
            if (nargout == 2)
               m = s(1);
               n = s(2);
            else
               m = s;
            end
         else
            m = s(dim);
         end
      end

      function r = length(a)
         s = size(a);
         if (min(s) == 0)
            r = 0;
         else
            r = max(s);
         end
      end

      function r = numel(a)
         r = prod(size(a)); %#ok<*PSIZE>
      end

      function r = isscalar(a)
         r = (numel(a) == 1);
      end

      function r = isvector(a)
         r = (size(a,1) == 1 || size(a,2) == 1);
      end

      function r = isempty(a)
         r = (numel(a) == 0);
      end

      function r = isrow(a)
         r = (size(a,1) == 1);
      end

      function r = iscolumn(a)
         r = (size(a,2) == 1);
      end

      function r = ismatrix(~)
         r = true;
      end

      function r = end(a, k, n)
         if n == 2
            r = size(a,k);
         else
            r = size(a,1) * size(a,2);
         end
      end

      %% Conversions
      function disp(a)
         disp(double(a))
      end

      function r = double(a)
         r = CMatrix.UnaryOp('double', a);
      end

      function r = logical(a)
         r = CMatrix.UnaryOp('logical', a);
      end

      function r = sparse(a,b,c,d,e,f)
         if nargin == 1
            if ~issparse(a)
               A = logical(sparse(double(a)));
               s = struct('type', '()');
               s.subs = {find(A)};
               s = CMatrix(subsref(a, s));
               s.x = reshape(s.x, [size(s.x,1) numel(s.x)/size(s.x,1)]);
               r = CMatrix({A;s.x});
            else
               r = CMatrix(a);
            end
         else
            assert(nargin == 3 || nargin == 5 || nargin == 6, "unsupported number of arguments for sparse");
            if nargin == 3
               i = a; j = b; s = c; m = max(i); n = max(j); nzmax = length(s);
               if isempty(i)
                  m = 0; n = 0;
               end
            elseif nargin == 5
               i = a; j = b; s = c; m = d; n = e; nzmax = length(s);
            elseif nargin == 6
               i = a; j = b; s = c; m = d; n = e; nzmax = f;
            end
            A = sparse(i, j, ones(nzmax,1,'logical'),m,n,nzmax);
            assert(length(s) == nzmax);
            s = CMatrix(s(:));
            r = CMatrix({A;s.x});
         end
      end

      function r = full(a)
         if issparse(a)
            A = a.x{1};
            s = a.x{2};
            r = zeros(size(s,1), size(A,1), size(A,2), 'uint8');
            idx = find(a.x{1});
            r(:, idx) = s;
            r = CMatrix(r);
         else
            r = CMatrix(a);
         end
      end

      function r = issparse(a)
         r = iscell(a.x);
      end

      function r = issymmetric(a)
         if size(a,1) ~= size(a,2)
            r = false;
         else
            r = full(all(a == a', 'all'));
         end
      end

      function r = diag(a)
         assert(nargin == 1, "Support only one parameters")
         if isvector(a)
            r = CMatrix(sparse(a));
            if size(a,1) == 1
               r = r';
            end
            r.x{1} = diag(double(a));
            if ~issparse(a)
               r = full(r);
            end
         else
            k = min(size(a));
            if k == 0
               r = CMatrix([]);
            else
               idx = (1:k) + size(a,1) * (0:(k-1));
               r =  subsref(a, struct('type', '()', 'subs', {{idx}}));
            end
            if issparse(a)
               r = sparse(r);
            end
            if size(a,2) < size(a,1)
               r = r';
            end
         end
      end

      function r = reshape(a, s)
         if issparse(a)
            a.x{1} = reshape(a.x{1}, s);
         else
            a.x = reshape(a.x, [size(a.x,1) s]);
         end
         r = CMatrix(a.x);
      end

      function r = eps(~)
         r = CMatrix(CMatrix.mex('eps'));
      end

      %% Comparisons
      function r = lt(a, b)
         r = CMatrix.BinaryOp('lt', a, b);
         if ((issparse(a) || issparse(b)) && ~issparse(r)), r = sparse(r); end
      end

      function r = gt(a, b)
         r = CMatrix.BinaryOp('gt', a, b);
         if ((issparse(a) || issparse(b)) && ~issparse(r)), r = sparse(r); end
      end

      function r = le(a, b)
         r = ~gt(a,b);
      end

      function r = ge(a, b)
         r = ~lt(a,b);
      end

      function r = ne(a, b)
         r = CMatrix.BinaryOp('ne', a, b);
         if ((issparse(a) || issparse(b)) && ~issparse(r)), r = sparse(r); end
      end

      function r = eq(a, b)
         r = ~ne(a,b);
      end

      function r = and(a, b)
         r = CMatrix.BinaryOp('and', a, b);
      end

      function r = or(a, b)
         r = CMatrix.BinaryOp('or', a, b);
      end

      function r = not(a)
         r = ~logical(a);
      end

      %% Arithmetic
      function r = plus(a, b)
         r = CMatrix.BinaryOp('plus', a, b);
      end

      function r = minus(a, b)
         r = CMatrix.BinaryOp('minus', a, b);
      end

      function r = times(a, b)
         r = CMatrix.BinaryOp('times', a, b);
      end

      function r = power(a, b)
         assert(isscalar(b) && b == 2, "support only power(a, 2)");
         r = a .* a;
      end

      function r = rdivide(a, b)
         if issparse(b)
            b = full(b);
         end
         r = CMatrix.BinaryOp('rdivide', a, b);

         if issparse(a) % To fix the bug regarding x / 0
            r2 = double(a) ./ double(b);
            r(~isfinite(r2)) = r2(~isfinite(r2));
         end
      end

      function r = ldivide(a, b)
         r = b./a;
      end

      function r = uminus(a)
         r = CMatrix.UnaryOp('uminus', a);
      end

      function r = uplus(a)
         r = a;
      end

      function r = abs(a)
         r = CMatrix.UnaryOp('abs', a);
      end

      function r = sqrt(a)
         r = CMatrix.UnaryOp('sqrt', a);
      end

      function r = sum(varargin)
         r = CMatrix.ReductionOp('sum', varargin{:});
      end

      function r = prod(varargin)
         r = CMatrix.ReductionOp('prod', varargin{:});
      end

      function r = all(a, dim)
         if nargin == 1
            r = all(logical(a));
         else
            r = all(logical(a), dim);
         end
      end

      function r = any(a, dim)
         if nargin == 1
            r = any(logical(a));
         else
            r = any(logical(a), dim);
         end
      end

      function r = max(a, b, c)
         if nargin == 1
            r = CMatrix.ReductionOp('max', a);
         elseif nargin == 3 && size(b,1) == 0 && size(b,2) == 0
            r = CMatrix.ReductionOp('max', a, c);
         else
            assert(nargin == 2);
            r = CMatrix.BinaryOp('max2', a, b);
            if issparse(a) || issparse(b)
               r = sparse(r);
            end
         end
      end

      function r = min(a, b, c)
         if nargin == 1
            r = CMatrix.ReductionOp('min', a);
         elseif nargin == 3 && size(b,1) == 0 && size(b,2) == 0
            r = CMatrix.ReductionOp('min', a, c);
         else
            assert(nargin == 2);
            r = CMatrix.BinaryOp('min2', a, b);
            if issparse(a) || issparse(b)
               r = sparse(r);
            end
         end
      end

      function r = norm(a)
         assert(isvector(a), "norm supports only vectors.");
         r = sqrt(full(sum(a.^2)));
      end

      function r = nnz(a)
         r = full(sum(logical(a),'all'));
      end

      %% Access
      function [i,j,v] = find(a)
         if nargout == 1
            i = find(logical(a));
         elseif nargout == 2
            [i,j] = find(logical(a));
         else
            a = sparse(CMatrix(a));
            [i,j] = find(a.x{1});
            v = CMatrix(a.x{2});
            if size(a,1) == 1
               v = v';
            end
            if numel(v) == 0
               v = CMatrix([]);
            end
         end
      end

      %% Matrix operations
      function r = ctranspose(a)
         r = transpose(a);
      end

      function r = transpose(a)
         r = CMatrix.UnaryOp('transpose', a);
      end

      function r = mtimes(a, b)
         if isscalar(a) || isscalar(b)
            r = a .* b;
         else
            r = CMatrix.BinaryOp('mtimes', a, b);
         end
      end

      function r = mldivide(a, b)
         assert(size(a,1) == size(b,1), 'Incompatible Size.');
         s = [size(a,2), size(b,2)];
         if size(a,2) == 0 || size(a,1) == 0 || size(b,2) == 0
            r = CMatrix(zeros(s));
         elseif isscalar(a)
            r = reshape(b ./ a, s);
         else
            b_full = full(b); % sparsity usually does not help. Do this for simplicity
            r = CMatrix.BinaryOp('mldivide', a, b_full);
         end
         if (issparse(a) && issparse(b))
            r = sparse(r);
         end
      end

      function r = mrdivide(a, b)
         r = (b'\a')';
      end

      function r = horzcat(varargin)
         allDense = true;
         for k = 1:length(varargin)
            allDense = allDense & ~issparse(varargin{k});
         end

         if (allDense)
            cat_input = cell(length(varargin), 1);
            for k = 1:length(varargin)
               cat_input{k} = varargin{k}.x;
            end
            r = CMatrix(cat(3, cat_input{:}));
         else
            A_bool = [];
            m = []; v = [];
            for k = 1:length(varargin)
               A = sparse(CMatrix(varargin{k}));
               if k == 1
                  m = size(A,1);
                  A_bool = A.x{1};
                  v = A.x{2};
               else
                  assert(m == size(A,1), 'Incompatible size.');
                  A_bool = [A_bool A.x{1}];
                  v = [v A.x{2}];
               end
            end
            r = CMatrix({A_bool;v});
         end
      end

      function r = vertcat(varargin)
         for i = 1:length(varargin)
            varargin{i} = varargin{i}';
         end
         r = horzcat(varargin{:})';
      end

      function r = subsref(a,s)
         if strcmp(s(1).type, '()')
            if issparse(a)
               idx = subsref(CMatrix.ToIndex(a),s);
               A = logical(idx);
               [~,~,idx] = find(idx);
               v = a.x{2};
               v = v(:, idx);
               r = CMatrix({A;v});
            else
               idx = subsref(CMatrix.ToIndex(a),s);
               r = CMatrix(reshape(a.x(:,idx), [size(a.x,1) size(idx)]));
            end
         else
            r = builtin('subsref',a,s);
         end
      end

      function r = subsasgn(a,s,b)
         if strcmp(s(1).type, '()')
            [a_idx, a_v] = CMatrix.ToIndex(a);
            [b_idx, b_v] = CMatrix.ToIndex(b);
            b_idx = max(a_idx,[],'all') + b_idx;
            v = [a_v b_v];

            r_idx = subsasgn(a_idx,s,b_idx);

            if issparse(r_idx)
               A = logical(r_idx);
               [~,~,idx] = find(r_idx);
               v = v(:, idx);
               r = {A;v};
            else
               r = reshape(v(:, r_idx), [size(v,1) size(r_idx)]);
            end
            r = CMatrix(r);
         else
            r = builtin('subsasgn',a,s,b);
         end
      end

      %% cholesky related
      function r = dissect(a)
         r = dissect(double(a));
      end

      function r = amd(a)
         r = amd(double(a));
      end

      function r = colamd(a)
         r = colamd(double(a));
      end

      function r = symbfact(a)
         r = symbfact(double(a));
      end

      function [r1, r2] = etree(a)
         [r1, r2] = etree(double(a));
      end

      function r = chol(a)
         r = CMatrix.UnaryOp('chol', a);
      end
   end

   methods (Static)
      function r = ones(varargin)
         r = CMatrix(ones(varargin{:}));
      end

      function r = zeros(varargin)
         r = CMatrix(zeros(varargin{:}));
      end

      function r = eye(varargin)
         r = CMatrix(eye(varargin{:}));
      end

      function r = rand(varargin)
         r = CMatrix(rand(varargin{:}));
      end

      function r = randn(varargin)
         r = CMatrix(randn(varargin{:}));
      end

      function r = randi(varargin)
         r = CMatrix(randi(varargin{:}));
      end

      function r = toMex(a)
         if isa(a, 'CMatrix')
            r = a.x;
         elseif isobject(a)
            r = a.x;
            r = CMatrix.mex('toMex', r);
         else
            r = CMatrix.mex('toMex', double(a));
         end
      end

      function r = UnaryOp(cmd, a)
         a = CMatrix.toMex(a);
         r = CMatrix.mex(cmd, a);

         if iscell(r) || isa(r, 'uint8')
            r = CMatrix(r);
         end
      end

      function r = BinaryOp(cmd, a, b)
         a = CMatrix.toMex(a);
         b = CMatrix.toMex(b);
         r = CMatrix.mex(cmd, a, b);

         if iscell(r) || isa(r, 'uint8')
            r = CMatrix(r);
         end
      end

      function [r, v] = ToIndex(a)
         if nargout == 2 && ~isa(a, 'CMatrix')
            a = CMatrix(a);
         end

         if issparse(a)
            [i,j] = find(double(a));
            r = sparse(i,j,1:length(i),size(a,1),size(a,2));

            if nargout == 2
               v = a.x{2};
            end
         else
            r = reshape(1:numel(a),[size(a,1) size(a,2)]);

            if nargout == 2
               v = reshape(a.x, [size(a.x,1) numel(a.x)/size(a.x,1)]);
            end
         end
      end

      function r = ReductionOp(cmd, a, dim_)
         a_size = size(a);
         a = CMatrix(a);

         if nargin == 2
            if (size(a,1) > 1)
               dim = 1;
            elseif (size(a,2) > 1)
               dim = 2;
            else
               dim = 1;
               a = subsref(a, struct('type', '()', 'subs', {{':'}}));
            end
         else
            assert(strcmp(dim_, 'all') || isscalar(dim_), 'dim can either be all or a scalar');
            if strcmp(dim_, 'all')
               dim = 1;
               a = subsref(a, struct('type', '()', 'subs', {{':'}}));
            else
               dim = dim_;
            end
         end

         if size(a,1) == 0
            switch cmd
               case 'sum'
                  r = CMatrix(0.0 * ones(1, size(a,2)));
               case 'prod'
                  r = CMatrix(1.0 * ones(1, size(a,2)));
               case 'max'
                  r = CMatrix(ones(0, a_size(2)));
               case 'min'
                  r = CMatrix(ones(0, a_size(2)));
            end
            if dim == 2
               r = r';
            end
         elseif dim == 1
            r = CMatrix.mex(cmd, a.x);
            r = CMatrix(r);
         elseif dim == 2
            a = a';
            r = CMatrix.mex(cmd, a.x);
            r = CMatrix(r)';
         end

         if issparse(a)
            r = sparse(r);
         end
      end
   end
end


function [headmodel, cfg] = ft_prepare_singleshell(cfg, mri)

% FT_PREPARE_SINGLESHELL is deprecated, please use FT_PREPARE_HEADMODEL and
% FT_PREPARE_MESH
%
% See also FT_PREPARE_HEADMODEL

% TODO the spheremesh option should be renamed consistently with other mesh generation cfgs
% TODO shape should contain pnt as subfield and not be equal to pnt (for consistency with other use of shape)

% Copyright (C) 2006-2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

warning('FT_PREPARE_SINGLESHELL is deprecated, please use FT_PREPARE_HEADMODEL with cfg.method = ''singleshell'' instead.')

% these are used by the ft_preamble/ft_postamble function and scripts
ft_revision = '$Id$';
ft_nargin   = nargin;
ft_nargout  = nargout;

% do the general setup of the function
ft_defaults
ft_preamble init
ft_preamble debug
ft_preamble loadvar mri
ft_preamble provenance mri

% the ft_abort variable is set to true or false in ft_preamble_init
if ft_abort
  return
end

% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamed', {'spheremesh', 'numvertices'});
cfg = ft_checkconfig(cfg, 'deprecated', 'mriunits');

% set the defaults
if ~isfield(cfg, 'threshold'),     cfg.threshold = 0.5;     end % relative
if ~isfield(cfg, 'numvertices'),   cfg.numvertices = [];    end % approximate number of vertices in sphere

% the data is specified as input variable or input file
hasmri = exist('mri', 'var');

if hasmri
  headmodel.bnd = ft_prepare_mesh(cfg, mri);
else
  headmodel.bnd = ft_prepare_mesh(cfg);
end

headmodel.type = 'singleshell';

% ensure that the geometrical units are specified
headmodel = ft_determine_units(headmodel);

% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug

ft_postamble previous   mri
ft_postamble provenance headmodel
ft_postamble history    headmodel


%% intesselation
% Below is a demonstration of the features of the |intesselation| function

%%
clear; close all; clc;

%% Syntax
% |L=intesselation(X,TES,XI);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function polycz() % autogenerated function wrapper
    % crosssel.m                      Alexander Allmann
    % function to select earthquakes in a cross-section and make them the
    % current catalog in the main map windo
    %
    %
    % turned into function by Celso G Reyes 2017

    ZG=ZmapGlobal.Data; % used by get_zmap_globals

    global newa

    report_this_filefun(mfilename('fullpath'));

    figNumber=findobj('Type','Figure','-and','Name','Z-Value-Cross-section');

    figure(figNumber);

    ax=findobj(gcf,'Tag','mainmap_ax');
    [x,y, mouse_points_overlay] = select_polygon(ax);

    hold on
    plot(x,y,'b-');
    YI = -newa.Depth;          % this substitution just to make equation below simple
    XI = newa(:,end);
    lb = polygon_filter(x,y, XI, YI, 'inside');

    %plot the selected eqs and mag freq curve
    ZG.newt2 = newa.subset(lb);
    newcat = newa.subset(lb);
    pl = plot(ZG.newt2(:,length(ZG.newt2.subset(1))),-ZG.newt2.Depth,'xk'); %FIXME huh? what are they trying to do? looks like indexing are mixed up
    set(pl,'MarkerSize',8, 'LineWidth',1)
    timeplot()
end


function fpalm_render(handles, h)
    outpath = get(handles.out_dir_edit, 'String'); %load output path from the edit box
    if outpath(length(outpath))~='\'
        outpath = [outpath,'\'];
    end

    mat_file = getappdata(0,'temp_runtime');

    warning off MATLAB:load:variableNotFound    %No need to warn if one isnt found, this is taken care of below
                                                %In addition, depending on
                                                %what calls this function, some of these variables may not yet exist anyway
    load(mat_file,'xf_all','yf_all','a0_all','total_molecules','file_info',...
                  'w','preview','plot1','x_size','y_size','iprod_thresh',...
                  'threshold','upper_threshold','n_bright_pixel_threshold', ...
                  'max_pixels_above_threshold','base_name','rbox');
    warning on MATLAB:load:variableNotFound     %Return warning to its original state

%---------------
%Added for backward compatability (changes in naming mechanism)
    if exist('file_info','var')
        if ~isfield(file_info,'part_name')
            load(mat_file,'base_name');
            file_info.part_name = base_name;
        end

        if ~isfield(file_info,'start')
            load(mat_file,'n_start');
            file_info.start = n_start;
        end

        if ~isfield(file_info,'stop')
            load(mat_file,'n_end');
            file_info.stop = n_end;
        end
    else
            load(mat_file,'base_name','n_end','n_start');
            file_info.part_name = base_name;
            file_info.start = n_start;
            file_info.stop = n_end;
    end
%----------------

    if isappdata(0,'from_mat_file')   %If not being called by einzelreader.m, create new waitbar instead of updating
        preview = 0;
        w = waitbarxmod(0,'Executing "fpalm render einzelreader.m" ...','CreateCancelBtn','delete(gcf)');
        set(w,'Name','Progress Bar');
        uicontrol('Style','pushbutton','Parent',w,'String','Pause','Position',[210,10,60,23], ...
                  'UserData',1,'Callback',@pause_gui);
        pause(.1); %Pause to ensure window completes drawing
        drawnow;    %Draw the extra button immediately
        keepontop('Progress Bar');
    else
        waitbarxmod(0,w,'Executing "fpalm render einzelreader.m" ...');   %rename the waitbar
    end

    if ~exist('a0_all','var') && preview  %If einzelreader.m hasn't found anything, return with no calculations
        return
    elseif ~exist('a0_all','var') && ~preview
        delete(w);
        error('No molecules found.');
    end

    sb     = get(handles.sb,'Value');
    sbloc  = str2num(get(handles.sb_loc,'String')); %str2num must be used here, nonscalar
    x0_bar = sbloc(1); %coordinates of scale bar
    y0_bar = sbloc(2);

    q      = str2double(get(handles.cam_pix_edit,'String'));  % pixel size in microns
    exf    = str2double(get(handles.exf_edit,'String')); %expansion factor
    bkgn   = str2double(get(handles.bkgn_noise,'String')); % background noise in photons
    ppp    = str2double(get(handles.pix_to_pho,'String'));

    NA     = str2double(get(handles.NA,'String'));
    wvlnth = str2double(get(handles.wvlnth,'String'))/1000; %Conversion to um
    psf_scale = str2double(get(handles.psf_scale_edit,'String'));

    r0 = psf_scale*0.55*wvlnth/NA/1.17; % 1/e2 radius of PSF, use 1/e2 = FWHM/1.17 from Pawley
                                  % scaled (20% for "real objective" due to
                                  % measured PSF from Hess and Webb 2002)
    psf_std=r0/2; %standard deviation of psf

    ishif=str2double(get(handles.ishift,'String'));
    jshif=str2double(get(handles.jshift,'String'));
    xw_render=str2double(get(handles.xw_render_edit,'String'));
    yw_render=str2double(get(handles.yw_render_edit,'String'));

    if xw_render ~= 0
        xw=xw_render;
    else
        xw=x_size;
    end
    if yw_render ~= 0
        yw=yw_render;
    else
        yw=y_size;
    end

    r0pix=r0/q; %1/e^2 radius of psf in pixels
    psf_w02=r0pix*r0pix;

    [xpix,ypix] = meshgrid(-rbox:rbox,-rbox:rbox);
    yfit=exp(-2*((xpix).*(xpix)+(ypix).*(ypix))/psf_w02);
    npix=sum(sum(yfit));     % area of molecule in square pixels

    a0_phot=a0_all/ppp;    % peak amplitude of each molecule in photons
    N=npix*a0_phot;        % number of photons for each molecule

    lp2=((psf_std^2)+(q^2)/12)*1./N+8*pi*(psf_std^4)*(bkgn^2)/(q^2)*1./(N.*N);
    lp=sqrt(lp2);
    lppix=lp/q*exf;   % width of each molecule in pixels, based on localization-uncertainty
    lp2pix=lppix.*lppix;

    xf=exf*(xf_all-ishif-0.5);
    yf=exf*(yf_all-jshif-0.5);
    xc=uint16(xf);
    yc=uint16(yf);

    nstart=1;
    nend=total_molecules;
    render_func;

    maxintens=max(max(impts));
    impts = impts/maxintens;

    if sb %draw scale bar if selected
        um1=1/q*exf;
        um1_round=round(um1);
        bar_width=12;

        for i=1:um1_round
            for j=1:bar_width
                xi=i+x0_bar;
                yi=j+y0_bar;
                impts(yi,xi)=1;
            end
        end

        nm250=0.25/q*exf;
        nm250_round=round(nm250);
        bar_width=4;
        y0_bar=y0_bar+bar_width;

        for i=1:um1_round
            for j=1:bar_width
                ival=round(i/nm250_round);
                ival=mod(ival,2);

                xi=i+x0_bar;
                yi=j+y0_bar;
                impts(yi,xi)=double(ival);
            end
        end
    end

    if preview
        set(0,'CurrentFigure',h);
        set(h,'CurrentAxes',plot1);
        imagesc(impts,'HitTest','off') %to look at pts only
        colormap gray
        axis image;
        title(['FPALM Image: Total Molecules:',num2str(total_molecules)])
        set(plot1, 'ButtonDownFcn', {@focus_swap,guidata(gcbo)});
    else
        figure('Name','Final Image')
        imagesc(impts)
        colormap gray
        axis image;
        title(['FPALM Image: Total Molecules:',num2str(total_molecules)])
        delete(w);
    end

    if isappdata(0,'Save')
        if getappdata(0,'Save')
            if (file_info.part_name(length(file_info.part_name)) == '_') %Avoid saving with repeat seperators
                if get(handles.adv_cb,'Value')
                    impts_gray_file=[outpath,'\',file_info.part_name,'pts_',num2str(file_info.start),'-',num2str(file_info.stop),'_t',num2str(iprod_thresh),'-',num2str(threshold),'-',num2str(upper_threshold),'_npt',num2str(n_bright_pixel_threshold),'-',num2str(max_pixels_above_threshold),'_e',num2str(exf),'.tif'];
                else
                    impts_gray_file=[outpath,'\',file_info.part_name,'pts_',num2str(file_info.start),'-',num2str(file_info.stop),'_t',num2str(iprod_thresh),'_e',num2str(exf),'.tif'];
                end
            else
                if get(handles.adv_cb,'Value')
                    impts_gray_file=[outpath,'\',file_info.part_name,'_pts_',num2str(file_info.start),'-',num2str(file_info.stop),'_t',num2str(iprod_thresh),'-',num2str(threshold),'-',num2str(upper_threshold),'_npt',num2str(n_bright_pixel_threshold),'-',num2str(max_pixels_above_threshold),'_e',num2str(exf),'.tif'];
                else
                    impts_gray_file=[outpath,'\',file_info.part_name,'_pts_',num2str(file_info.start),'-',num2str(file_info.stop),'_t',num2str(iprod_thresh),'_e',num2str(exf),'.tif'];
                end
            end
            imwrite(uint8(impts*255),impts_gray_file,'Compression','none');
            rmappdata(0,'Save');

            if get(handles.oc_wf,'Value') %save widefield image if selected
                load(mat_file, 'image_sum');
                if (file_info.part_name(length(file_info.part_name)) == '_') %Avoid saving with repeated seperators
                    wf_file = [outpath,'\',file_info.part_name,'wf.tif'];
                else
                    wf_file = [outpath,'\',file_info.part_name,'_wf.tif'];
                end
                imwrite(uint8((image_sum/max(image_sum(:)))*255),wf_file,'Compression','none');
            end

            if get(handles.oc_hist,'Value') %show photon histogram of complete image
                lp_min = min(lp)*1000;
                lp_max = max(lp)*1000;
                n_bins=round(2*total_molecules^(1/3));
                bins=linspace(lp_min,lp_max,n_bins);

                figure
                hist(lp*1000,bins);
                ylabel('Frequency');
                xlabel('Localization Precision (nm)');
            end
        end
    end


function autoTrainRFC(varargin)
%AUTOTRAINRFC trains a RandomForestClassifier (RFC)
%based on CCDC change detection results and an land cover reference image.
%
% Specific parameters
% ------------------------
%   'SampleImage'        A reference image with '.hdr' format. *REQUIRED.
%                        Note Do not input '.hdr'. For example, if your
%                        sample file name is 'your_path/sample.hdr', you
%                        should input 'your_path/sample'.
%
%   'SampleYear'         The year of the reference data. *REQUIRED.
%   'SampleNumber'       Total number of training samples. Default is
%                        20,000
%   'NTrees'             Number of trees grown. Default is 500.
%   'CCDCDir'           Directory of CCDC change detection results.
%                       Default is the path to current folder.
%
% For example
% autoTrainRFC('SampleImage','\\Mac\Home\Desktop\CCDCTest\13633','SampleYear' ,2000)
%
% History
% ------------------------
% CCDC 1.3 version - Zhe Zhu, EROS, USGS
%
% Revisions: $ Date: 11/25/2015 $ Copyright: Zhe Zhu
% Version 1.3  Select sample based on best strategy (06/30/2015)
% Version 1.2  Only use undisturbed data (05/11/2015)
% Version 1.1  Use version 7.3 for storing RF model (01/10/2015)
% Version 1.0  Fixed a bug in picking the wrong pixel for training (11/08/2014)
%
% Author: Zhe Zhu (zhe.zhu#ttu.edu)
%         Shi Qiu (shi.qiu#ttu.edu)
% Date: 28. Jun, 2018

    %% get parameters from inputs
    % defaults
    % version of CCDC
    ccdc_v = 1.3;
    % where the all CCDC change detection results are
    ccdc_dir = pwd;
    % number of trees grown.
    ntrees = 500;
    % request the user's inputs
    p = inputParser;
    p.FunctionName = 'trainParas';
    % optional
    % default values.
    addParameter(p,'CCDCDir',ccdc_dir);
    addParameter(p,'SampleImage','');
    addParameter(p,'SampleYear','');
    addParameter(p,'SampleNumber','');
    addParameter(p,'NTrees',ntrees);

    parse(p,varargin{:});
    ccdc_dir = p.Results.CCDCDir;
    dir_out = ccdc_dir;

    % number of trees grown.
    ntrees = p.Results.NTrees;

    name_roi = p.Results.SampleImage;

    if isempty(name_roi)
        fprintf('Please input a reference image''s path\r\n');
    end

    trn_year =  p.Results.SampleYear;
    if isempty(trn_year)
        fprintf('Please input the year the reference data presents \r\n');
    end
    num_tot = p.Results.SampleNumber;
    if isempty(num_tot)
        num_tot = 20000;
        fprintf('Total number of samples are %d (default) \r\n',num_tot);
    else
        fprintf('Total number of samples are %d \r\n',num_tot);
    end

    %% Prepare for the inputs
    % get image parameters automatically
    imf=dir(fullfile(ccdc_dir,'L*')); % folder names
    [nrows,ncols,nbands] = autoPara(imf);

    % 2. ground truth time interval
    gt_start = datenum(trn_year,1,1);
    gt_end = datenum(trn_year,12,31);

    % Constants:
    % number of coefficients
    num_c = 8;
    jiDim = [ncols,nrows];

    % use the Trends

    im_roi = enviread(name_roi); % Land Cover Trends data (all pixels)

    % transformed to Matlab dimension (opposite in x & y)
    tim_roi = im_roi';
    clear im_roi;

    % Find nonzero ids with 1 2 3
    %                       4 5 6
    idsfind = find(tim_roi > 0);
    [~,i_ids] = ind2sub(jiDim,idsfind);

    % length of roi pixels
    rec_l = length(idsfind);
%                 rec_l = 1000;
    % Get Training data prepared
    % the training data is NxD and labels are Nx1, where N=#of
    % examples, D=# of features
    % intialize maximum Xs and Ys
    X = zeros(rec_l,(num_c+1)*(nbands-1)); % 7 bands cft & rmse
    Y = zeros(rec_l,1); % Trends classes + location

    % Get into the TSFitMap folder
    name_rst = 'TSFitMap';
    tsfitmap_path = fullfile(ccdc_dir,name_rst);
    % cd(v_input.name_rst);
    % intiate i_row
    i_row = -1;
    % number of pixels for traning
    plusid = 0;

% %     for i=1:rec_l
    for i=1:rec_l
        % Just load once for a line of rec_cg for all reference within this line
        if i_ids(i) ~= i_row

            fprintf('Processing the %dth row ...\n',i_row);

            % load CCDCRec
            load(fullfile(tsfitmap_path,['record_change',num2str(i_ids(i))]));

            % matrix of each component
% %             try % sometimes the line record has no fields.
            t_start = [rec_cg.t_start];
            t_end = [rec_cg.t_end];
            coefs = [rec_cg.coefs];
            rmse = [rec_cg.rmse];
            pos = [rec_cg.pos];
            categ = [rec_cg.category];
            % reshape coefs
            coefs = reshape(coefs,num_c,nbands-1,[]);
        end

        % find the curve within a fixed time interval
        ids_line = find(pos == idsfind(i));

        for j = 1:length(ids_line)
            % id of reference data
            id_ref = ids_line(j);
            % position of reference data
            pos_ref = pos(id_ref);

            % take curves that fall witin the training period
            % remove curves that are changed within training period
            if t_start(id_ref) < gt_start & t_end(id_ref) > gt_end
                % number of time series model for training
                plusid = plusid + 1;

                % two way of overall reflectance
                tmp_cft = coefs(:,:,id_ref);
                % temporal overall ref
                % tmp_cft(1,:) = tmp_cft(1,:)+gt_mid*tmp_cft(2,:);
                tmp_cft(1,:) = tmp_cft(1,:) + 0.5*(t_start(id_ref)+t_end(id_ref))*tmp_cft(2,:);

                % all rmse
                tmp_rmse = rmse(:,id_ref);

                % prepare Xs
                X(plusid,:) = [tmp_rmse;tmp_cft(:)];
                Y(plusid) = tim_roi(pos_ref); % class category
            end
        end
        i_row = i_ids(i);
    end

    % remove out of boundary or changed pixels
    X = X(1:plusid,:);
    Y = Y(1:plusid);

    % make sure they are double!
    Y = double(Y);
    X = double(X);

% %                 % cd to the images folder
% %                 cd(l_dir);

    %% selecting pixels for training
    % number of variables
    x_dim = size(X,2);

    % update class number
    all_class = unique(Y);
    % update number of class
    n_class = length(all_class);
    % calculate proportion based # for each class
    prct = hist(Y(:,1),all_class);
    prct = prct/sum(prct);

    % number of reference for euqal number training
    eq_num = num_tot; % total #
    n_min = round(0.03*num_tot); % minimum #
    n_max = round(0.4*num_tot); % maximum #

    % intialized selected X & Y training data
    sel_X_trn = [];
    sel_Y_trn = [];

    for i_class = 1:n_class
        % find ids for each land cover class
        ids = find(Y == all_class(i_class));
        % total # of reference pixels for permute
        tmp_N = length(ids);

        % random permute the reference pixels
        tmp_rv = randperm(tmp_N);

        % adjust num_prop based on proportion
        adj_num = ceil(eq_num*prct(i_class));

        % adjust num_prop based on min and max
        if adj_num < n_min
            adj_num = n_min;
        elseif adj_num > n_max
            adj_num = n_max;
        end

        if tmp_N > adj_num
            % if tmp_N > adj_num, use adj_num, otherwise, use tmp_N
            tot_n = adj_num;
        else
            tot_n = tmp_N;
        end

        % permutted ids
        rnd_ids = ids(tmp_rv(1:tot_n));

        % X_trn and Y_trn
        sel_X_trn = [sel_X_trn; X(rnd_ids,:)];
        sel_Y_trn = [sel_Y_trn; Y(rnd_ids)];
    end

    % log for CCDC Train paramters and versions
    % report only for the first task
    class_value = unique(sel_Y_trn);
    class_number = hist(sel_Y_trn,class_value);

    fileID = fopen(fullfile(ccdc_dir, 'CCDC_Train_log.txt'),'w');
    % write location of image stack
    fprintf(fileID,'Image location = %s\r\n',ccdc_dir);
    % write number of images used
    fprintf(fileID,'Number of sample = %d\r\n',sum(class_number));
    % write number of images used
    fprintf(fileID,'Minimum number of sample per class = %d\r\n',min(class_number));
    % write number of images used
    fprintf(fileID,'Maximum number of sample per class = %d\r\n',max(class_number));
    % CCDC Version
    fprintf(fileID,'CCDC Train Version = %.2f\r\n',ccdc_v);
    % updates
    fprintf(fileID,'******************************************************************************************************\r\n');
    fprintf(fileID,'Revisions: $ Date: 11/20/2015 $ Copyright: Zhe Zhu\r\n');
    fprintf(fileID,'Version 1.3   Select sample based on best strategy (06/30/2015)\r\n');
    fprintf(fileID,'Version 1.2   Only use undisturbed data (05/11/2015)\r\n');
    fprintf(fileID,'Version 1.1   Use version 7.3 for storing RF model (01/10/2015) \r\n');
    fprintf(fileID,'Version 1.0   Fixed a bug in picking the wrong pixel for training (11/08/2014)\r\n');
    fprintf(fileID,'******************************************************************************************************\r\n');
    fclose(fileID);

    modelRF = classRF_train(sel_X_trn,sel_Y_trn,ntrees);
    save(fullfile(dir_out,'modelRF'),'modelRF','-v7.3');

    fprintf('Finishined Training! The model can be found at %s\r\n',dir_out);
end


function class_info=gen_class_info_ade()

class_info_ADE=load('class_info_ADE.mat');
class_info_ADE=class_info_ADE.class_info_ADE;

class_names=class_info_ADE.Name;
assert(size(class_names, 2)==1);
class_names=cat(1, {'void'}, class_names);

class_label_values=uint8([0 1:150]);

class_info=[];

class_info.class_names = class_names;

class_info.class_label_values=class_label_values;
class_info.background_label_value=uint8(1);
class_info.void_label_values=uint8(0);

% addpath ../libs/VOCdevkit_2012/VOCcode
class_info.mask_cmap = VOClabelcolormap(256);

class_info=process_class_info(class_info);

end


function animacion

global p1 p2 p3 p4 p5 p6 p7 p1aux p2aux

global TD_gripper
global robot

p1=[[1.2254, 1.1375, 1.3],[0.0000, -0.0027, -1.0000, -0.0000], [0, 0, 0, 0], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];
p1aux=[[1.2254, 1.1375, 1.3],[0.0000, -0.0027, -1.0000, -0.0000], [0, 0, 0, 0], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];
p2=[[1.1254, 1.975, 1.2],[0.0000, -0.0027, -1.0000, -0.0000], [0, 0, 0, 0], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];
p2aux=[[1.1254, 1.975, 1.3],[0.0000, -0.0027, -1.0000, -0.0000], [0, 0, 0, 0], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];
p3=[[2.2500, -0.150, 0.080],[0.0000, 1.0000, 0.0000, 0.0000], [0, 0, 0, 0], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];
p4=[[1.5000, -0.150, 0.080],[0.0000, 1.0000, 0.0000, 0.0000], [0, 0, 0, 0], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];
p5=[[1, -1.5, 1.3],[0.0000, -0.6946, 0.7194, 0.0000], [0, 0, 0, 0], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];
p6=[[0.05, -1.5, 1.3],[0.0000, -0.6946, 0.7194, 0.0000], [0, 0, 0, 0], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];
p7=[[0.05, -1.5, 1.2],[0.0000, -0.6946, 0.7194, 0.0000], [0, 0, 0, 0], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];

robot = load_robot('KUKA','KR120_R3200_PA');
robot.T0 = [1 0 0 0;0 1 0 0;0 0 1 1;0 0 0 1];
robot.graphical.draw_axes=0;
robot.equipment{1} = load_robot('equipment/tables','table_big');
robot.equipment{1}.graphical.color = [75 75 75]./255;
robot.equipment{1}.graphical.draw_axes=0;
robot.equipment{1}.T0 = [1 0 0 -0.5;0 1 0 -0.5; 0 0 1 0;0 0 0 1];
robot.tool = load_robot('equipment/end_tools','pallet_gripper');
robot.tool.graphical.draw_axes=0;
robot.equipment{2} = load_robot('equipment','conveyor_belt_2');
robot.equipment{2}.T0 = [0 -1 0 0;1 0 0 2.4; 0 0 1 0; 0 0 0 1];
robot.equipment{2}.graphical.draw_axes=0;
robot.equipment{2}.graphical.color = [1 80 30]./255;
robot.equipment{3} = load_robot('equipment','conveyor_belt_2');
robot.equipment{3}.graphical.color = [1 80 30]./255;
robot.equipment{3}.graphical.draw_axes=0;
robot.equipment{3}.T0 = [1 0 0 0; 0 1 0 -2.4; 0 0 1 0; 0 0 0 1];
robot.equipment{4} = load_robot('equipment/tables','palletizing');
robot.equipment{4}.T0 = [-1 0 0 2.5; 0 -1 0 0; 0 0 1 0; 0 0 0 1];
robot.equipment{4}.graphical.draw_axes=0;
robot.piece{1} = load_robot('equipment/objects','loaded_pallet');
robot.piece{1}.T0 = [0 -1 0 1;1 0 0 2.2;0 0 1 1.23;0 0 0 1];
robot.piece{1}.graphical.draw_axes=0;
robot.piece{1}.graphical.color = [90 70 10]./255;
robot.piece{1}.graphical.draw_transparent=0;
drawrobot3d(robot);

MoveJ(p1,'vmax','z100',TD_gripper, 'wobj0');
MoveJ(p2,'vmax','fine',TD_gripper, 'wobj0');
simulation_grip_piece;
WaitTime(2);
MoveJ(p2aux,'vmax','fine',TD_gripper, 'wobj0');
MoveJ(p1aux,'vmax','z100',TD_gripper, 'wobj0');
MoveJ(p3,'vmax','fine',TD_gripper, 'wobj0');
WaitTime(2);
simulation_release_piece;
MoveJ(p4,'vmax','fine',TD_gripper, 'wobj0');
WaitTime(20);
MoveJ(p3,'vmax','fine',TD_gripper, 'wobj0');
simulation_grip_piece;
WaitTime(2);
MoveJ(p5,'vmax','z100',TD_gripper, 'wobj0');
MoveJ(p6,'vmax','fine',TD_gripper, 'wobj0');
MoveJ(p7,'vmax','fine',TD_gripper, 'wobj0');
simulation_release_piece;
WaitTime(2);
MoveJ(p5,'vmax','z100',TD_gripper, 'wobj0');
end


%PRVERSION PRtools version number
%
%		[VERSION,STR,DATE] = PRVERSION
%
% OUTPUT
%		VERSION   Version number (double)
%		STR				Version number (string)
%		DATE			Version date (string)
%
% DESCRIPTION
% Returns the numerical version number of PRTools VER (e.g. VER = 3.0205)
% and as a string, e.g. STR = '3.2.5'. In DATE, the version date is returned
% as a string.

% $Id: prversion.m,v 1.2 2006/03/08 22:06:58 duin Exp $

function [version,str,date] = prversion(location)

if nargin < 1 % get it locally
	signature = prtver;
	str = signature{1}.Version;
	date = signature{1}.Date;
  version = str2version(str);
	%version   = str2num(str(1)) + (str2num(str(3))*1000 + str2num(str(5))*10)/10000;
	if nargout == 0
		disp([newline '   PRTools version ' str newline])
		clear version
  end
else % location is url
  if verLessThan('matlab','8.0')
    s = ''; % Cannot read if server is down
  else
    [s,status] = urlread(location,'TimeOut',5);
  end
  %s = urlread(location);
  s = [s ' '];                % make sure there is a space
  s = strrep(s,char(10),' '); % replace newline by space
  n = strfind(lower(s),'version');
  nspace = strfind(s,' ');
  str = s(nspace(1)+1:nspace(2)-1);
  version = str2version(str);
  date = s(nspace(2)+1:nspace(3)-1);
end

function version = str2version(str)
n = strfind(str,'.');
if isempty(n)
  version = str2num(str);
elseif length(n) == 1
  version = str2num(str(1:n-1)) + str2num(str(n+1:end))/100;
else
  version = str2num(str(1:n(1)-1)) + str2num(str(n(1)+1:n(2)-1))/100 + str2num(str(n(2)+1:end))/10000;
end
return;


function [infos, auxillary_toolboxes] = tapas_get_toolbox_infos()
	% Function storing information regarding toolboxes.
	%
	% Each toolbox is represented by a field with its lower-case-name.
	% The field has the following subfields:
	%   init_function   [character vector]
	%           If specified, use that function to initialze the toolbox (and do
	%           not anything else apart from adding init_dir to the path).
	%           If not specified, add init_dir and all subfolders
	%   init_dir        [character vector]
	%           If init function is specified; the directory, where it can be
	%           found (has to be added to MATLABPATH to call the function)
	%           If init function is not specified, the root dir of the toolbox,
	%           which (and all subdirs) will be added.
	%   dependencies   [character vector]
	%           Names of dependent toolboxes. Needs to be lower case (the field-
	%           name in the struct). At the moment, we cannot check for depen-
	%           dencies of dependencies, so they should be specified as depen-
	%           dencies as well.
	%   diagnose_files [character vector/cell array of character vectors]
        %           Name(s) of files to be checked by TAPAS_diagnose('toolboxName').
	%
	% muellmat@ethz.ch
	% copyright (C) 2022

	infos = struct();
    %% Order determines init-order: do that by alphabet for main toolboxes
	infos = tapas_default_toolbox_info(infos, 'ceode');

    infos.hgf.init_function = '';
	infos.hgf.init_dir = 'HGF';
	infos.hgf.dependencies = [];
	infos.hgf.diagnose_files = '';

	infos.huge.init_function = 'tapas_huge_compile';
	infos.huge.init_dir = 'huge';
	infos.huge.dependencies = [];
	infos.huge.diagnose_files = '';

	infos.physio.init_dir = strcat('PhysIO',filesep,'code');
	infos.physio.init_function = 'tapas_physio_init';
	infos.physio.dependencies = [];
	infos.physio.diagnose_files = 'tapas_physio_main_create_regressors';

	infos = tapas_default_toolbox_info(infos,'rDCM');

	infos = tapas_default_toolbox_info(infos,'sem');

	infos.uniqc.init_dir = 'UniQC';
	infos.uniqc.init_function = '';
	infos.uniqc.dependencies = [];
	infos.uniqc.diagnose_files = 'tapas_uniqc_demo_fmri_qa'; % in subfolder demo/MrSeries

	%% Auxillary toolboxes:
    infos.external.init_function = '';
	infos.external.init_dir = 'external';
	infos.external.dependencies = '';
	infos.external.diagnose_files = '';

    infos = tapas_default_toolbox_info(infos,'tools'); % Want to have that?

    auxillary_toolboxes = {'external','tools'}; % Just inform - let init decide what to do
end

function infos = tapas_default_toolbox_info(infos,folderName)
    % Setting default toolbox info (no init function, no dependencies).
    fld_name = lower(folderName);
    if ismember(fld_name,fieldnames(infos))
        warning('Infos for toolbox %s already there!\n',fld_name);
    end
    infos.(fld_name).init_function = '';
    infos.(fld_name).init_dir = folderName;
    infos.(fld_name).dependencies = '';
    infos.(fld_name).diagnose_files = '';

end


% TABLE Table.
%    Tables are used to collect heterogeneous data and metadata into a single
%    container.  Tables are suitable for storing column-oriented or tabular data
%    that are often stored as columns in a text file or in a spreadsheet.  Tables
%    can accommodate variables of different types, sizes, units, etc.  They are
%    often used to store experimental data, with rows representing different
%    observations and columns representing different measured variables.
%
%    Use the TABLE constructor to create a table from variables in the MATLAB
%    workspace.  Use the readtable function to create a table by reading data
%    from a text or spreadsheet file.
%
%    The TABLE constructor can also be used to create tables without
%    providing workspace variables, by providing the size and variable
%    types.
%
%    Tables can be subscripted using parentheses much like ordinary numeric
%    arrays, but in addition to numeric and logical indices, you can use a
%    table's variable and row names as indices.  You can access individual
%    variables in a table much like fields in a structure, using dot
%    subscripting.  You can access the contents of one or more variables using
%    brace subscripting.
%
%    Tables can contain different kinds of variables, including numeric, logical,
%    character, categorical, and cell.  However, a table is a different class
%    than the variables that it contains.  For example, even a table that
%    contains only variables that are double arrays cannot be operated on as if
%    it were itself a double array.  However, using dot subscripting, you can
%    operate on a variable in a table as if it were a workspace variable.  Using
%    brace subscripting, you can operate on one or more variables in a table as
%    if they were in a homogeneous array.
%
%    A table T has properties that store metadata such as its variable and row
%    names.  Access or assign to a property using P = T.Properties.PropName or
%    T.Properties.PropName = P, where PropName is one of the following:
%
%    TABLE metadata properties:
%        Description          - A character vector describing the table
%        DimensionNames       - A two-element cell array of character vectors containing names of
%                               the dimensions of the table
%        VariableNames        - A cell array containing names of the variables in the table
%        VariableDescriptions - A cell array of character vectors containing descriptions of the
%                               variables in the table
%        VariableUnits        - A cell array of character vectors containing units for the variables
%                               in table
%        VariableContinuity   - An array containing a matlab.tabular.Continuity value for each table
%                               variable, specifying whether a variable represents continuous or discrete
%                               data values. You can assign 'unset', 'continuous', 'step', or 'event' to
%                               elements of VariableContinuity.
%        RowNames             - A cell array of nonempty, distinct character vectors containing names
%                               of the rows in the table
%        UserData             - A variable containing any additional information associated
%                               with the table.  You can assign any value to this property.
%
%    TABLE methods and functions:
%      Construction and conversion:
%        table              - Create a table from workspace variables.
%        array2table        - Convert homogeneous array to table.
%        cell2table         - Convert cell array to table.
%        struct2table       - Convert structure array to table.
%        table2array        - Convert table to a homogeneous array.
%        table2cell         - Convert table to cell array.
%        table2struct       - Convert table to structure array.
%      Import and export:
%        readtable          - Create a table by reading from a file.
%        writetable         - Write a table to a file.
%        write              - Write a table to a file.
%      Size and shape:
%        istable            - True for tables.
%        size               - Size of a table.
%        width              - Number of variables in a table.
%        height             - Number of rows in a table.
%        ndims              - Number of dimensions of a table.
%        numel              - Number of elements in a table.
%        horzcat            - Horizontal concatenation for tables.
%        vertcat            - Vertical concatenation for tables.
%      Set membership:
%        intersect          - Find rows common to two tables.
%        ismember           - Find rows in one table that occur in another table.
%        setdiff            - Find rows that occur in one table but not in another.
%        setxor             - Find rows that occur in one or the other of two tables, but not both.
%        unique             - Find unique rows in a table.
%        union              - Find rows that occur in either of two tables.
%      Data manipulation and reorganization:
%        summary            - Print summary of a table.
%        addvars            - Insert new variables at a specified location in a table.
%        movevars           - Move table variables to a specified location.
%        removevars         - Delete the specified table variables.
%        splitvars          - Splits multi-column variables into separate variables.
%        mergevars          - Merges multiple variables into one multi-column variable or a nested table.
%        sortrows           - Sort rows of a table.
%        stack              - Stack up data from multiple variables into a single variable.
%        unstack            - Unstack data from a single variable into multiple variables.
%        join               - Merge two tables by matching up rows using key variables.
%        innerjoin          - Inner join between two tables.
%        outerjoin          - Outer join between two tables.
%        rows2vars          - Reorient rows to be variables of output table.
%        inner2outer        - Invert a nested table-in-table hierarchy.
%        ismissing          - Find elements in a table that contain missing values.
%        standardizeMissing - Insert missing data indicators into a table.
%      Computations on tables:
%        varfun             - Apply a function to variables in a table.
%        rowfun             - Apply a function to rows of a table.
%
%    Examples:
%
%       % Create a table from individual workspace variables.
%       load patients
%       patients = table(LastName,Gender,Age,Height,Weight,Smoker,Systolic,Diastolic)
%
%       % Select the rows for patients who smoke, and a subset of the variables.
%       smokers = patients(patients.Smoker == true, {'LastName' 'Gender' 'Systolic' 'Diastolic'})
%
%       % Convert the two blood pressure variables into a single variable.
%       patients.BloodPressure = [patients.Systolic patients.Diastolic];
%       patients(:,{'Systolic' 'Diastolic'}) = []
%
%       % Pick out two specific patients by the LastName variable.
%       patients(ismember(patients.LastName,{'Smith' 'Jones'}), :)
%
%       % Convert the LastName variable into row names.
%       patients.Properties.RowNames = patients.LastName;
%       patients.LastName = []
%
%       % Use the row names to pick out two specific patients.
%       patients({'Smith' 'Jones'},:)
%
%       % Add metadata to the table.
%       patients.Properties.Description = 'Simulated patient data';
%       patients.Properties.VariableUnits =  {''  'Yrs'  'In'  'Lbs'  ''  'mm Hg'};
%       patients.Properties.VariableDescriptions{6} = 'Systolic/Diastolic';
%       summary(patients)
%
%       % Create a new variable in the table from existing variables.
%       patients.BMI = (patients.Weight * 0.453592) ./ (patients.Height * 0.0254).^2
%       patients.Properties.VariableUnits{'BMI'} =  'kg/m^2';
%       patients.Properties.VariableDescriptions{'BMI'} = 'Body Mass Index';
%
%       % Sort the table based on the new variable.
%       sortrows(patients,'BMI')
%
%       % Make a scatter plot of two of the table's variables.
%       plot(patients.Height,patients.Weight,'o')
%
%       % Create tables from text and spreadsheet files
%       patients2 = readtable('patients.dat','ReadRowNames',true)
%       patients3 = readtable('patients.xls','ReadRowNames',true)
%
%       % Create a table from a numeric matrix
%       load tetmesh.mat
%       t = array2table(X,'VariableNames',{'x' 'y' 'z'});
%       plot3(t.x,t.y,t.z,'.')
%
%    See also TABLE, CATEGORICAL
%
%    Reference page in Doc Center
%       doc table
%
%    Other functions named table
%
%       codistributed/table    tall/table
%


function Reaction_time_task_GUI(varargin)
fh = figure('Visible','off', ...
            'HandleVisibility','callback', ...
            'NumberTitle','off', ...  % turns off MATLAB GUI window title
            'Name','Reaction_time_task_GUI', ...    % now, define my own
            'Units','normalized', ...
            'Position',[1.000000e-001 1.000000e-001 6.000000e-001 6.000000e-001], ...
            'Color','white', ...   % match bg of MODE_new.jpg
            'Resize','off');
set(fh,'MenuBar','none');  % removes MATLAB default menu bar
x0 = 0.1; y0 = 0.85;
x0run = 0.825; y0run = 0.075; % lower-left corner coord. of the run button
dxst1 = 0.075; dyst1 = 0.05;  % for static text 1
dxet1 = 0.100; dyet1 = 0.05;  % for edit text 1
dxst2 = 0.400; dyst2 = 0.10;  % for static text 2
dxpb1 = 0.050; dypb1 = 0.05;  % for PDF logo pushbuttons
dxrun = 0.100; dyrun = 0.075; % for "Run" pushbutton
% First, create a Heading for the secondary GUI with a static text box
dx = 0.6; dy = 0.125;
st0h = uicontrol(fh, ...
            'style','text', ...
            'String',['Lateral intraparietal area' char(10) '(Eq. 28, p. 1370: Grossberg & Pilly (2008))'], ...
            'Units','normalized', ...
            'Position',[x0,y0,dx,dy], ...
            'FontSize',12, ...
            'FontWeight','bold');

% Create static box, edit box, static box, logo (that points to a doc; optional)
y0 = y0 - dy*1.05; space = dxst1*0.20;
data.str{1} = 'A9';
data.default{1} = 1.000000;
  st1h(1) = uicontrol(fh,'style','text', ...
      'String','A9', ...
      'Units','normalized', ...
      'Position',[x0,y0,dxst1,dyst1], ...
      'FontSize',10, ...
      'FontWeight','bold');
  et1h(1) = uicontrol(fh,'Style','edit', ...
      'String','1', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+space,y0,dxet1,dyet1], ...
      'FontSize',10, ...
      'FontWeight','normal', ...
      'callback',{@edit1_Callback 'A9'});
  st2h(1) = uicontrol(fh,'style','text', ...
      'String','Parameter that ...', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+space*2,y0-0.02,dxst2,dyst2], ...
      'FontSize',10, ...
      'FontWeight','bold');
  pb1h(1) = uicontrol(fh,'Style','pushbutton', ...
      'String','PDF', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+dxst2+space*3,y0,dxpb1,dypb1], ...
      'FontSize',10, ...
      'FontWeight','bold', ...
      'callback',{@opendoc1_Callback 'A9_heur.pdf'});
  y0 = y0 - max([dyst1 dyst2 dyet1 dypb1])*1.1;
data.str{2} = 'g_f';
data.default{2} = 1.000000;
  st1h(2) = uicontrol(fh,'style','text', ...
      'String','g_f', ...
      'Units','normalized', ...
      'Position',[x0,y0,dxst1,dyst1], ...
      'FontSize',10, ...
      'FontWeight','bold');
  et1h(2) = uicontrol(fh,'Style','edit', ...
      'String','1', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+space,y0,dxet1,dyet1], ...
      'FontSize',10, ...
      'FontWeight','normal', ...
      'callback',{@edit1_Callback 'g_f'});
  st2h(2) = uicontrol(fh,'style','text', ...
      'String','Gain of recurrent self-excitation ...', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+space*2,y0-0.02,dxst2,dyst2], ...
      'FontSize',10, ...
      'FontWeight','bold');
  pb1h(2) = uicontrol(fh,'Style','pushbutton', ...
      'String','PDF', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+dxst2+space*3,y0,dxpb1,dypb1], ...
      'FontSize',10, ...
      'FontWeight','bold', ...
      'callback',{@opendoc1_Callback 'g_f_heur.pdf'});
  y0 = y0 - max([dyst1 dyst2 dyet1 dypb1])*1.1;
data.str{3} = 'g_h';
data.default{3} = 5.000000;
  st1h(3) = uicontrol(fh,'style','text', ...
      'String','g_h', ...
      'Units','normalized', ...
      'Position',[x0,y0,dxst1,dyst1], ...
      'FontSize',10, ...
      'FontWeight','bold');
  et1h(3) = uicontrol(fh,'Style','edit', ...
      'String','5', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+space,y0,dxet1,dyet1], ...
      'FontSize',10, ...
      'FontWeight','normal', ...
      'callback',{@edit1_Callback 'g_h'});
  st2h(3) = uicontrol(fh,'style','text', ...
      'String','Gain of recurrent inhibition ...', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+space*2,y0-0.02,dxst2,dyst2], ...
      'FontSize',10, ...
      'FontWeight','bold');
  pb1h(3) = uicontrol(fh,'Style','pushbutton', ...
      'String','PDF', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+dxst2+space*3,y0,dxpb1,dypb1], ...
      'FontSize',10, ...
      'FontWeight','bold', ...
      'callback',{@opendoc1_Callback 'g_h_heur.pdf'});
  y0 = y0 - max([dyst1 dyst2 dyet1 dypb1])*1.1;
data.str{4} = 'lambda';
data.default{4} = 5.000000;
  st1h(4) = uicontrol(fh,'style','text', ...
      'String','lambda', ...
      'Units','normalized', ...
      'Position',[x0,y0,dxst1,dyst1], ...
      'FontSize',10, ...
      'FontWeight','bold');
  et1h(4) = uicontrol(fh,'Style','edit', ...
      'String','5', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+space,y0,dxet1,dyet1], ...
      'FontSize',10, ...
      'FontWeight','normal', ...
      'callback',{@edit1_Callback 'lambda'});
  st2h(4) = uicontrol(fh,'style','text', ...
      'String','Gain of bottom-up excitation ...', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+space*2,y0-0.02,dxst2,dyst2], ...
      'FontSize',10, ...
      'FontWeight','bold');
  pb1h(4) = uicontrol(fh,'Style','pushbutton', ...
      'String','PDF', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+dxst2+space*3,y0,dxpb1,dypb1], ...
      'FontSize',10, ...
      'FontWeight','bold', ...
      'callback',{@opendoc1_Callback 'lambda_heur.pdf'});
  y0 = y0 - max([dyst1 dyst2 dyet1 dypb1])*1.1;
data.str{5} = 'sigLIP';
data.default{5} = 5.000000;
  st1h(5) = uicontrol(fh,'style','text', ...
      'String','sigLIP', ...
      'Units','normalized', ...
      'Position',[x0,y0,dxst1,dyst1], ...
      'FontSize',10, ...
      'FontWeight','bold');
  et1h(5) = uicontrol(fh,'Style','edit', ...
      'String','5', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+space,y0,dxet1,dyet1], ...
      'FontSize',10, ...
      'FontWeight','normal', ...
      'callback',{@edit1_Callback 'sigLIP'});
  st2h(5) = uicontrol(fh,'style','text', ...
      'String','Gain of recurrent ...', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+space*2,y0-0.02,dxst2,dyst2], ...
      'FontSize',10, ...
      'FontWeight','bold');
  pb1h(5) = uicontrol(fh,'Style','pushbutton', ...
      'String','PDF', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+dxst2+space*3,y0,dxpb1,dypb1], ...
      'FontSize',10, ...
      'FontWeight','bold', ...
      'callback',{@opendoc1_Callback 'sigLIP_heur.pdf'});
  y0 = y0 - max([dyst1 dyst2 dyet1 dypb1])*1.1;
data.str{6} = 'Tdec';
data.default{6} = 55.000000;
  st1h(6) = uicontrol(fh,'style','text', ...
      'String','Tdec', ...
      'Units','normalized', ...
      'Position',[x0,y0,dxst1,dyst1], ...
      'FontSize',10, ...
      'FontWeight','bold');
  et1h(6) = uicontrol(fh,'Style','edit', ...
      'String','55', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+space,y0,dxet1,dyet1], ...
      'FontSize',10, ...
      'FontWeight','normal', ...
      'callback',{@edit1_Callback 'Tdec'});
  st2h(6) = uicontrol(fh,'style','text', ...
      'String','Threshold LIP ...', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+space*2,y0-0.02,dxst2,dyst2], ...
      'FontSize',10, ...
      'FontWeight','bold');
  pb1h(6) = uicontrol(fh,'Style','pushbutton', ...
      'String','PDF', ...
      'Units','normalized', ...
      'Position',[x0+dxst1+dxet1+dxst2+space*3,y0,dxpb1,dypb1], ...
      'FontSize',10, ...
      'FontWeight','bold', ...
      'callback',{@opendoc1_Callback 'Tdec_heur.pdf'});
  y0 = y0 - max([dyst1 dyst2 dyet1 dypb1])*1.1;
% save the edit text handles to data
data.et1h = et1h(1:end);
for i=1:size(data.str,1)
   eval(['data.' data.str{i} '= data.default{i};']);
end
data.guiName = 'Reaction_time_task_GUI';
setappdata(fh, 'myData', data);
%align(st0h,'HorizontalAlignment','center');
st3h = uicontrol(fh,'style','text', ...
      'String','After changing each parameter, press "Enter".', ...
      'Units','normalized', ...
      'Position',[0.05,0.08,0.60,0.05], ...
      'HorizontalAlignment','Left', ...
      'foregroundColor',[1 0 0], ...
      'FontSize',10, ...
      'FontWeight','bold');
st4h = uicontrol(fh,'style','text', ...
      'String','To see each parameter heuristic, please click on the PDF logo.', ...
      'Units','normalized', ...
      'Position',[0.05,0.02,0.60,0.05], ...
      'HorizontalAlignment','Left', ...
      'foregroundColor',[1 0 0], ...
      'FontSize',10, ...
      'FontWeight','bold');

runh = uicontrol(fh,'Style','pushbutton', ...
      'String','RUN', ...
      'Units','normalized', ...
      'Position',[x0run,y0run,dxrun,dyrun], ...
      'FontSize',12, ...
      'FontWeight','bold', ...
      'callback',{@run1_Callback 'RTtasknew(A9,g_f,g_h,lambda,sigLIP,Tdec)'});
PDFbuttons(pb1h);

etbgcolor = get(et1h(1),'BackgroundColor');
set(fh,'Color',etbgcolor);
set(fh,'Visible','on');

function opendoc1_Callback(hObject,eventdata,varargin)
% hObject    handle to Exit_menu_item (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
open(varargin{1});

function edit1_Callback(hObject, eventdata, varargin)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double

fh = get(hObject,'parent');
data = getappdata(fh, 'myData');
value = str2num(get(hObject,'String'));
eval(['data.' varargin{1} '= value;']);
setappdata(fh,'myData',data);

function run1_Callback(hObject, eventdata, varargin)
% hObject    handle to run1_Callback
% eventdata  reserved - to be defined in a future version of MATLAB
% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double
fh = get(hObject,'parent');
data = getappdata(fh, 'myData');
for i=1:length(data.str)
   eval([data.str{i} '= data.' data.str{i} ';']);  % e.g., A9 = data.A9;
end
% Prevent user from changing the contents of edit boxes
editBoxEnable2(data,'Off');
old_color=get(hObject,'BackgroundColor'); % save original button color
set(hObject, 'BackgroundColor', [1 0 0]); % Change button color
set(hObject, 'String', 'running ...');
% open('RTcaption.pdf');
drawnow    % to make sure that the "Run" button change color right away
eval(varargin{1})   % run the m-file specified by varargin{1}
set(hObject, 'String', 'Run');
set(hObject, 'BackgroundColor', old_color);
editBoxEnable2(data,'On');


function Y=repmat(varargin)
%REPMAT (overloaded)

Y = varargin{1};
dim = Y.dim;
resize = [varargin{2:end}];
index = (1:size(Y.basis,1))';
index = reshape(index,Y.dim);
index = repmat(index,resize);
Y.basis = Y.basis(index(:),:);
Y.dim = size(index);
% Reset info about conic terms
Y.conicinfo = [0 0];


function CLim= visutil_unifyCLim(h, CLim)
%VISUTIL_UNIFYCLIM - Unify the CLim in all axes pointed to by handles h or
% in the current figure if no handles are given
%
%Synopsis:
% CLIM= visutil_unifyCLim
% CLIM= visutil_unifyCLim(H)
% CLIM= visutil_unifyCLim(H, CLIM)
%
%Input:
% H: List of axis handles
% CLIM: CLim value to set, otherwise the color limit range among all axes
%       taken

% blanker@cs.tu-berlin.de, 09/2009

if ~exist('h','var') || isempty(h),
  h= get(gcf, 'children');
end
hax= findobj(h, 'Type','axes', 'Tag','');
if ~exist('CLim','var') || isempty(CLim)
    for hi= 1:length(hax),
        cl(hi,:)= get(hax(hi), 'CLim');
    end
    CLim= [min(cl(:,1)) max(cl(:,2))];
end
set(hax, 'CLim', CLim);


% eeg_mergechan() - merge channel structure while preserving channel
%                   order
%
% >> mergelocs = eeg_mergechan(locs1, locs2);
%
% Inputs:
%     locs1     - EEGLAB channel location structure
%     locs2     - second EEGLAB channel location structure
%
% Output:
%     mergelocs - merged channel location structure
%
% Author: Arnaud Delorme, August 2006

% Copyright (C) Arnaud Delorme, CERCO, 2006, arno@salk.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

% union of two channel location structure
% without loosing the order information
% ---------------------------------------
function alllocs = myunion(locs1, locs2)

   labs1 = { locs1.labels };
   labs2 = { locs2.labels };

   count1 = 1;
   count2 = 1;
   count3 = 1;
   alllocs = locs1; alllocs(:) = [];
   while count1 <= length(locs1) | count2 <= length(locs2)

       if count1 > length(locs1)
           alllocs(count3) = locs2(count2);
           count2 = count2 + 1;
           count3 = count3 + 1;
       elseif count2 > length(locs2)
           alllocs(count3) = locs1(count1);
           count1 = count1 + 1;
           count3 = count3 + 1;
       elseif strcmpi(labs1{count1}, labs2{count2})
           alllocs(count3) = locs1(count1);
           count1 = count1 + 1;
           count2 = count2 + 1;
           count3 = count3 + 1;
       elseif isempty(strmatch(labs1{count1}, labs2))
           alllocs(count3) = locs1(count1);
           count1 = count1 + 1;
           count3 = count3 + 1;
       else
           alllocs(count3) = locs2(count2);
           count2 = count2 + 1;
           count3 = count3 + 1;
       end;

   end;


function [success] = viewLineFilledError(inputMean,inputStd,varargin)
	% Makes solid error bars around line.
	% Biafra Ahanonu
	% started: 2014.01.03 [19:13:01]
	% inputs
		% inputMean - Vector [1 timePoints] of y mean for each value of
		% inputStd - Vector [1 timePoints] indicating the std or SEM at each time point in inputMean
	% outputs
		% success - Binary 1 = ran without errors, 0 = encountered errors

	[success] = ciapkg.view.viewLineFilledError(inputMean,inputStd,'passArgs', varargin);
end


function bool = gsp_check_fourier(G)
%GSP_CHECK_FOURIER Check is the Fourier basis is computed
%   Usage:  bool = gsp_check_fourier(G):
%
%   Input parameters:
%       G           : Graph structure
%   Output parameters:
%       bool        : boolean
%
%   This function check is the Laplacian eigenvalues and eigenfunctions are
%   computed.
%

bool = ( isfield(G,'e') && isfield(G,'U') );

end


%kfunction ' '
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros function.pane file
%
% Parameters:
% String: expr 'f(w,h,d,t,e) =', default: 'w + h': 'function expression'
% Integer: wsize ' ', default: 350: 'Width size of value data'
% Integer: hsize ' ', default: 350: 'Height size of value data'
% Integer: dsize ' ', default: 1: 'Depth size of value data'
% Integer: tsize ' ', default: 1: 'Time size of value data'
% Integer: esize ' ', default: 1: 'Elements size of value data'
%
% Example: kfunction( {'expr','w + h';'wsize',350;'hsize',350;'dsize',1;'tsize',1;'esize',1})
%
% Khoros helpfile follows below:

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

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


function mv = mv_reorderCondNums(mv,newOrder);
%
% mv = mv_reorderCondNums(mv,[newOrder]);
%
% Specify a new order for non-null conditions.
% If not specified, will pop up a UI.
%
%
%
% ras 03/05.
if notDefined('mv'),    mv = get(gcf,'UserData');		end
if ishandle(mv),		mv = get(mv, 'UserData');		end

if notDefined('newOrder')
    % put up a dialog
    nums = mv.trials.condNums;
    names = mv.trials.condNames;
    def = {num2str(nums)};
    prompt{1} = 'New Condition # Order [Current Order: ';
    for i = 1:length(names)
        prompt{1} = [prompt{1} num2str(nums(i)) ') ' names{i} ' '];
    end
    prompt{1} = [prompt{1} ']'];
	dlgTitle='Reorder Conditions';
	answer=inputdlg(prompt,dlgTitle,1,def);
    newOrder = str2num(answer{1});
end

% if the null isn't included, put it first:
if ~ismember(newOrder, 0)
	newOrder = [0 newOrder];
end

%% need to actually change the condition numbers in the event
%% specification...tricky...
% first, make all the conditions negative. We don't allow negative
% condition specification, so these won't be confused in the shuffling
mv.trials.cond = -(mv.trials.cond + 1); % null is -1, down from there

% now, map each original value to the new value
for c = 1:length(newOrder)
	I = find(mv.trials.cond == -c);
	mv.trials.cond(I) = newOrder(c);
end

% get the indexing needed to produce this
% new order:
% [ignore ind] = sort(newOrder);
newOrder = newOrder + 1; % just account for null

% now change the labels, colors emv.
mv.trials.condNums = mv.trials.condNums(newOrder);
mv.trials.condNames = mv.trials.condNames(newOrder);
mv.trials.condColors = mv.trials.condColors(newOrder);

set(gcf,'UserData',mv);

multiVoxelUI;

return


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
%==============================================================================
%
%
% KERNEL/TOOLS
%
% Contents of FAIR TOOLS
%
%   contents.m          this file
%   dealOptions.m       deals persistent options for use in main modules
%   reportStatus.m      reports the current setting of the toolbox
%
%   testFAIR.m          tests the complete FAIR toolbox
%   testTools.m         test the kernel/tools folder
%
%   FAIRtestPara.m      handles the variables used for testings
%   testEnd.m           finishes    the testing environment
%
%   FAIRcheckFolder.m   generates list of files to be tested
%   FAIRcheckFiles.m    checks all files from a list
%   FAIRmake.m          convenient way of calling the matlab mex compiler
%   FAIRcell2struct.m   converts cell to struct and vice versa
%   FAIRmessage.m       generates nice message
%   FAIRinput.m         input, disabled in the testing framework
%   FAIRpause.m         pause, disabled in the testing framework
%   FAIRpath.m          shortcut to the root of the toolbox
%==============================================================================

function debit = contents
if nargout == 0, help(mfilename); return; end;

debit = {
  'contents.m'
  'dealOptions.m'
  'reportStatus.m'

  'testFAIR.m'
  'testTools.m'

  'FAIRtestPara.m'
  'testEnd.m'

  'FAIRcheckFolder.m'
  'FAIRcheckFiles.m'
  'FAIRmake.m'

  'FAIRcell2struct.m'
  'FAIRmessage.m'
  'FAIRinput.m'
  'FAIRpause.m'
  'FAIRpath.m'

};
%==============================================================================


function hout=suptitle(str)
%suptitle puts a title above all subplots.
%
% suptitle('text') adds text to the top of the figure above all subplots.

% Amount of the figure window devoted to subplots
plotregion = .92;

% Y position of title in normalized coordinates
titleypos  = .95;

% Fontsize for supertitle
fs = get(gcf,'defaultaxesfontsize')+4;

% Fudge factor to adjust y spacing between subplots
fudge=1;

haold = gca;
figunits = get(gcf,'units');

% Get the (approximate) difference between full height (plot + title
% + xlabel) and bounding rectangle.

if ~strcmp(figunits,'pixels')
    set(gcf,'units','pixels');
    pos = get(gcf,'position');
    set(gcf,'units',figunits);
else
    pos = get(gcf,'position');
end
ff = (fs-4)*1.27*5/pos(4)*fudge;

% The 5 here reflects about 3 characters of height below
% an axis and 2 above. 1.27 is pixels per point.

% Determine the bounding rectangle for all the plots

h = findobj(gcf,'Type','axes');

oldUnits = get(h, {'Units'});
if ~all(strcmp(oldUnits, 'normalized'))
    % This code is based on normalized units, so we need to temporarily
    % change the axes to normalized units.
    set(h, 'Units', 'normalized');
    cleanup = onCleanup(@()resetUnits(h, oldUnits));
end

max_y=0;
min_y=1;
oldtitle = [];
numAxes = length(h);
thePositions = zeros(numAxes,4);
for i=1:numAxes
    pos=get(h(i),'pos');
    thePositions(i,:) = pos;
    if ~strcmp(get(h(i),'Tag'),'suptitle')
        if pos(2) < min_y
            min_y=pos(2)-ff/5*3;
        end
        if pos(4)+pos(2) > max_y
            max_y=pos(4)+pos(2)+ff/5*2;
        end
    else
        oldtitle = h(i);
    end
end

if max_y > plotregion
    scale = (plotregion-min_y)/(max_y-min_y);
    for i=1:numAxes
        pos = thePositions(i,:);
        pos(2) = (pos(2)-min_y)*scale+min_y;
        pos(4) = pos(4)*scale-(1-scale)*ff/5*3;
        set(h(i),'position',pos);
    end
end

np = get(gcf,'nextplot');
set(gcf,'nextplot','add');
if ~isempty(oldtitle)
    delete(oldtitle);
end
axes('pos',[0 1 1 1],'visible','off','Tag','suptitle');
ht=text(.5,titleypos-1,str);set(ht,'horizontalalignment','center','fontsize',fs);
set(gcf,'nextplot',np);
axes(haold);
if nargout
    hout=ht;
end
end

function resetUnits(h, oldUnits)
    % Reset units on axes object. Note that one of these objects could have
    % been an old supertitle that has since been deleted.
    valid = isgraphics(h);
    set(h(valid), {'Units'}, oldUnits(valid));
end