function varargout = type(varargin)
% TYPE M-file for type.fig
%      TYPE, by itself, creates a new TYPE or raises the existing
%      singleton*.
%
%      H = TYPE returns the handle to a new TYPE or the handle to
%      the existing singleton*.
%
%      TYPE('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in TYPE.M with the given input arguments.
%
%      TYPE('Property','Value',...) creates a new TYPE or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before type_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to type_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

% Copyright 2002-2003 The MathWorks, Inc.

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

% Last Modified by GUIDE v2.5 14-Sep-2005 17:55:01

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @type_OpeningFcn, ...
                   'gui_OutputFcn',  @type_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(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

% --- Executes just before type is made visible.
function type_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 type (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = type_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;

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
close main;
run('..\temp\main')

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
close main
run('..\pre\main')

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
close main
run('..\level\main')

% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
close main
run('..\level\main')


function result = document_cache(context, identifier, fun, varargin)
% document_cache Cache proxy for report generation
%
% Can be used with report context to cache results of a certain function.
%
% Input:
% - context (structure): Report context structure.
% - identifier (string): Caching identifier.
% - fun (handle): Handle to processing function.
% - varargin (cell): Arguments for processing function.
%
% Output:
% - result: Output argument of the processing function.
%
cache_file = fullfile(context.cachedir, sprintf('%s.mat', identifier));

result = {};
if exist(cache_file, 'file')
    load(cache_file);
end;

if isempty(result)

    clear result;

    result = fun(varargin{:});

    save(cache_file, 'result');

end;


function props = propnames(s)

if isstruct(s)
    props = fieldnames(s);
else
    props = properties(s);
end


classdef Data < handle
    properties (Access = public)
        type
    end

    methods
        function obj = Data(type)
            if nargin == 1
                obj.type = type;
            end
        end
    end
end


%kkinsertseg 'Insert Selected Data Segments from Input 1 into Input 2'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kinsertseg.pane file
%
% Parameters:
% InputFile: i1 'Input 1', required: 'Source Input File'
% InputFile: i2 'Input 2', required: 'Destination Input File'
% OutputFile: o 'Output ', required: 'output file'
% Toggle: val 'Value', default: 0: 'If -val flag is selected, operate on Value segment'
% Toggle: map 'Map', default: 0: 'If -map flag is selected, operate on map segment'
% Toggle: mask 'Mask', default: 0: 'If -mask flag is selected, operate on Mask segment'
% Toggle: loc 'Location', default: 0: 'If -loc flag is selected, operate on Location segment'
% Toggle: time 'Time', default: 0: 'If -time flag is selected, operate on Time segment'
%
% Example: o = kkinsertseg({i1, i2}, {'i1','';'i2','';'o','';'val',0;'map',0;'mask',0;'loc',0;'time',0})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kinsertseg - Insert Selected Data Segments from Input 1 into Input 2
%
%  DESCRIPTION
% This program will insert the specified
% segment(s) for the first input object into
% the second input object producing a new
% or output object.  If -segment is
% "Insert All" all the segments and
% their associated attributes will be inserted.
% The -segment parameter can also specify
% multiple segments by typing a string
% containing the segment names separated
% by space(s):
%
%                "segment1 segment2 segment3"
%
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

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

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


function jaabaPerUserDirName=JaabaPerUserSettingsAbsDirName()

if isunix() || ismac()
  settingsDirName=getenv('HOME');
  jaabatxt = '.jaaba.txt';
  jaabadir = '.jaaba';
else
  settingsDirName = getenv('APPDATA');
  jaabatxt = 'jaaba.txt';
  jaabadir = 'jaaba';
end
if isdeployed,
%   if exist(fullfile(settingsDirName,jaabatxt),'file')
%     ff = fopen(fullfile(settingsDirName,jaabatxt));
%     jaabaPerUserDirName = fgetl(ff);
%     fclose(ff);
%   else
%     jaabaPerUserDirName = uigetdir(settingsDirName,'Select a file to store JAABA configuration files');
%     if ~exist(jaabaPerUserDirName)
%       mkdir(jaabaPerUserDirName);
%     end
%     ff  = fopen(fullfile(settingsDirName,jaabatxt),'w');
%     fprintf(ff,'%s',jaabaPerUserDirName);
%     fclose(ff);
%     if jaabaPerUserDirName == 0,
%       error('Cannot continue without a settings dir');
%     end
%     dd = dir(fullfile(pwd,'params','*.xml'));
%     for ndx = 1:numel(dd)
%       copyfile(fullfile(pwd,'params',dd(ndx).name),....
%         fullfile(jaabaPerUserDirName,dd(ndx).name));
%     end
%   end
  jaabaPerUserDirName = 'params';
else
  jaabaPerUserDirName=fullfile(settingsDirName,jaabadir);
end

if ~exist(jaabaPerUserDirName,'dir');
  mkdir(jaabaPerUserDirName);
end

end


classdef MimModelCacheEntry < CoreBaseClass

    properties
        CurrentHash
        RemoteHash
    end

    methods
        function obj = MimModelCacheEntry(currentHash, remoteHash)
            obj.CurrentHash = currentHash;
            obj.RemoteHash = remoteHash;
        end

        function updateHashes(obj, currentHash, remoteHash)
            obj.CurrentHash = currentHash;
            obj.RemoteHash = remoteHash;
        end

        function changed = hasChanged(obj)
            changed = ~isequal(obj.CurrentHash, obj.RemoteHash);
        end
    end
end


classdef PostProcTestsSuite < handle

    methods

        function obj = PostProcTestsSuite()
            warning('off', 'MATLAB:structOnObject')
            results = runtests("PostProcTests","ProcedureName","testFastDisplacement", 'Debug', true);
            table(results)
            warning('on', 'MATLAB:structOnObject')
        end

    end
end


function saveresults(res,peval,p, name_res_file)
% saveresults(res,peval,p, name_res_file)

if ~exist(peval.res_dir,'dir')
    fprintf('Creating directory:\n%s\n', peval.res_dir)
    mkdir (peval.res_dir);
end

if exist('peval.dir_res','var');
    savehere = [peval.dir_res '/' name_res_file];
else
    savehere = name_res_file;
end

if ~isfield (peval,'fid') peval.fid=1;end
mfprintf(peval.fid, ['Saving data to:\n%s\n'], savehere)
save (savehere,'res', 'peval', 'p');


function varargout = exportfig(varargin)
%EXPORTFIG  Export a figure.
%   EXPORTFIG(H, FILENAME) writes the figure H to FILENAME.  H is
%   a figure handle and FILENAME is a string that specifies the
%   name of the output file.
%
%   EXPORTFIG(H, FILENAME, OPTIONS) writes the figure H to FILENAME
%   with options initially specified by the structure OPTIONS. The
%   field names of OPTIONS must be legal parameters listed below
%   and the field values must be legal values for the corresponding
%   parameter. Default options can be set in releases prior to R12
%   by storing the OPTIONS structure in the root object's appdata
%   with the command
%      setappdata(0,'exportfigdefaults', OPTIONS)
%   and for releases after R12 by setting the preference with the
%   command
%      setpref('exportfig', 'defaults', OPTIONS)
%
%   EXPORTFIG(...,PARAM1,VAL1,PARAM2,VAL2,...) specifies
%   parameters that control various characteristics of the output
%   file. Any parameter value can be the string 'auto' which means
%   the parameter uses the default factory behavior, overriding
%   any other default for the parameter.
%
%   Format Paramter:
%     'Format'  a string
%          specifies the output format. Defaults to 'eps'. For a
%          list of export formats type 'help print'.
%     'Preview' one of the strings 'none', 'tiff'
%          specifies a preview for EPS files. Defaults to 'none'.
%
%   Size Parameters:
%     'Width'   a positive scalar
%          specifies the width in the figure's PaperUnits
%     'Height'  a positive scalar
%          specifies the height in the figure's PaperUnits
%     'Bounds' one of the strings 'tight', 'loose'
%          specifies a tight or loose bounding box. Defaults to 'tight'.
%     'Reference' an axes handle or a string
%          specifies that the width and height parameters
%          are relative to the given axes. If a string is
%          specified then it must evaluate to an axes handle.
%
%     Specifying only one dimension sets the other dimension
%     so that the exported aspect ratio is the same as the
%     figure's or reference axes' current aspect ratio.
%     If neither dimension is specified the size defaults to
%     the width and height from the figure's or reference
%     axes' size. Tight bounding boxes are only computed for
%     2-D views and in that case the computed bounds enclose all
%     text objects.
%
%   Rendering Parameters:
%     'Color'     one of the strings 'bw', 'gray', 'cmyk'
%         'bw'    specifies that lines and text are exported in
%                 black and all other objects in grayscale
%         'gray'  specifies that all objects are exported in grayscale
%         'rgb'   specifies that all objects are exported in color
%                 using the RGB color space
%         'cmyk'  specifies that all objects are exported in color
%                 using the CMYK color space
%     'Renderer'  one of 'painters', 'zbuffer', 'opengl'
%         specifies the renderer to use
%     'Resolution'   a positive scalar
%         specifies the resolution in dots-per-inch.
%     'LockAxes'  one of 0 or 1
%         specifies that all axes limits and ticks should be fixed
%         while exporting.
%
%     The default color setting is 'bw'.
%
%   Font Parameters:
%     'FontMode'     one of the strings 'scaled', 'fixed'
%     'FontSize'     a positive scalar
%          in 'scaled' mode multiplies with the font size of each
%          text object to obtain the exported font size
%          in 'fixed' mode specifies the font size of all text
%          objects in points
%     'DefaultFixedFontSize' a positive scalar
%          in 'fixed' mode specified the default font size in
%          points
%     'FontSizeMin' a positive scalar
%          specifies the minimum font size allowed after scaling
%     'FontSizeMax' a positive scalar
%          specifies the maximum font size allowed after scaling
%     'FontEncoding' one of the strings 'latin1', 'adobe'
%          specifies the character encoding of the font
%     'SeparateText' one of 0 or 1
%          specifies that the text objects are stored in separate
%          file as EPS with the base filename having '_t' appended.
%
%     If FontMode is 'scaled' but FontSize is not specified then a
%     scaling factor is computed from the ratio of the size of the
%     exported figure to the size of the actual figure.
%
%     The default 'FontMode' setting is 'scaled'.
%
%   Line Width Parameters:
%     'LineMode'     one of the strings 'scaled', 'fixed'
%     'LineWidth'    a positive scalar
%     'DefaultFixedLineWidth' a positive scalar
%     'LineWidthMin' a positive scalar
%          specifies the minimum line width allowed after scaling
%     'LineWidthMax' a positive scalar
%          specifies the maximum line width allowed after scaling
%     The semantics of 'Line' parameters are exactly the
%     same as the corresponding 'Font' parameters, except that
%     they apply to line widths instead of font sizes.
%
%   Style Map Parameter:
%     'LineStyleMap'    one of [], 'bw', or a function name or handle
%          specifies how to map line colors to styles. An empty
%          style map means styles are not changed. The style map
%          'bw' is a built-in mapping that maps lines with the same
%          color to the same style and otherwise cycles through the
%          available styles. A user-specified map is a function
%          that takes as input a cell array of line objects and
%          outputs a cell array of line style strings. The default
%          map is [].
%
%   Examples:
%     exportfig(gcf,'fig1.eps','height',3);
%       Exports the current figure to the file named 'fig1.eps' with
%       a height of 3 inches (assuming the figure's PaperUnits is
%       inches) and an aspect ratio the same as the figure's aspect
%       ratio on screen.
%
%     opts = struct('FontMode','fixed','FontSize',10,'height',3);
%     exportfig(gcf, 'fig2.eps', opts, 'height', 5);
%       Exports the current figure to 'fig2.eps' with all
%       text in 10 point fonts and with height 5 inches.
%
%   See also PREVIEWFIG, APPLYTOFIG, RESTOREFIG, PRINT.

%  Copyright 2000 Ben Hinkle
%  Email bug reports and comments to bhinkle@mathworks.com

if (nargin < 2)
  error('Too few input arguments');
end

% exportfig(H, filename, [options,] ...)
H = varargin{1};
if ~LocalIsHG(H,'figure')
  error('First argument must be a handle to a figure.');
end
filename = varargin{2};
if ~ischar(filename)
  error('Second argument must be a string.');
end
paramPairs = {varargin{3:end}};
if nargin > 2
  if isstruct(paramPairs{1})
    pcell = LocalToCell(paramPairs{1});
    paramPairs = {pcell{:}, paramPairs{2:end}};
  end
end
verstr = version;
majorver = str2num(verstr(1));
defaults = [];
if majorver > 5
  if ispref('exportfig','defaults')
    defaults = getpref('exportfig','defaults');
  end
elseif exist('getappdata')
  defaults = getappdata(0,'exportfigdefaults');
end
if ~isempty(defaults)
  dcell = LocalToCell(defaults);
  paramPairs = {dcell{:}, paramPairs{:}};
end

% Do some validity checking on param-value pairs
if (rem(length(paramPairs),2) ~= 0)
  error(['Invalid input syntax. Optional parameters and values' ...
	 ' must be in pairs.']);
end

auto.format = 'eps';
auto.preview = 'none';
auto.width = -1;
auto.height = -1;
auto.color = 'bw';
auto.defaultfontsize=10;
auto.fontsize = -1;
auto.fontmode='scaled';
auto.fontmin = 8;
auto.fontmax = 60;
auto.defaultlinewidth = 1.0;
auto.linewidth = -1;
auto.linemode=[];
auto.linemin = 0.5;
auto.linemax = 100;
auto.fontencoding = 'latin1';
auto.renderer = [];
auto.resolution = [];
auto.stylemap = [];
auto.applystyle = 0;
auto.refobj = -1;
auto.bounds = 'tight';
explicitbounds = 0;
auto.lockaxes = 1;
auto.separatetext = 0;
opts = auto;

% Process param-value pairs
args = {};
for k = 1:2:length(paramPairs)
  param = lower(paramPairs{k});
  if ~ischar(param)
    error('Optional parameter names must be strings');
  end
  value = paramPairs{k+1};

  switch (param)
   case 'format'
    opts.format = LocalCheckAuto(lower(value),auto.format);
    if strcmp(opts.format,'preview')
      error(['Format ''preview'' no longer supported. Use PREVIEWFIG' ...
	     ' instead.']);
    end
   case 'preview'
    opts.preview = LocalCheckAuto(lower(value),auto.preview);
    if ~strcmp(opts.preview,{'none','tiff'})
      error('Preview must be ''none'' or ''tiff''.');
    end
   case 'width'
    opts.width = LocalToNum(value, auto.width);
    if ~ischar(value) | ~strcmp(value,'auto')
      if ~LocalIsPositiveScalar(opts.width)
	error('Width must be a numeric scalar > 0');
      end
    end
   case 'height'
    opts.height = LocalToNum(value, auto.height);
    if ~ischar(value) | ~strcmp(value,'auto')
      if(~LocalIsPositiveScalar(opts.height))
	error('Height must be a numeric scalar > 0');
      end
    end
   case 'color'
    opts.color = LocalCheckAuto(lower(value),auto.color);
    if ~strcmp(opts.color,{'bw','gray','rgb','cmyk'})
      error('Color must be ''bw'', ''gray'',''rgb'' or ''cmyk''.');
    end
   case 'fontmode'
    opts.fontmode = LocalCheckAuto(lower(value),auto.fontmode);
    if ~strcmp(opts.fontmode,{'scaled','fixed'})
      error('FontMode must be ''scaled'' or ''fixed''.');
    end
   case 'fontsize'
    opts.fontsize = LocalToNum(value,auto.fontsize);
    if ~ischar(value) | ~strcmp(value,'auto')
      if ~LocalIsPositiveScalar(opts.fontsize)
	error('FontSize must be a numeric scalar > 0');
      end
    end
   case 'defaultfixedfontsize'
    opts.defaultfontsize = LocalToNum(value,auto.defaultfontsize);
    if ~ischar(value) | ~strcmp(value,'auto')
      if ~LocalIsPositiveScalar(opts.defaultfontsize)
	error('DefaultFixedFontSize must be a numeric scalar > 0');
      end
    end
   case 'fontsizemin'
    opts.fontmin = LocalToNum(value,auto.fontmin);
    if ~ischar(value) | ~strcmp(value,'auto')
      if ~LocalIsPositiveScalar(opts.fontmin)
	error('FontSizeMin must be a numeric scalar > 0');
      end
    end
   case 'fontsizemax'
    opts.fontmax = LocalToNum(value,auto.fontmax);
    if ~ischar(value) | ~strcmp(value,'auto')
      if ~LocalIsPositiveScalar(opts.fontmax)
	error('FontSizeMax must be a numeric scalar > 0');
      end
    end
   case 'fontencoding'
    opts.fontencoding = LocalCheckAuto(lower(value),auto.fontencoding);
    if ~strcmp(opts.fontencoding,{'latin1','adobe'})
      error('FontEncoding must be ''latin1'' or ''adobe''.');
    end
   case 'linemode'
    opts.linemode = LocalCheckAuto(lower(value),auto.linemode);
    if ~strcmp(opts.linemode,{'scaled','fixed'})
      error('LineMode must be ''scaled'' or ''fixed''.');
    end
   case 'linewidth'
    opts.linewidth = LocalToNum(value,auto.linewidth);
    if ~ischar(value) | ~strcmp(value,'auto')
      if ~LocalIsPositiveScalar(opts.linewidth)
	error('LineWidth must be a numeric scalar > 0');
      end
    end
   case 'defaultfixedlinewidth'
    opts.defaultlinewidth = LocalToNum(value,auto.defaultlinewidth);
    if ~ischar(value) | ~strcmp(value,'auto')
      if ~LocalIsPositiveScalar(opts.defaultlinewidth)
	error(['DefaultFixedLineWidth must be a numeric scalar >' ...
	       ' 0']);
      end
    end
   case 'linewidthmin'
    opts.linemin = LocalToNum(value,auto.linemin);
    if ~ischar(value) | ~strcmp(value,'auto')
      if ~LocalIsPositiveScalar(opts.linemin)
	error('LineWidthMin must be a numeric scalar > 0');
      end
    end
   case 'linewidthmax'
    opts.linemax = LocalToNum(value,auto.linemax);
    if ~ischar(value) | ~strcmp(value,'auto')
      if ~LocalIsPositiveScalar(opts.linemax)
	error('LineWidthMax must be a numeric scalar > 0');
      end
    end
   case 'linestylemap'
    opts.stylemap = LocalCheckAuto(value,auto.stylemap);
   case 'renderer'
    opts.renderer = LocalCheckAuto(lower(value),auto.renderer);
    if ~ischar(value) | ~strcmp(value,'auto')
      if ~strcmp(opts.renderer,{'painters','zbuffer','opengl'})
	error(['Renderer must be ''painters'', ''zbuffer'' or' ...
	       ' ''opengl''.']);
      end
    end
   case 'resolution'
    opts.resolution = LocalToNum(value,auto.resolution);
    if ~ischar(value) | ~strcmp(value,'auto')
      if ~(isnumeric(value) & (prod(size(value)) == 1) & (value >= 0));
	error('Resolution must be a numeric scalar >= 0');
      end
    end
   case 'applystyle' % means to apply the options and not export
    opts.applystyle = 1;
   case 'reference'
    if ischar(value)
      if strcmp(value,'auto')
	opts.refobj = auto.refobj;
      else
	opts.refobj = eval(value);
      end
    else
      opts.refobj = value;
    end
    if ~LocalIsHG(opts.refobj,'axes')
      error('Reference object must evaluate to an axes handle.');
    end
   case 'bounds'
    opts.bounds = LocalCheckAuto(lower(value),auto.bounds);
    explicitbounds = 1;
    if ~strcmp(opts.bounds,{'tight','loose'})
      error('Bounds must be ''tight'' or ''loose''.');
    end
   case 'lockaxes'
    opts.lockaxes = LocalToNum(value,auto.lockaxes);
   case 'separatetext'
    opts.separatetext = LocalToNum(value,auto.separatetext);
   otherwise
    error(['Unrecognized option ' param '.']);
  end
end

% make sure figure is up-to-date
drawnow;

allLines  = findall(H, 'type', 'line');
allText   = findall(H, 'type', 'text');
allAxes   = findall(H, 'type', 'axes');
allImages = findall(H, 'type', 'image');
allLights = findall(H, 'type', 'light');
allPatch  = findall(H, 'type', 'patch');
allSurf   = findall(H, 'type', 'surface');
allRect   = findall(H, 'type', 'rectangle');
allFont   = [allText; allAxes];
allColor  = [allLines; allText; allAxes; allLights];
allMarker = [allLines; allPatch; allSurf];
allEdge   = [allPatch; allSurf];
allCData  = [allImages; allPatch; allSurf];

old.objs = {};
old.prop = {};
old.values = {};

% Process format
if strncmp(opts.format,'eps',3) & ~strcmp(opts.preview,'none')
  args = {args{:}, ['-' opts.preview]};
end

hadError = 0;
oldwarn = warning;
try

  % lock axes limits, ticks and labels if requested
  if opts.lockaxes
    old = LocalManualAxesMode(old, allAxes, 'TickMode');
    old = LocalManualAxesMode(old, allAxes, 'TickLabelMode');
    old = LocalManualAxesMode(old, allAxes, 'LimMode');
  end

  % Process size parameters
  figurePaperUnits = get(H, 'PaperUnits');
  oldFigureUnits = get(H, 'Units');
  oldFigPos = get(H,'Position');
  set(H, 'Units', figurePaperUnits);
  figPos = get(H,'Position');
  refsize = figPos(3:4);
  if opts.refobj ~= -1
    oldUnits = get(opts.refobj, 'Units');
    set(opts.refobj, 'Units', figurePaperUnits);
    r = get(opts.refobj, 'Position');
    refsize = r(3:4);
    set(opts.refobj, 'Units', oldUnits);
  end
  aspectRatio = refsize(1)/refsize(2);
  if (opts.width == -1) & (opts.height == -1)
    opts.width = refsize(1);
    opts.height = refsize(2);
  elseif (opts.width == -1)
    opts.width = opts.height * aspectRatio;
  elseif (opts.height == -1)
    opts.height = opts.width / aspectRatio;
  end
  wscale = opts.width/refsize(1);
  hscale = opts.height/refsize(2);
  sizescale = min(wscale,hscale);
  old = LocalPushOldData(old,H,'PaperPositionMode', ...
			 get(H,'PaperPositionMode'));
  set(H, 'PaperPositionMode', 'auto');
  newPos = [figPos(1) figPos(2)+figPos(4)*(1-hscale) ...
	    wscale*figPos(3) hscale*figPos(4)];
  set(H, 'Position', newPos);
  set(H, 'Units', oldFigureUnits);

  % process line-style map
  if ~isempty(opts.stylemap) & ~isempty(allLines)
    oldlstyle = LocalGetAsCell(allLines,'LineStyle');
    old = LocalPushOldData(old, allLines, {'LineStyle'}, ...
			   oldlstyle);
    newlstyle = oldlstyle;
    if ischar(opts.stylemap) & strcmpi(opts.stylemap,'bw')
      newlstyle = LocalMapColorToStyle(allLines);
    else
      try
	newlstyle = feval(opts.stylemap,allLines);
      catch
	warning(['Skipping stylemap. ' lasterr]);
      end
    end
    set(allLines,{'LineStyle'},newlstyle);
  end

  % Process rendering parameters
  switch (opts.color)
   case {'bw', 'gray'}
    if ~strcmp(opts.color,'bw') & strncmp(opts.format,'eps',3)
      opts.format = [opts.format 'c'];
    end
    args = {args{:}, ['-d' opts.format]};

    %compute and set gray colormap
    oldcmap = get(H,'Colormap');
    newgrays = 0.30*oldcmap(:,1) + 0.59*oldcmap(:,2) + 0.11*oldcmap(:,3);
    newcmap = [newgrays newgrays newgrays];
    old = LocalPushOldData(old, H, 'Colormap', oldcmap);
    set(H, 'Colormap', newcmap);

    %compute and set ColorSpec and CData properties
    old = LocalUpdateColors(allColor, 'color', old);
    old = LocalUpdateColors(allAxes, 'xcolor', old);
    old = LocalUpdateColors(allAxes, 'ycolor', old);
    old = LocalUpdateColors(allAxes, 'zcolor', old);
    old = LocalUpdateColors(allMarker, 'MarkerEdgeColor', old);
    old = LocalUpdateColors(allMarker, 'MarkerFaceColor', old);
    old = LocalUpdateColors(allEdge, 'EdgeColor', old);
    old = LocalUpdateColors(allEdge, 'FaceColor', old);
    old = LocalUpdateColors(allCData, 'CData', old);

   case {'rgb','cmyk'}
    if strncmp(opts.format,'eps',3)
      opts.format = [opts.format 'c'];
      args = {args{:}, ['-d' opts.format]};
      if strcmp(opts.color,'cmyk')
	args = {args{:}, '-cmyk'};
      end
    else
      args = {args{:}, ['-d' opts.format]};
    end
   otherwise
    error('Invalid Color parameter');
  end
  if (~isempty(opts.renderer))
    args = {args{:}, ['-' opts.renderer]};
  end
  if (~isempty(opts.resolution)) | ~strncmp(opts.format,'eps',3)
    if isempty(opts.resolution)
      opts.resolution = 0;
    end
    args = {args{:}, ['-r' int2str(opts.resolution)]};
  end

  % Process font parameters
  if ~isempty(opts.fontmode)
    oldfonts = LocalGetAsCell(allFont,'FontSize');
    oldfontunits = LocalGetAsCell(allFont,'FontUnits');
    set(allFont,'FontUnits','points');
    switch (opts.fontmode)
     case 'fixed'
      if (opts.fontsize == -1)
	set(allFont,'FontSize',opts.defaultfontsize);
      else
	set(allFont,'FontSize',opts.fontsize);
      end
     case 'scaled'
      if (opts.fontsize == -1)
	scale = sizescale;
      else
	scale = opts.fontsize;
      end
      newfonts = LocalScale(oldfonts,scale,opts.fontmin,opts.fontmax);
      set(allFont,{'FontSize'},newfonts);
     otherwise
      error('Invalid FontMode parameter');
    end
    old = LocalPushOldData(old, allFont, {'FontSize'}, oldfonts);
    old = LocalPushOldData(old, allFont, {'FontUnits'}, oldfontunits);
  end
  if strcmp(opts.fontencoding,'adobe') & strncmp(opts.format,'eps',3)
    args = {args{:}, '-adobecset'};
  end

  % Process line parameters
  if ~isempty(opts.linemode)
    oldlines = LocalGetAsCell(allMarker,'LineWidth');
    old = LocalPushOldData(old, allMarker, {'LineWidth'}, oldlines);
    switch (opts.linemode)
     case 'fixed'
      if (opts.linewidth == -1)
	set(allMarker,'LineWidth',opts.defaultlinewidth);
      else
	set(allMarker,'LineWidth',opts.linewidth);
      end
     case 'scaled'
      if (opts.linewidth == -1)
	scale = sizescale;
      else
	scale = opts.linewidth;
      end
      newlines = LocalScale(oldlines, scale, opts.linemin, opts.linemax);
      set(allMarker,{'LineWidth'},newlines);
    end
  end

  % adjust figure bounds to surround axes
  if strcmp(opts.bounds,'tight')
    if (~strncmp(opts.format,'eps',3) & LocalHas3DPlot(allAxes)) | ...
	  (strncmp(opts.format,'eps',3) & opts.separatetext)
      if (explicitbounds == 1)
	warning(['Cannot compute ''tight'' bounds. Using ''loose''' ...
		 ' bounds.']);
      end
      opts.bounds = 'loose';
    end
  end
  warning('off');
  if ~isempty(allAxes)
    if strncmp(opts.format,'eps',3)
      if strcmp(opts.bounds,'loose')
	args = {args{:}, '-loose'};
      end
      old = LocalPushOldData(old,H,'Position', oldFigPos);
    elseif strcmp(opts.bounds,'tight')
      oldaunits = LocalGetAsCell(allAxes,'Units');
      oldapos = LocalGetAsCell(allAxes,'Position');
      oldtunits = LocalGetAsCell(allText,'units');
      oldtpos = LocalGetAsCell(allText,'Position');
      set(allAxes,'units','points');
      apos = LocalGetAsCell(allAxes,'Position');
      oldunits = get(H,'Units');
      set(H,'units','points');
      origfr = get(H,'position');
      fr = [];
      for k=1:length(allAxes)
	if ~strcmpi(get(allAxes(k),'Tag'),'legend')
	  axesR = apos{k};
	  r = LocalAxesTightBoundingBox(axesR, allAxes(k));
	  r(1:2) = r(1:2) + axesR(1:2);
	  fr = LocalUnionRect(fr,r);
	end
      end
      if isempty(fr)
	fr = [0 0 origfr(3:4)];
      end
      for k=1:length(allAxes)
	ax = allAxes(k);
	r = apos{k};
	r(1:2) = r(1:2) - fr(1:2);
	set(ax,'Position',r);
      end
      old = LocalPushOldData(old, allAxes, {'Position'}, oldapos);
      old = LocalPushOldData(old, allText, {'Position'}, oldtpos);
      old = LocalPushOldData(old, allText, {'Units'}, oldtunits);
      old = LocalPushOldData(old, allAxes, {'Units'}, oldaunits);
      old = LocalPushOldData(old, H, 'Position', oldFigPos);
      old = LocalPushOldData(old, H, 'Units', oldFigureUnits);
      r = [origfr(1) origfr(2)+origfr(4)-fr(4) fr(3:4)];
      set(H,'Position',r);
    else
      args = {args{:}, '-loose'};
      old = LocalPushOldData(old,H,'Position', oldFigPos);
    end
  end

  % Process text in a separate file if needed
  if opts.separatetext & ~opts.applystyle
    % First hide all text and export
    oldtvis = LocalGetAsCell(allText,'visible');
    set(allText,'visible','off');
    oldax = LocalGetAsCell(allAxes,'XTickLabel',1);
    olday = LocalGetAsCell(allAxes,'YTickLabel',1);
    oldaz = LocalGetAsCell(allAxes,'ZTickLabel',1);
    null = cell(length(oldax),1);
    [null{:}] = deal([]);
    set(allAxes,{'XTickLabel'},null);
    set(allAxes,{'YTickLabel'},null);
    set(allAxes,{'ZTickLabel'},null);
    print(H, filename, args{:});
    set(allText,{'Visible'},oldtvis);
    set(allAxes,{'XTickLabel'},oldax);
    set(allAxes,{'YTickLabel'},olday);
    set(allAxes,{'ZTickLabel'},oldaz);
    % Now hide all non-text and export as eps in painters
    [path, name, ext] = fileparts(filename);
    tfile = fullfile(path,[name '_t.eps']);
    tfile2 = fullfile(path,[name '_t2.eps']);
    foundRenderer = 0;
    for k=1:length(args)
      if strncmp('-d',args{k},2)
	args{k} = '-deps';
      elseif strncmp('-zbuffer',args{k},8) | ...
	    strncmp('-opengl', args{k},6)
	args{k} = '-painters';
	foundRenderer = 1;
      end
    end
    if ~foundRenderer
      args = {args{:}, '-painters'};
    end
    allNonText = [allLines; allLights; allPatch; ...
		  allImages; allSurf; allRect];
    oldvis = LocalGetAsCell(allNonText,'visible');
    oldc = LocalGetAsCell(allAxes,'color');
    oldaxg = LocalGetAsCell(allAxes,'XGrid');
    oldayg = LocalGetAsCell(allAxes,'YGrid');
    oldazg = LocalGetAsCell(allAxes,'ZGrid');
    [null{:}] = deal('off');
    set(allAxes,{'XGrid'},null);
    set(allAxes,{'YGrid'},null);
    set(allAxes,{'ZGrid'},null);
    set(allNonText,'Visible','off');
    set(allAxes,'Color','none');
    print(H, tfile2, args{:});
    set(allNonText,{'Visible'},oldvis);
    set(allAxes,{'Color'},oldc);
    set(allAxes,{'XGrid'},oldaxg);
    set(allAxes,{'YGrid'},oldayg);
    set(allAxes,{'ZGrid'},oldazg);
    %hack up the postscript file
    fid1 = fopen(tfile,'w');
    fid2 = fopen(tfile2,'r');
    line = fgetl(fid2);
    while ischar(line)
      if strncmp(line,'%%Title',7)
	fprintf(fid1,'%s\n',['%%Title: ', tfile]);
      elseif (length(line) < 3)
	fprintf(fid1,'%s\n',line);
      elseif ~strcmp(line(end-2:end),' PR') & ...
	    ~strcmp(line(end-1:end),' L')
	fprintf(fid1,'%s\n',line);
      end
      line = fgetl(fid2);
    end
    fclose(fid1);
    fclose(fid2);
    delete(tfile2);

  elseif ~opts.applystyle
    drawnow;
    print(H, filename, args{:});
  end
  warning(oldwarn);

catch
  warning(oldwarn);
  hadError = 1;
end

% Restore figure settings
if opts.applystyle
  varargout{1} = old;
else
  for n=1:length(old.objs)
    if ~iscell(old.values{n}) & iscell(old.prop{n})
      old.values{n} = {old.values{n}};
    end
    set(old.objs{n}, old.prop{n}, old.values{n});
  end
end

if hadError
  error(deblank(lasterr));
end

%
%  Local Functions
%

function outData = LocalPushOldData(inData, objs, prop, values)
outData.objs = {objs, inData.objs{:}};
outData.prop = {prop, inData.prop{:}};
outData.values = {values, inData.values{:}};

function cellArray = LocalGetAsCell(fig,prop,allowemptycell);
cellArray = get(fig,prop);
if nargin < 3
  allowemptycell = 0;
end
if ~iscell(cellArray) & (allowemptycell | ~isempty(cellArray))
  cellArray = {cellArray};
end

function newArray = LocalScale(inArray, scale, minv, maxv)
n = length(inArray);
newArray = cell(n,1);
for k=1:n
  newArray{k} = min(maxv,max(minv,scale*inArray{k}(1)));
end

function gray = LocalMapToGray1(color)
gray = color;
if ischar(color)
  switch color(1)
   case 'y'
    color = [1 1 0];
   case 'm'
    color = [1 0 1];
   case 'c'
    color = [0 1 1];
   case 'r'
    color = [1 0 0];
   case 'g'
    color = [0 1 0];
   case 'b'
    color = [0 0 1];
   case 'w'
    color = [1 1 1];
   case 'k'
    color = [0 0 0];
  end
end
if ~ischar(color)
  gray = 0.30*color(1) + 0.59*color(2) + 0.11*color(3);
end

function newArray = LocalMapToGray(inArray);
n = length(inArray);
newArray = cell(n,1);
for k=1:n
  color = inArray{k};
  if ~isempty(color)
    color = LocalMapToGray1(color);
  end
  if isempty(color) | ischar(color)
    newArray{k} = color;
  else
    newArray{k} = [color color color];
  end
end

function newArray = LocalMapColorToStyle(inArray);
inArray = LocalGetAsCell(inArray,'Color');
n = length(inArray);
newArray = cell(n,1);
styles = {'-','--',':','-.'};
uniques = [];
nstyles = length(styles);
for k=1:n
  gray = LocalMapToGray1(inArray{k});
  if isempty(gray) | ischar(gray) | gray < .05
    newArray{k} = '-';
  else
    if ~isempty(uniques) & any(gray == uniques)
      ind = find(gray==uniques);
    else
      uniques = [uniques gray];
      ind = length(uniques);
    end
    newArray{k} = styles{mod(ind-1,nstyles)+1};
  end
end

function newArray = LocalMapCData(inArray);
n = length(inArray);
newArray = cell(n,1);
for k=1:n
  color = inArray{k};
  if (ndims(color) == 3) & isa(color,'double')
    gray = 0.30*color(:,:,1) + 0.59*color(:,:,2) + 0.11*color(:,:,3);
    color(:,:,1) = gray;
    color(:,:,2) = gray;
    color(:,:,3) = gray;
  end
  newArray{k} = color;
end

function outData = LocalUpdateColors(inArray, prop, inData)
value = LocalGetAsCell(inArray,prop);
outData.objs = {inData.objs{:}, inArray};
outData.prop = {inData.prop{:}, {prop}};
outData.values = {inData.values{:}, value};
if (~isempty(value))
  if strcmp(prop,'CData')
    value = LocalMapCData(value);
  else
    value = LocalMapToGray(value);
  end
  set(inArray,{prop},value);
end

function bool = LocalIsPositiveScalar(value)
bool = isnumeric(value) & ...
       prod(size(value)) == 1 & ...
       value > 0;

function value = LocalToNum(value,auto)
if ischar(value)
  if strcmp(value,'auto')
    value = auto;
  else
    value = str2num(value);
  end
end

%convert a struct to {field1,val1,field2,val2,...}
function c = LocalToCell(s)
f = fieldnames(s);
v = struct2cell(s);
opts = cell(2,length(f));
opts(1,:) = f;
opts(2,:) = v;
c = {opts{:}};

function c = LocalIsHG(obj,hgtype)
c = 0;
if (length(obj) == 1) & ishandle(obj)
  c = strcmp(get(obj,'type'),hgtype);
end

function c = LocalHas3DPlot(a)
zticks = LocalGetAsCell(a,'ZTickLabel');
c = 0;
for k=1:length(zticks)
  if ~isempty(zticks{k})
    c = 1;
    return;
  end
end

function r = LocalUnionRect(r1,r2)
if isempty(r1)
  r = r2;
elseif isempty(r2)
  r = r1;
elseif max(r2(3:4)) > 0
  left = min(r1(1),r2(1));
  bot = min(r1(2),r2(2));
  right = max(r1(1)+r1(3),r2(1)+r2(3));
  top = max(r1(2)+r1(4),r2(2)+r2(4));
  r = [left bot right-left top-bot];
else
  r = r1;
end

function c = LocalLabelsMatchTicks(labs,ticks)
c = 0;
try
  t1 = num2str(ticks(1));
  n = length(ticks);
  tend = num2str(ticks(n));
  c = strncmp(labs(1),t1,length(labs(1))) & ...
      strncmp(labs(n),tend,length(labs(n)));
end

function r = LocalAxesTightBoundingBox(axesR, a)
r = [];
atext = findall(a,'type','text','visible','on');
if ~isempty(atext)
  set(atext,'units','points');
  res=LocalGetAsCell(atext,'extent');
  for n=1:length(atext)
    r = LocalUnionRect(r,res{n});
  end
end
if strcmp(get(a,'visible'),'on')
  r = LocalUnionRect(r,[0 0 axesR(3:4)]);
  oldunits = get(a,'fontunits');
  set(a,'fontunits','points');
  label = text(0,0,'','parent',a,...
	       'units','points',...
	       'fontsize',get(a,'fontsize'),...
	       'fontname',get(a,'fontname'),...
	       'fontweight',get(a,'fontweight'),...
	       'fontangle',get(a,'fontangle'),...
	       'visible','off');
  fs = get(a,'fontsize');

  % handle y axis tick labels
  ry = [0 -fs/2 0 axesR(4)+fs];
  ylabs = get(a,'yticklabels');
  yticks = get(a,'ytick');
  maxw = 0;
  if ~isempty(ylabs)
    for n=1:size(ylabs,1)
      set(label,'string',ylabs(n,:));
      ext = get(label,'extent');
      maxw = max(maxw,ext(3));
    end
    if ~LocalLabelsMatchTicks(ylabs,yticks) & ...
	  strcmp(get(a,'xaxislocation'),'bottom')
      ry(4) = ry(4) + 1.5*ext(4);
    end
    if strcmp(get(a,'yaxislocation'),'left')
      ry(1) = -(maxw+5);
    else
      ry(1) = axesR(3);
    end
    ry(3) = maxw+5;
    r = LocalUnionRect(r,ry);
  end

  % handle x axis tick labels
  rx = [0 0 0 fs+5];
  xlabs = get(a,'xticklabels');
  xticks = get(a,'xtick');
  if ~isempty(xlabs)
    if strcmp(get(a,'xaxislocation'),'bottom')
      rx(2) = -(fs+5);
      if ~LocalLabelsMatchTicks(xlabs,xticks);
	rx(4) = rx(4) + 2*fs;
	rx(2) = rx(2) - 2*fs;
      end
    else
      rx(2) = axesR(4);
      % exponent is still below axes
      if ~LocalLabelsMatchTicks(xlabs,xticks);
	rx(4) = rx(4) + axesR(4) + 2*fs;
	rx(2) = -2*fs;
      end
    end
    set(label,'string',xlabs(1,:));
    ext1 = get(label,'extent');
    rx(1) = -ext1(3)/2;
    set(label,'string',xlabs(size(xlabs,1),:));
    ext2 = get(label,'extent');
    rx(3) = axesR(3) + (ext2(3) + ext1(3))/2;
    r = LocalUnionRect(r,rx);
  end
  set(a,'fontunits',oldunits);
  delete(label);
end

function c = LocalManualAxesMode(old, allAxes, base)
xs = ['X' base];
ys = ['Y' base];
zs = ['Z' base];
oldXMode = LocalGetAsCell(allAxes,xs);
oldYMode = LocalGetAsCell(allAxes,ys);
oldZMode = LocalGetAsCell(allAxes,zs);
old = LocalPushOldData(old, allAxes, {xs}, oldXMode);
old = LocalPushOldData(old, allAxes, {ys}, oldYMode);
old = LocalPushOldData(old, allAxes, {zs}, oldZMode);
set(allAxes,xs,'manual');
set(allAxes,ys,'manual');
set(allAxes,zs,'manual');
c = old;

function val = LocalCheckAuto(val, auto)
if ischar(val) & strcmp(val,'auto')
  val = auto;
end


classdef TabPanel < uix.Container & uix.mixin.Panel
    %uix.TabPanel  Tab panel
    %
    %  p = uix.TabPanel(p1,v1,p2,v2,...) constructs a tab panel and sets
    %  parameter p1 to value v1, etc.
    %
    %  A tab panel shows one of its contents and hides the others according
    %  to which tab is selected.
    %
    %  From R2014b, MATLAB provides uitabgroup and uitab as standard
    %  components.  Consider using uitabgroup and uitab for new code if
    %  these meet your requirements.
    %
    %  See also: uitabgroup, uitab, uix.CardPanel

    %  Copyright 2009-2016 The MathWorks, Inc.
    %  $Revision: 1480 $ $Date: 2017-02-15 16:56:13 +0100 (Wed, 15 Feb 2017) $

    properties( Access = public, Dependent, AbortSet )
        FontAngle % font angle
        FontName % font name
        FontSize % font size
        FontWeight % font weight
        FontUnits % font weight
        ForegroundColor % tab text color [RGB]
        HighlightColor % border highlight color [RGB]
        ShadowColor % border shadow color [RGB]
    end

    properties
        SelectionChangedFcn = '' % selection change callback
    end

    properties( Access = public, Dependent, AbortSet )
        TabEnables % tab enable states
        TabLocation % tab location [top|bottom]
        TabTitles % tab titles
        TabContextMenus % tab context menus
        TabWidth % tab width
    end

    properties( Access = private )
        FontAngle_ = get( 0, 'DefaultUicontrolFontAngle' ) % backing for FontAngle
        FontName_ = get( 0, 'DefaultUicontrolFontName' ) % backing for FontName
        FontSize_ = get( 0, 'DefaultUicontrolFontSize' ) % backing for FontSize
        FontWeight_ = get( 0, 'DefaultUicontrolFontWeight' ) % backing for FontWeight
        FontUnits_ = get( 0, 'DefaultUicontrolFontUnits' ) % backing for FontUnits
        ForegroundColor_ = get( 0, 'DefaultUicontrolForegroundColor' ) % backing for ForegroundColor
        HighlightColor_ = [1 1 1] % backing for HighlightColor
        ShadowColor_ = [0.7 0.7 0.7] % backing for ShadowColor
        ParentBackgroundColor = get( 0, 'DefaultUicontrolForegroundColor' ) % default parent background color
        Tabs = gobjects( [0 1] ) % tabs
        TabListeners = event.listener.empty( [0 1] ) % tab listeners
        TabLocation_ = 'top' % backing for TabPosition
        TabHeight = -1 % cache of tab height (-1 denotes stale cache)
        TabWidth_ = 50 % backing for TabWidth
        Dividers % tab dividers
        BackgroundColorListener % listener
        SelectionChangedListener % listener
        ParentListener % listener
        ParentBackgroundColorListener % listener
    end

    properties( Access = private, Constant )
        FontNames = listfonts() % all available font names
        DividerMask = uix.TabPanel.getDividerMask() % divider image data
        DividerWidth = 8 % divider width
        TabMinimumHeight = 9 % tab minimum height
        Tint = 0.85 % tint factor for unselected tabs
    end

    methods

        function obj = TabPanel( varargin )
            %uix.TabPanel  Tab panel constructor
            %
            %  p = uix.TabPanel() constructs a tab panel.
            %
            %  p = uix.TabPanel(p1,v1,p2,v2,...) sets parameter p1 to value
            %  v1, etc.

            % Create dividers
            dividers = matlab.ui.control.UIControl( 'Internal', true, ...
                'Parent', obj, 'Units', 'pixels', 'Style', 'checkbox',...
                'Tag', 'TabPanelDividers' );

            % Create listeners
            backgroundColorListener = event.proplistener( obj, ...
                findprop( obj, 'BackgroundColor' ), 'PostSet', ...
                @obj.onBackgroundColorChange );
            selectionChangedListener = event.listener( obj, ...
                'SelectionChanged', @obj.onSelectionChanged );
            parentListener = event.proplistener( obj, ...
                findprop( obj, 'Parent' ), 'PostSet', ...
                @obj.onParentChanged );

            % Store properties
            obj.Dividers = dividers;
            obj.BackgroundColorListener = backgroundColorListener;
            obj.SelectionChangedListener = selectionChangedListener;
            obj.ParentListener = parentListener;

            % Set properties
            try
                uix.set( obj, varargin{:} )
            catch e
                delete( obj )
                e.throwAsCaller()
            end

        end % constructor

    end % structors

    methods

        function value = get.FontAngle( obj )

            value = obj.FontAngle_;

        end % get.FontAngle

        function set.FontAngle( obj, value )

            % Check
            assert( ischar( value ) && any( strcmp( value, {'normal','italic','oblique'} ) ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''FontAngle'' must be ''normal'', ''italic'' or ''oblique''.' )

            % Set
            obj.FontAngle_ = value;

            % Update existing tabs
            tabs = obj.Tabs;
            n = numel( tabs );
            for ii = 1:n
                tab = tabs(ii);
                tab.FontAngle = value;
            end

            % Mark as dirty
            obj.TabHeight = -1;
            obj.Dirty = true;

        end % set.FontAngle

        function value = get.FontName( obj )

            value = obj.FontName_;

        end % get.FontName

        function set.FontName( obj, value )

            % Check
            assert( ischar( value ) && any( strcmp( value, obj.FontNames ) ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''FontName'' must be a valid font name.' )

            % Set
            obj.FontName_ = value;

            % Update existing tabs
            tabs = obj.Tabs;
            n = numel( tabs );
            for ii = 1:n
                tab = tabs(ii);
                tab.FontName = value;
            end

            % Mark as dirty
            obj.TabHeight = -1;
            obj.Dirty = true;

        end % set.FontName

        function value = get.FontSize( obj )

            value = obj.FontSize_;

        end % get.FontSize

        function set.FontSize( obj, value )

            % Check
            assert( isa( value, 'double' ) && isscalar( value ) && ...
                isreal( value ) && ~isinf( value ) && ...
                ~isnan( value ) && value > 0, ...
                'uix:InvalidPropertyValue', ...
                'Property ''FontSize'' must be a positive scalar.' )

            % Set
            obj.FontSize_ = value;

            % Update existing tabs
            tabs = obj.Tabs;
            n = numel( tabs );
            for ii = 1:n
                tab = tabs(ii);
                tab.FontSize = value;
            end

            % Mark as dirty
            obj.TabHeight = -1;
            obj.Dirty = true;

        end % set.FontSize

        function value = get.FontWeight( obj )

            value = obj.FontWeight_;

        end % get.FontWeight

        function set.FontWeight( obj, value )

            % Check
            assert( ischar( value ) && any( strcmp( value, {'normal','bold'} ) ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''FontWeight'' must be ''normal'' or ''bold''.' )

            % Set
            obj.FontWeight_ = value;

            % Update existing tabs
            tabs = obj.Tabs;
            n = numel( tabs );
            for ii = 1:n
                tab = tabs(ii);
                tab.FontWeight = value;
            end

            % Mark as dirty
            obj.TabHeight = -1;
            obj.Dirty = true;

        end % set.FontWeight

        function value = get.FontUnits( obj )

            value = obj.FontUnits_;

        end % get.FontUnits

        function set.FontUnits( obj, value )

            % Check
            assert( ischar( value ) && ...
                any( strcmp( value, {'inches','centimeters','points','pixels'} ) ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''FontUnits'' must be ''inches'', ''centimeters'', ''points'' or ''pixels''.' )

            % Compute size in new units
            oldUnits = obj.FontUnits_;
            oldSize = obj.FontSize_;
            newUnits = value;
            newSize = oldSize * convert( oldUnits ) / convert( newUnits );

            % Set size and units
            obj.FontSize_ = newSize;
            obj.FontUnits_ = newUnits;

            % Update existing tabs
            tabs = obj.Tabs;
            n = numel( tabs );
            for ii = 1:n
                tab = tabs(ii);
                tab.FontUnits = newUnits;
            end

            % Mark as dirty
            obj.TabHeight = -1;
            obj.Dirty = true;

            function factor = convert( units )
                %convert  Compute conversion factor to points
                %
                %  f = convert(u) computes the conversion factor from units
                %  u to points.  For example, convert('inches') since 1
                %  inch equals 72 points.

                persistent SCREEN_PIXELS_PER_INCH
                if isequal( SCREEN_PIXELS_PER_INCH, [] ) % uninitialized
                    SCREEN_PIXELS_PER_INCH = get( 0, 'ScreenPixelsPerInch' );
                end

                switch units
                    case 'inches'
                        factor = 72;
                    case 'centimeters'
                        factor = 72 / 2.54;
                    case 'points'
                        factor = 1;
                    case 'pixels'
                        factor = 72 / SCREEN_PIXELS_PER_INCH;
                end

            end % convert

        end % set.FontUnits

        function value = get.ForegroundColor( obj )

            value = obj.ForegroundColor_;

        end % get.ForegroundColor

        function set.ForegroundColor( obj, value )

            % Check
            assert( isnumeric( value ) && isequal( size( value ), [1 3] ) && ...
                all( isreal( value ) ) && all( value >= 0 ) && all( value <= 1 ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''ForegroundColor'' must be an RGB triple.' )

            % Set
            obj.ForegroundColor_ = value;

            % Update existing tabs
            tabs = obj.Tabs;
            n = numel( tabs );
            for ii = 1:n
                tab = tabs(ii);
                tab.ForegroundColor = value;
            end

        end % set.ForegroundColor

        function value = get.HighlightColor( obj )

            value = obj.HighlightColor_;

        end % get.HighlightColor

        function set.HighlightColor( obj, value )

            % Check
            assert( isnumeric( value ) && isequal( size( value ), [1 3] ) && ...
                all( isreal( value ) ) && all( value >= 0 ) && all( value <= 1 ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''HighlightColor'' must be an RGB triple.' )

            % Set
            obj.HighlightColor_ = value;

            % Mark as dirty
            obj.Dirty = true;

        end % set.HighlightColor

        function set.SelectionChangedFcn( obj, value )

            % Check
            if ischar( value ) % string
                % OK
            elseif isa( value, 'function_handle' ) && ...
                    isequal( size( value ), [1 1] ) % function handle
                % OK
            elseif iscell( value ) && ndims( value ) == 2 && ...
                    size( value, 1 ) == 1 && size( value, 2 ) > 0 && ...
                    isa( value{1}, 'function_handle' ) && ...
                    isequal( size( value{1} ), [1 1] ) %#ok<ISMAT> % cell callback
                % OK
            else
                error( 'uix:InvalidPropertyValue', ...
                    'Property ''SelectionChangedFcn'' must be a valid callback.' )
            end

            % Set
            obj.SelectionChangedFcn = value;

        end % set.SelectionChangedFcn

        function value = get.ShadowColor( obj )

            value = obj.ShadowColor_;

        end % get.ShadowColor

        function set.ShadowColor( obj, value )

            % Check
            assert( isnumeric( value ) && isequal( size( value ), [1 3] ) && ...
                all( isreal( value ) ) && all( value >= 0 ) && all( value <= 1 ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''ShadowColor'' must be an RGB triple.' )

            % Set
            obj.ShadowColor_ = value;

            % Mark as dirty
            obj.Dirty = true;

        end % set.ShadowColor

        function value = get.TabEnables( obj )

            value = get( obj.Tabs, {'Enable'} );
            value(strcmp( value, 'inactive' )) = {'on'};

        end % get.TabEnables

        function set.TabEnables( obj, value )

            % For those who can't tell a column from a row...
            if isrow( value )
                value = transpose( value );
            end

            % Retrieve tabs
            tabs = obj.Tabs;
            tabListeners = obj.TabListeners;

            % Check
            assert( iscellstr( value ) && ...
                isequal( size( value ), size( tabs ) ) && ...
                all( strcmp( value, 'on' ) | strcmp( value, 'off' ) ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''TabEnables'' should be a cell array of strings ''on'' or ''off'', one per tab.' )

            % Set
            tf = strcmp( value, 'on' );
            value(tf) = {'inactive'};
            for ii = 1:numel( tabs )
                tabs(ii).Enable = value{ii};
                tabListeners(ii).Enabled = tf(ii);
            end

            % Show selected child
            obj.showSelection()

            % Mark as dirty
            obj.Dirty = true;

        end % set.TabEnables

        function value = get.TabLocation( obj )

            value = obj.TabLocation_;

        end % get.TabLocation

        function set.TabLocation( obj, value )

            % Check
            assert( ischar( value ) && ...
                any( strcmp( value, {'top','bottom'} ) ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''TabLocation'' should be ''top'' or ''bottom''.' )

            % Set
            obj.TabLocation_ = value;

            % Mark as dirty
            obj.Dirty = true;

        end % set.TabLocation

        function value = get.TabTitles( obj )

            value = get( obj.Tabs, {'String'} );

        end % get.TabTitles

        function set.TabTitles( obj, value )

            % For those who can't tell a column from a row...
            if isrow( value )
                value = transpose( value );
            end

            % Retrieve tabs
            tabs = obj.Tabs;

            % Check
            assert( iscellstr( value ) && ...
                isequal( size( value ), size( tabs ) ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''TabTitles'' should be a cell array of strings, one per tab.' )

            % Set
            n = numel( tabs );
            for ii = 1:n
                tabs(ii).String = value{ii};
            end

            % Mark as dirty
            obj.TabHeight = -1;
            obj.Dirty = true;

        end % set.TabTitles

        function value = get.TabContextMenus( obj )

            tabs = obj.Tabs;
            n = numel( tabs );
            value = cell( [n 1] );
            for ii = 1:n
                value{ii} = tabs(ii).UIContextMenu;
            end

        end % get.TabContextMenus

        function set.TabContextMenus( obj, value )

            tabs = obj.Tabs;
            n = numel( tabs );
            for ii = 1:n
                tabs(ii).UIContextMenu = value{ii};
            end

        end % set.TabContextMenus

        function value = get.TabWidth( obj )

            value = obj.TabWidth_;

        end % get.TabWidth

        function set.TabWidth( obj, value )

            % Check
            assert( isa( value, 'double' ) && isscalar( value ) && ...
                isreal( value ) && ~isinf( value ) && ...
                ~isnan( value ) && value ~= 0, ...
                'uix:InvalidPropertyValue', ...
                'Property ''TabWidth'' must be a non-zero scalar.' )

            % Set
            obj.TabWidth_ = value;

            % Mark as dirty
            obj.Dirty = true;

        end % set.TabWidth

    end % accessors

    methods( Access = protected )

        function redraw( obj )

            % Compute positions
            bounds = hgconvertunits( ancestor( obj, 'figure' ), ...
                [0 0 1 1], 'normalized', 'pixels', obj );
            w = ceil( bounds(1) + bounds(3) ) - floor( bounds(1) ); % width
            h = ceil( bounds(2) + bounds(4) ) - floor( bounds(2) ); % height
            p = obj.Padding_; % padding
            tabs = obj.Tabs;
            n = numel( tabs ); % number of tabs
            tH = obj.TabHeight; % tab height
            if tH == -1 % cache stale, refresh
                if n > 0
                    cTabExtents = get( tabs, {'Extent'} );
                    tabExtents = vertcat( cTabExtents{:} );
                    tH = max( tabExtents(:,4) );
                end
                tH = max( tH, obj.TabMinimumHeight ); % apply minimum
                tH = ceil( tH ); % round up
                obj.TabHeight = tH; % store
            end
            cH = max( [h - 2 * p - tH, 1] ); % contents height
            switch obj.TabLocation_
                case 'top'
                    cY = 1 + p; % contents y
                    tY = cY + cH + p; % tab y
                case 'bottom'
                    tY = 1; % tab y
                    cY = tY + tH + p; % contents y
            end
            cX = 1 + p; % contents x
            cW = max( [w - 2 * p, 1] ); % contents width
            tW = obj.TabWidth_; % tab width
            dW = obj.DividerWidth; % tab divider width
            if tW < 0 && n > 0 % relative
                tW = max( ( w - (n+1) * dW ) / n, 1 );
            end
            tW = ceil( tW ); % round up
            for ii = 1:n
                tabs(ii).Position = [1 + (ii-1) * tW + ii * dW, tY, tW, tH];
            end
            obj.Dividers.Position = [0 tY w+1 tH];
            contentsPosition = [cX cY cW cH];

            % Redraw tabs
            obj.redrawTabs()

            % Redraw contents
            selection = obj.Selection_;
            if selection ~= 0 && strcmp( obj.TabEnables{selection}, 'on' )
                uix.setPosition( obj.Contents_(selection), contentsPosition, 'pixels' )
            end

        end % redraw

        function addChild( obj, child )
            %addChild  Add child
            %
            %  c.addChild(d) adds the child d to the container c.

            % Create new tab
            n = numel( obj.Tabs );
            tab = matlab.ui.control.UIControl( 'Internal', true, ...
                'Parent', obj, 'Style', 'text', 'Enable', 'inactive', ...
                'Units', 'pixels', 'FontUnits', obj.FontUnits_, ...
                'FontSize', obj.FontSize_, 'FontName', obj.FontName_, ...
                'FontAngle', obj.FontAngle_, 'FontWeight', obj.FontWeight_, ...
                'ForegroundColor', obj.ForegroundColor_, ...
                'String', sprintf( 'Page %d', n + 1 ) );
            tabListener = event.listener( tab, 'ButtonDown', @obj.onTabClicked );
            obj.Tabs(n+1,:) = tab;
            obj.TabListeners(n+1,:) = tabListener;

            % Mark as dirty
            obj.TabHeight = -1;

            % Check for bug
            if verLessThan( 'MATLAB', '8.5' ) && strcmp( child.Visible, 'off' )
                obj.G1218142 = true;
            end

            % Select new content
            oldSelection = obj.Selection_;
            if numel( obj.Contents_ ) == 0
                newSelection = 1;
                obj.Selection_ = newSelection;
            else
                newSelection = oldSelection;
            end

            % Call superclass method
            addChild@uix.mixin.Container( obj, child )

            % Show selected child
            obj.showSelection()

            % Notify selection change
            if oldSelection ~= newSelection
                obj.notify( 'SelectionChanged', ...
                    uix.SelectionData( oldSelection, newSelection ) )
            end

        end % addChild

        function removeChild( obj, child )
            %removeChild  Remove child
            %
            %  c.removeChild(d) removes the child d from the container c.

            % Find index of removed child
            contents = obj.Contents_;
            index = find( contents == child );

            % Remove tab
            delete( obj.Tabs(index) )
            obj.Tabs(index,:) = [];
            obj.TabListeners(index,:) = [];

            % Call superclass method
            removeChild@uix.mixin.Panel( obj, child )

        end % removeChild

        function reorder( obj, indices )
            %reorder  Reorder contents
            %
            %  c.reorder(i) reorders the container contents using indices
            %  i, c.Contents = c.Contents(i).

            % Reorder
            obj.Tabs = obj.Tabs(indices,:);
            obj.TabListeners = obj.TabListeners(indices,:);

            % Call superclass method
            reorder@uix.mixin.Panel( obj, indices )

        end % reorder

        function reparent( obj, oldFigure, newFigure )
            %reparent  Reparent container
            %
            %  c.reparent(a,b) reparents the container c from the figure a
            %  to the figure b.

            if ~isequal( oldFigure, newFigure )
                contextMenus = obj.TabContextMenus;
                for ii = 1:numel( contextMenus )
                    contextMenu = contextMenus{ii};
                    if ~isempty( contextMenu )
                        contextMenu.Parent = newFigure;
                    end
                end
            end

            % Call superclass method
            reparent@uix.mixin.Panel( obj, oldFigure, newFigure )

        end % reparent

        function showSelection( obj )
            %showSelection  Show selected child, hide the others
            %
            %  c.showSelection() shows the selected child of the container
            %  c, and hides the others.

            % Call superclass method
            showSelection@uix.mixin.Panel( obj )

            % If not enabled, hide selected contents too
            selection = obj.Selection_;
            if selection ~= 0 && strcmp( obj.TabEnables{selection}, 'off' )
                child = obj.Contents_(selection);
                child.Visible = 'off';
                if isa( child, 'matlab.graphics.axis.Axes' )
                    child.ContentsVisible = 'off';
                end
                % As a remedy for g1100294, move off-screen too
                margin = 1000;
                if isa( child, 'matlab.graphics.axis.Axes' ) ...
                        && strcmp(child.ActivePositionProperty, 'outerposition' )
                    child.OuterPosition(1) = -child.OuterPosition(3)-margin;
                else
                    child.Position(1) = -child.Position(3)-margin;
                end
            end

        end % showSelection

    end % template methods

    methods( Access = private )

        function redrawTabs( obj )
            %redrawTabs  Redraw tabs
            %
            %  p.redrawTabs() redraws the tabs.

            % Get relevant properties
            selection = obj.Selection_;
            tabs = obj.Tabs;
            t = numel( tabs );
            dividers = obj.Dividers;

            % Handle no tabs as a special case
            if t == 0
                dividers.Visible = 'off'; % hide
                return
            end

            % Repaint tabs
            backgroundColor = obj.BackgroundColor;
            for ii = 1:t
                tab = tabs(ii);
                if ii == selection
                    tab.BackgroundColor = backgroundColor;
                else
                    tab.BackgroundColor = obj.Tint * backgroundColor;
                end
            end

            % Repaint dividers
            d = t + 1;
            dividerNames = repmat( 'F', [d 2] ); % initialize
            dividerNames(1,1) = 'E'; % end
            dividerNames(end,2) = 'E'; % end
            if selection ~= 0
                dividerNames(selection,2) = 'T'; % selected
                dividerNames(selection+1,1) = 'T'; % selected
            end
            tH = obj.TabHeight;
            assert( tH >= obj.TabMinimumHeight, 'uix:InvalidState', ...
                'Cannot redraw tabs with invalid TabHeight.' )
            tW = obj.Tabs(1).Position(3);
            dW = obj.DividerWidth;
            allCData = zeros( [tH 0 3] ); % initialize
            map = [obj.ShadowColor; obj.BackgroundColor; ...
                obj.Tint * obj.BackgroundColor; obj.HighlightColor;...
                obj.ParentBackgroundColor];
            for ii = 1:d
                % Select mask
                iMask = obj.DividerMask.( dividerNames(ii,:) );
                % Resize
                iData = repmat( iMask(5,:), [tH 1] );
                iData(1:4,:) = iMask(1:4,:);
                iData(end-3:end,:) = iMask(end-3:end,:);
                % Convert to RGB
                cData = ind2rgb( iData+1, map );
                % Orient
                switch obj.TabLocation_
                    case 'bottom'
                        cData = flipud( cData );
                end
                % Insert
                allCData(1:tH,(ii-1)*(dW+tW)+(1:dW),:) = cData; % center
                if ii > 1 % extend left under transparent uicontrol edge
                    allCData(1:tH,(ii-1)*(dW+tW),:) = cData(:,1,:);
                end
                if ii < d % extend right under transparent uicontrol edge
                    allCData(1:tH,(ii-1)*(dW+tW)+dW+1,:) = cData(:,end,:);
                end
            end
            dividers.CData = allCData; % paint
            dividers.BackgroundColor = obj.ParentBackgroundColor;
            dividers.Visible = 'on'; % show

        end % redrawTabs

    end % helper methods

    methods( Access = private )

        function onTabClicked( obj, source, ~ )

            % Update selection
            oldSelection = obj.Selection_;
            newSelection = find( source == obj.Tabs );
            if oldSelection == newSelection, return, end % abort set
            obj.Selection_ = newSelection;

            % Show selected child
            obj.showSelection()

            % Mark as dirty
            obj.Dirty = true;

            % Notify selection change
            obj.notify( 'SelectionChanged', ...
                uix.SelectionData( oldSelection, newSelection ) )

        end % onTabClicked

        function onBackgroundColorChange( obj, ~, ~ )

            % Mark as dirty
            obj.Dirty = true;

        end % onBackgroundColorChange

        function onSelectionChanged( obj, source, eventData )

            % Call callback
            callback = obj.SelectionChangedFcn;
            if ischar( callback ) && isequal( callback, '' )
                % do nothing
            elseif ischar( callback )
                feval( callback, source, eventData )
            elseif isa( callback, 'function_handle' )
                callback( source, eventData )
            elseif iscell( callback )
                feval( callback{1}, source, eventData, callback{2:end} )
            end

        end % onSelectionChanged

        function onParentChanged( obj, ~, ~ )

            % Update ParentBackgroundColor and ParentBackgroundColor
            if isprop( obj.Parent, 'BackgroundColor' )
                prop = 'BackgroundColor';
            elseif isprop( obj.Parent, 'Color' )
                prop = 'Color';
            else
                prop = [];
            end

            if ~isempty( prop )
                obj.ParentBackgroundColorListener = event.proplistener( obj.Parent, ...
                    findprop( obj.Parent, prop ), 'PostSet', ...
                    @( src, evt ) obj.updateParentBackgroundColor( prop ) );
            else
                obj.ParentBackgroundColorListener = [];
            end

            obj.updateParentBackgroundColor( prop );

        end % onParentChanged

        function updateParentBackgroundColor( obj, prop )

            if isempty( prop )
                obj.ParentBackgroundColor = obj.BackgroundColor;
            else
                obj.ParentBackgroundColor = obj.Parent.(prop);
            end

            % Mark as dirty
            obj.Dirty = true;

        end

    end % event handlers

    methods( Access = private, Static )

        function mask = getDividerMask()
            %getDividerMask  Get divider image data
            %
            %  m = uix.TabPanel.getDividerMask() returns the image masks
            %  for tab panel dividers.  Mask entries are 0 (shadow), 1
            %  (background), 2 (tint) and 3 (highlight).

            mask.EF = indexColor( uix.loadIcon( 'tab_NoEdge_NotSelected.png' ) );
            mask.ET = indexColor( uix.loadIcon( 'tab_NoEdge_Selected.png' ) );
            mask.FE = indexColor( uix.loadIcon( 'tab_NotSelected_NoEdge.png' ) );
            mask.FF = indexColor( uix.loadIcon( 'tab_NotSelected_NotSelected.png' ) );
            mask.FT = indexColor( uix.loadIcon( 'tab_NotSelected_Selected.png' ) );
            mask.TE = indexColor( uix.loadIcon( 'tab_Selected_NoEdge.png' ) );
            mask.TF = indexColor( uix.loadIcon( 'tab_Selected_NotSelected.png' ) );

            function mask = indexColor( rgbMap )
                %indexColor  Returns a map of index given an RGB map
                %
                %  mask = indexColor( rgbMap ) returns a mask of color
                %  index based on the supplied rgbMap.
                %  black  : 0
                %  red    : 1
                %  yellow : 2
                %  white  : 3
                %  blue   : 4
                mask = nan( size( rgbMap, 1 ),size( rgbMap, 2 ) );
                % Black
                colorIndex = isColor( rgbMap, [0 0 0] );
                mask(colorIndex) = 0;
                % Red
                colorIndex = isColor( rgbMap, [1 0 0] );
                mask(colorIndex) = 1;
                % Yellow
                colorIndex = isColor( rgbMap, [1 1 0] );
                mask(colorIndex) = 2;
                % White
                colorIndex = isColor( rgbMap, [1 1 1] );
                mask(colorIndex) = 3;
                % Blue
                colorIndex = isColor( rgbMap, [0 0 1] );
                mask(colorIndex) = 4;
                % Nested
                function boolMap = isColor( map, color )
                    %isColor  Return a map of boolean where map is equal to color
                    boolMap = all( bsxfun( @eq, map, permute( color, [1 3 2] ) ), 3 );
                end
            end

        end % getDividerMask

    end % static helper methods

end % classdef


function ts = loadTimestamps(ts_dir)

fid = fopen([ts_dir '/timestamps.txt']);
col = textscan(fid,'%s\n',-1,'delimiter',',');
ts = col{1};
fclose(fid);


function varargout = help1(varargin)
% HELP1 M-file for help1.fig
%      HELP1, by itself, creates a new HELP1 or raises the existing
%      singleton*.
%
%      H = HELP1 returns the handle to a new HELP1 or the handle to
%      the existing singleton*.
%
%      HELP1('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in HELP1.M with the given input arguments.
%
%      HELP1('Property','Value',...) creates a new HELP1 or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before help1_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to help1_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

% Copyright 2002-2003 The MathWorks, Inc.

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

% Last Modified by GUIDE v2.5 06-Feb-2008 22:05:36

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @help1_OpeningFcn, ...
                   'gui_OutputFcn',  @help1_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(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

% --- Executes just before help1 is made visible.
function help1_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 help1 (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = help1_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;

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


function opti_Install_Help()
%OPTI_INSTALL_HELP  Build and save the OPTI help database

%You Must be in the OPTI Directory!
builddocsearchdb ([cd '\Help\OPTI_HTML'])


ngname1 = 'comp.windows.x';
ngname2 = 'comp.graphics';
load_20nggeneral;


% Demo script for fitpath.m
%
% Example:
%   demo
%
% Will bring up the demonstration GUI. Click on the button, browse for a file with
% a long path and see it truncated in the GUI. Don't worry it won't do anything
% with the actual file.

%=================================================================================
%
%        AUTHOR: Erik Newton (Newtek Software Ltd)
%
%           WEB: www.newteksoftware.co.uk
%
%	Copyright Newtek Software Ltd 2006
%
% This function is free for all use, but please leave in my credit.
% Check out more tutorials & functions at our website.
%
%==================================================================================

h_figure = figure(...
   'Name','fitpath demo', ...
   'MenuBar','none', ...
   'NumberTitle','Off', ...
   'Position',[50 50 260 30], ...
   'Resize','Off');

LABEL_BACK = get(h_figure,'Color');

% Init filename
uicontrol(h_figure, ...
   'BackgroundColor',LABEL_BACK, ...
   'Position', [5 5 30 18], ...
   'Horizontal', 'Right', ...
   'String','File:', ...
   'Style','text');
h_filename = uicontrol(h_figure, ...
   'BackgroundColor',LABEL_BACK, ...
   'Position',[35 5 200 18], ...
   'Horizontal', 'Left', ...
   'Style','text', ...
   'Tag','InitFilename');
uicontrol(h_figure, ...
   'Position', [235 5 20 18], ...
   'Horizontal', 'Center', ...
   ...'Callback', '[init_file,new_path]=uigetfile; set(h_filename,''string'',fullfile(new_path,init_file));', ...
   'Callback', '[init_file,new_path]=uigetfile; fitpath(h_filename,fullfile(new_path,init_file));', ...
   'String','...', ...
   'TooltipString', 'Select file.', ...
   'Style','PushButton');

%==================================================================================


function startup()
% startup()
% --------------------------------------------------------
% R-FCN implementation
% Modified from MATLAB Faster R-CNN (https://github.com/shaoqingren/faster_rcnn)
% Copyright (c) 2016, Jifeng Dai
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------

    curdir = fileparts(mfilename('fullpath'));
    addpath(genpath(fullfile(curdir, 'utils')));
    addpath(genpath(fullfile(curdir, 'functions')));
    addpath(genpath(fullfile(curdir, 'bin')));
    addpath(genpath(fullfile(curdir, 'experiments')));
    addpath(genpath(fullfile(curdir, 'imdb')));

    mkdir_if_missing(fullfile(curdir, 'datasets'));

    mkdir_if_missing(fullfile(curdir, 'external'));

    caffe_path = fullfile(curdir, 'external', 'caffe', 'matlab');
    if exist(caffe_path, 'dir') == 0
        error('matcaffe is missing from external/caffe/matlab; See README.md');
    end
    addpath(genpath(caffe_path));

    mkdir_if_missing(fullfile(curdir, 'imdb', 'cache'));

    mkdir_if_missing(fullfile(curdir, 'output'));

    mkdir_if_missing(fullfile(curdir, 'models'));

    fprintf('rfcn startup done\n');
end


%  INTERNAL FUNCTION
%
%  see also mygrid
%


classdef surfPrinter < figurePrinter

     properties (Access = private)

    end

    methods (Access = public)

        function obj = surfPrinter(figureID)
            obj.init(figureID);
            obj.setFontSizes();
            obj.setPositionAndSize();
        end

    end

    methods (Access = private)

        function init(obj,figureID)
            obj.figID = figureID;
        end

    end

end


function [ind,indf] = get_index(d),
  ind= d.index;
  indf = d.findex;


function mrSESSION = mrvMakeEmptySession;
%
% mrSESSION = mrvMakeEmptySession: [no arguments]
%
% Create a mrSESSION struct without
% any functionals assigned, for pseudo-realtime.
%
%
% ras 04/05.

[p f] = fileparts(pwd);

mrSESSION.mrLoadRetVersion = '3.10'; % I figure it's updated at to least that :)
mrSESSION.sessionCode = f;
mrSESSION.description = 'mrvTurbo';
mrSESSION.subject = '';
mrSESSION.examNum = '';
mrSESSION.inplanes = [];
mrSESSION.functionals = [];

dataTYPES.name = 'Original';

vANATOMYPATH = '';

save mrSESSION mrSESSION dataTYPES

return


function fails = failedtests(results)

    tr = table(results);

    f = string( tr(tr.Failed,:).Name );

    f = arrayfun( @(x) extractBefore(x, "/"), f);

    fails = unique(f);
end


function status = fseek( fid, offset, origin )
%FSEEK Set file position indicator.
% STATUS = FSEEK(FID, OFFSET, ORIGIN) mimics the behavior of MATLAB's FSEEK
% function, but allows for seeking past the end of a file (just appends
% zeros to the end of the file until it reaches desired location).
%
%   OFFSET values are interpreted as follows:
%       >= 0   Move position indicator OFFSET bytes after ORIGIN.
%       < 0    Move position indicator OFFSET bytes before ORIGIN.
%
%   ORIGIN values are interpreted as follows:
%       'bof' or -1   Beginning of file
%       'cof' or  0   Current position in file
%       'eof' or  1   End of file
%
%   STATUS is 0 on success and -1 on failure.  If an error occurs, use
%   FERROR to get more information.
%
% Written by: Wade Schwartzkopf, NGA/IDT
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

status = fseek(fid, offset, origin); % Try MATLAB's fseek first
if status < 0 % Didn't work
    [message, errnum] = ferror(fid);
    if errnum == -27 % "Offset is bad - after end-of-file or last character written."
        % This is not an error in our case.  We will do special handling to
        % allow this fseek to skip to position past current end of file.
        switch origin
            case {-1, 'bof'}
                offset = offset - ftell(fid); % Convert offset to be from current position, not beginning of file
            case {0, 'cof'} % No change required
            case {1, 'eof'}
                fseek(fid,0,'eof');
        end
        if offset>0
            % Use fwrite skip parameter to append to end of file an
            % arbitrary amount
            status = -(fwrite(fid, uint8(0), 'uint8', offset-1) ~= 1);
        end
    end
end

end

% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////


classdef Tx < adi.AD9144.Tx
    % adi.DAQ2.Tx Transmit data from the DAQ2 evaluation platform
    %   The adi.DAQ2.Tx System object is a signal source that can
    %   send complex data to the DAQ2.
    %
    %   tx = adi.DAQ2.Tx;
    %   tx = adi.DAQ2.Tx('uri','192.168.2.1');
    %
    %   User Guide
    %
    %   See also adi.AD9144.Tx, adi.DAQ2.Rx
    methods
        %% Constructor
        function obj = Tx(varargin)
            % Returns the matlabshared.libiio.base object
            coder.allowpcode('plain');
            obj = obj@adi.AD9144.Tx(varargin{:});
        end
    end

end


function [string, file_name] = user_string(string_name, string)
%USER_STRING  Get/set a user specific string
%
% Examples:
%   string  = user_string(string_name)
%   isSaved = user_string(string_name, new_string)
%   [value, file_name] = user_string(...)
%
% Function to get and set a string in a system or user specific file. This
% enables, for example, system specific paths to binaries to be saved.
%
% The specified string will be saved in a file named <string_name>.txt,
% either in a subfolder named .ignore under this file's folder, or in the
% user's prefdir folder (in case this file's folder is non-writable).
%
% IN:
%   string_name - String containing the name of the string required, which
%                 sets the filename storing the string: <string_name>.txt
%   new_string  - The new string to be saved in the <string_name>.txt file
%
% OUT:
%   string  - The currently saved string. Default: ''
%   isSaved - Boolean indicating whether the save was succesful
%   file_name - path of the .txt file used to contain the requested string

% Copyright (C) Oliver Woodford 2011-2014, Yair Altman 2015-

% This method of saving paths avoids changing .m files which might be in a
% version control system. Instead it saves the user dependent paths in
% separate files with a .txt extension, which need not be checked in to
% the version control system. Thank you to Jonas Dorn for suggesting this
% approach.

% 10/01/2013 - Access files in text, not binary mode, as latter can cause
%              errors. Thanks to Christian for pointing this out.
% 29/05/2015 - Save file in prefdir if current folder is non-writable (issue #74)
% 09/01/2018 - Fix issue #232: if the string looks like a file/folder path, ensure it actually exists
% 15/01/2020 - Added file_name output argument

    if ~ischar(string_name)
        error('string_name must be a string.');
    end
    % Create the full filename
    fname = [string_name '.txt'];
    dname = fullfile(fileparts(mfilename('fullpath')), '.ignore');
    file_name = fullfile(dname, fname);
    default_file_name = file_name;
    if nargin > 1
        % Set string
        if ~ischar(string)
            error('new_string must be a string.');
        end
        % Make sure the save directory exists
        %dname = fileparts(file_name);
        if ~exist(dname, 'dir')
            % Create the directory
            try
                if ~mkdir(dname)
                    string = false;
                    return
                end
            catch
                string = false;
                return
            end
            % Make it hidden
            try
                fileattrib(dname, '+h');
            catch
            end
        end
        % Write the file
        fid = fopen(file_name, 'wt');
        if fid == -1
            % file cannot be created/updated - use prefdir if file does not already exist
            % (if file exists but is simply not writable, don't create a duplicate in prefdir)
            if ~exist(file_name,'file')
                file_name = fullfile(prefdir, fname);
                fid = fopen(file_name, 'wt');
            end
            if fid == -1
                string = false;
                file_name = default_file_name;
                return
            end
        end
        try
            fprintf(fid, '%s', string);
        catch
            fclose(fid);
            string = false;
            return
        end
        fclose(fid);
        string = true;
    else
        % Get string
        fid = fopen(file_name, 'rt');
        if fid == -1
            % file cannot be read, try to read the file in prefdir
            file_name = fullfile(prefdir, fname);
            fid = fopen(file_name, 'rt');
            if fid == -1
                string = '';
                file_name = default_file_name;
                return
            end
        end
        string = fgetl(fid);
        fclose(fid);

        % Fix issue #232: if the string looks like a file/folder path, ensure it actually exists
        if ~isempty(string) && any(string=='\' | string=='/') && ~exist(string) %#ok<EXIST>
            string = '';
        end
    end
end


classdef EventWithJointLimits < Simulink.IntEnumType
    %EVENTWITHJOINTLIMITS Class for selecting a None, Warning or EmergencyStop signal
    %
    %   Class for selecting a None, Warning or EmergencyStop signal triggered by the joints hitting
    %   the limits.

    enumeration
        None(0)
        Warning(1)
        EmergencyStop(2)
    end
end


function navego_print_version()

versionstr = 'NaveGo, release v1.3';

fprintf('\n%s.\n', versionstr)

end