%EXPORT_FIG  Exports figures suitable for publication
%
% Examples:
%   im = export_fig
%   [im alpha] = export_fig
%   export_fig filename
%   export_fig filename -format1 -format2
%   export_fig ... -nocrop
%   export_fig ... -transparent
%   export_fig ... -native
%   export_fig ... -m<val>
%   export_fig ... -r<val>
%   export_fig ... -a<val>
%   export_fig ... -q<val>
%   export_fig ... -<renderer>
%   export_fig ... -<colorspace>
%   export_fig ... -append
%   export_fig ... -bookmark
%   export_fig(..., handle)
%
% This function saves a figure or single axes to one or more vector and/or
% bitmap file formats, and/or outputs a rasterized version to the
% workspace, with the following properties:
%   - Figure/axes reproduced as it appears on screen
%   - Cropped borders (optional)
%   - Embedded fonts (vector formats)
%   - Improved line and grid line styles
%   - Anti-aliased graphics (bitmap formats)
%   - Render images at native resolution (optional for bitmap formats)
%   - Transparent background supported (pdf, eps, png)
%   - Semi-transparent patch objects supported (png only)
%   - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff)
%   - Variable image compression, including lossless (pdf, eps, jpg)
%   - Optionally append to file (pdf, tiff)
%   - Vector formats: pdf, eps
%   - Bitmap formats: png, tiff, jpg, bmp, export to workspace
%
% This function is especially suited to exporting figures for use in
% publications and presentations, because of the high quality and
% portability of media produced.
%
% Note that the background color and figure dimensions are reproduced
% (the latter approximately, and ignoring cropping & magnification) in the
% output file. For transparent background (and semi-transparent patch
% objects), use the -transparent option or set the figure 'Color' property
% to 'none'. To make axes transparent set the axes 'Color' property to
% 'none'. Pdf, eps and png are the only file formats to support a
% transparent background, whilst the png format alone supports transparency
% of patch objects.
%
% The choice of renderer (opengl, zbuffer or painters) has a large impact
% on the quality of output. Whilst the default value (opengl for bitmaps,
% painters for vector formats) generally gives good results, if you aren't
% satisfied then try another renderer.  Notes: 1) For vector formats (eps,
% pdf), only painters generates vector graphics. 2) For bitmaps, only
% opengl can render transparent patch objects correctly. 3) For bitmaps,
% only painters will correctly scale line dash and dot lengths when
% magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when
% using painters.
%
% When exporting to vector format (pdf & eps) and bitmap format using the
% painters renderer, this function requires that ghostscript is installed
% on your system. You can download this from:
%   http://www.ghostscript.com
% When exporting to eps it additionally requires pdftops, from the Xpdf
% suite of functions. You can download this from:
%   http://www.foolabs.com/xpdf
%
%IN:
%   filename - string containing the name (optionally including full or
%              relative path) of the file the figure is to be saved as. If
%              a path is not specified, the figure is saved in the current
%              directory. If no name and no output arguments are specified,
%              the default name, 'export_fig_out', is used. If neither a
%              file extension nor a format are specified, a ".png" is added
%              and the figure saved in that format.
%   -format1, -format2, etc. - strings containing the extensions of the
%                              file formats the figure is to be saved as.
%                              Valid options are: '-pdf', '-eps', '-png',
%                              '-tif', '-jpg' and '-bmp'. All combinations
%                              of formats are valid.
%   -nocrop - option indicating that the borders of the output are not to
%             be cropped.
%   -transparent - option indicating that the figure background is to be
%                  made transparent (png, pdf and eps output only).
%   -m<val> - option where val indicates the factor to magnify the
%             on-screen figure pixel dimensions by when generating bitmap
%             outputs. Default: '-m1'.
%   -r<val> - option val indicates the resolution (in pixels per inch) to
%             export bitmap and vector outputs at, keeping the dimensions
%             of the on-screen figure. Default: '-r864' (for vector output
%             only). Note that the -m option overides the -r option for
%             bitmap outputs only.
%   -native - option indicating that the output resolution (when outputting
%             a bitmap format) should be such that the vertical resolution
%             of the first suitable image found in the figure is at the
%             native resolution of that image. To specify a particular
%             image to use, give it the tag 'export_fig_native'. Notes:
%             This overrides any value set with the -m and -r options. It
%             also assumes that the image is displayed front-to-parallel
%             with the screen. The output resolution is approximate and
%             should not be relied upon. Anti-aliasing can have adverse
%             effects on image quality (disable with the -a1 option).
%   -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to
%                        use for bitmap outputs. '-a1' means no anti-
%                        aliasing; '-a4' is the maximum amount (default).
%   -<renderer> - option to force a particular renderer (painters, opengl
%                 or zbuffer) to be used over the default: opengl for
%                 bitmaps; painters for vector formats.
%   -<colorspace> - option indicating which colorspace color figures should
%                   be saved in: RGB (default), CMYK or gray. CMYK is only
%                   supported in pdf, eps and tiff output.
%   -q<val> - option to vary bitmap image quality (in pdf, eps and jpg
%             files only).  Larger val, in the range 0-100, gives higher
%             quality/lower compression. val > 100 gives lossless
%             compression. Default: '-q95' for jpg, ghostscript prepress
%             default for pdf & eps. Note: lossless compression can
%             sometimes give a smaller file size than the default lossy
%             compression, depending on the type of images.
%   -append - option indicating that if the file (pdfs only) already
%             exists, the figure is to be appended as a new page, instead
%             of being overwritten (default).
%   -bookmark - option to indicate that a bookmark with the name of the
%               figure is to be created in the output file (pdf only).
%   handle - The handle of the figure, axes or uipanels (can be an array of
%            handles, but the objects must be in the same figure) to be
%            saved. Default: gcf.
%
%OUT:
%   im - MxNxC uint8 image array of the figure.
%   alpha - MxN single array of alphamatte values in range [0,1], for the
%           case when the background is transparent.
%
%   Some helpful examples and tips can be found at:
%      http://sites.google.com/site/oliverwoodford/software/export_fig
%
%   See also PRINT, SAVEAS.

% Copyright (C) Oliver Woodford 2008-2014

% The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG
% (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782).
% The idea for using pdftops came from the MATLAB newsgroup (id: 168171).
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928).
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id:
% 20979).
% The idea of appending figures in pdfs came from Matt C in comments on the
% FEX (id: 23629)

% Thanks to Roland Martin for pointing out the colour MATLAB
% bug/feature with colorbar axes and transparent backgrounds.
% Thanks also to Andrew Matthews for describing a bug to do with the figure
% size changing in -nodisplay mode. I couldn't reproduce it, but included a
% fix anyway.
% Thanks to Tammy Threadgill for reporting a bug where an axes is not
% isolated from gui objects.

% 23/02/12: Ensure that axes limits don't change during printing
% 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for
%           reporting it).
% 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling
%           bookmarking of figures in pdf files.
% 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep
%           tick marks fixed.
% 12/12/12: Add support for isolating uipanels. Thanks to michael for
%           suggesting it.
% 25/09/13: Add support for changing resolution in vector formats. Thanks
%           to Jan Jaap Meijer for suggesting it.
% 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner
%           for suggesting it.

function [im, alpha] = export_fig(varargin)
% Make sure the figure is rendered correctly _now_ so that properties like
% axes limits are up-to-date.
drawnow;
% Parse the input arguments
[fig, options] = parse_args(nargout, varargin{:});
% Isolate the subplot, if it is one
cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'}));
if cls
    % Given handles of one or more axes, so isolate them from the rest
    fig = isolate_axes(fig);
else
    % Check we have a figure
    if ~isequal(get(fig, 'Type'), 'figure');
        error('Handle must be that of a figure, axes or uipanel');
    end
    % Get the old InvertHardcopy mode
    old_mode = get(fig, 'InvertHardcopy');
end
% Hack the font units where necessary (due to a font rendering bug in
% print?). This may not work perfectly in all cases. Also it can change the
% figure layout if reverted, so use a copy.
magnify = options.magnify * options.aa_factor;
if isbitmap(options) && magnify ~= 1
    fontu = findobj(fig, 'FontUnits', 'normalized');
    if ~isempty(fontu)
        % Some normalized font units found
        if ~cls
            fig = copyfig(fig);
            set(fig, 'Visible', 'off');
            fontu = findobj(fig, 'FontUnits', 'normalized');
            cls = true;
        end
        set(fontu, 'FontUnits', 'points');
    end
end
% MATLAB "feature": axes limits and tick marks can change when printing
Hlims = findall(fig, 'Type', 'axes');
if ~cls
    % Record the old axes limit and tick modes
    Xlims = make_cell(get(Hlims, 'XLimMode'));
    Ylims = make_cell(get(Hlims, 'YLimMode'));
    Zlims = make_cell(get(Hlims, 'ZLimMode'));
    Xtick = make_cell(get(Hlims, 'XTickMode'));
    Ytick = make_cell(get(Hlims, 'YTickMode'));
    Ztick = make_cell(get(Hlims, 'ZTickMode'));
end
% Set all axes limit and tick modes to manual, so the limits and ticks can't change
set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual', 'XTickMode', 'manual', 'YTickMode', 'manual', 'ZTickMode', 'manual');
% Set to print exactly what is there
set(fig, 'InvertHardcopy', 'off');
% Set the renderer
switch options.renderer
    case 1
        renderer = '-opengl';
    case 2
        renderer = '-zbuffer';
    case 3
        renderer = '-painters';
    otherwise
        renderer = '-opengl'; % Default for bitmaps
end
% Do the bitmap formats first
if isbitmap(options)
    % Get the background colour
    if options.transparent && (options.png || options.alpha)
        % Get out an alpha channel
        % MATLAB "feature": black colorbar axes can change to white and vice versa!
        hCB = findobj(fig, 'Type', 'axes', 'Tag', 'Colorbar');
        if isempty(hCB)
            yCol = [];
            xCol = [];
        else
            yCol = get(hCB, 'YColor');
            xCol = get(hCB, 'XColor');
            if iscell(yCol)
                yCol = cell2mat(yCol);
                xCol = cell2mat(xCol);
            end
            yCol = sum(yCol, 2);
            xCol = sum(xCol, 2);
        end
        % MATLAB "feature": apparently figure size can change when changing
        % colour in -nodisplay mode
        pos = get(fig, 'Position');
        % Set the background colour to black, and set size in case it was
        % changed internally
        tcol = get(fig, 'Color');
        set(fig, 'Color', 'k', 'Position', pos);
        % Correct the colorbar axes colours
        set(hCB(yCol==0), 'YColor', [0 0 0]);
        set(hCB(xCol==0), 'XColor', [0 0 0]);
        % Print large version to array
        B = print2array(fig, magnify, renderer);
        % Downscale the image
        B = downsize(single(B), options.aa_factor);
        % Set background to white (and set size)
        set(fig, 'Color', 'w', 'Position', pos);
        % Correct the colorbar axes colours
        set(hCB(yCol==3), 'YColor', [1 1 1]);
        set(hCB(xCol==3), 'XColor', [1 1 1]);
        % Print large version to array
        A = print2array(fig, magnify, renderer);
        % Downscale the image
        A = downsize(single(A), options.aa_factor);
        % Set the background colour (and size) back to normal
        set(fig, 'Color', tcol, 'Position', pos);
        % Compute the alpha map
        alpha = round(sum(B - A, 3)) / (255 * 3) + 1;
        A = alpha;
        A(A==0) = 1;
        A = B ./ A(:,:,[1 1 1]);
        clear B
        % Convert to greyscale
        if options.colourspace == 2
            A = rgb2grey(A);
        end
        A = uint8(A);
        % Crop the background
        if options.crop
            [alpha, v] = crop_background(alpha, 0);
            A = A(v(1):v(2),v(3):v(4),:);
        end
        if options.png
            % Compute the resolution
            res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
            % Save the png
            imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
            % Clear the png bit
            options.png = false;
        end
        % Return only one channel for greyscale
        if isbitmap(options)
            A = check_greyscale(A);
        end
        if options.alpha
            % Store the image
            im = A;
            % Clear the alpha bit
            options.alpha = false;
        end
        % Get the non-alpha image
        if isbitmap(options)
            alph = alpha(:,:,ones(1, size(A, 3)));
            A = uint8(single(A) .* alph + 255 * (1 - alph));
            clear alph
        end
        if options.im
            % Store the new image
            im = A;
        end
    else
        % Print large version to array
        if options.transparent
            % MATLAB "feature": apparently figure size can change when changing
            % colour in -nodisplay mode
            pos = get(fig, 'Position');
            tcol = get(fig, 'Color');
            set(fig, 'Color', 'w', 'Position', pos);
            A = print2array(fig, magnify, renderer);
            set(fig, 'Color', tcol, 'Position', pos);
            tcol = 255;
        else
            [A, tcol] = print2array(fig, magnify, renderer);
        end
        % Crop the background
        if options.crop
            A = crop_background(A, tcol);
        end
        % Downscale the image
        A = downsize(A, options.aa_factor);
        if options.colourspace == 2
            % Convert to greyscale
            A = rgb2grey(A);
        else
            % Return only one channel for greyscale
            A = check_greyscale(A);
        end
        % Outputs
        if options.im
            im = A;
        end
        if options.alpha
            im = A;
            alpha = zeros(size(A, 1), size(A, 2), 'single');
        end
    end
    % Save the images
    if options.png
        res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
        imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
    end
    if options.bmp
        imwrite(A, [options.name '.bmp']);
    end
    % Save jpeg with given quality
    if options.jpg
        quality = options.quality;
        if isempty(quality)
            quality = 95;
        end
        if quality > 100
            imwrite(A, [options.name '.jpg'], 'Mode', 'lossless');
        else
            imwrite(A, [options.name '.jpg'], 'Quality', quality);
        end
    end
    % Save tif images in cmyk if wanted (and possible)
    if options.tif
        if options.colourspace == 1 && size(A, 3) == 3
            A = double(255 - A);
            K = min(A, [], 3);
            K_ = 255 ./ max(255 - K, 1);
            C = (A(:,:,1) - K) .* K_;
            M = (A(:,:,2) - K) .* K_;
            Y = (A(:,:,3) - K) .* K_;
            A = uint8(cat(3, C, M, Y, K));
            clear C M Y K K_
        end
        append_mode = {'overwrite', 'append'};
        imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1});
    end
end
% Now do the vector formats
if isvector(options)
    % Set the default renderer to painters
    if ~options.renderer
        renderer = '-painters';
    end
    % Generate some filenames
    tmp_nam = [tempname '.eps'];
    if options.pdf
        pdf_nam = [options.name '.pdf'];
    else
        pdf_nam = [tempname '.pdf'];
    end
    % Generate the options for print
    p2eArgs = {renderer, sprintf('-r%d', options.resolution)};
    if options.colourspace == 1
        p2eArgs = [p2eArgs {'-cmyk'}];
    end
    if ~options.crop
        p2eArgs = [p2eArgs {'-loose'}];
    end
    try
        % Generate an eps
        print2eps(tmp_nam, fig, p2eArgs{:});
        % Remove the background, if desired
        if options.transparent && ~isequal(get(fig, 'Color'), 'none')
            eps_remove_background(tmp_nam, 1 + using_hg2(fig));
        end
        % Add a bookmark to the PDF if desired
        if options.bookmark
            fig_nam = get(fig, 'Name');
            if isempty(fig_nam)
                warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.');
            end
            add_bookmark(tmp_nam, fig_nam);
        end
        % Generate a pdf
        eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);
    catch ex
        % Delete the eps
        delete(tmp_nam);
        rethrow(ex);
    end
    % Delete the eps
    delete(tmp_nam);
    if options.eps
        try
            % Generate an eps from the pdf
            pdf2eps(pdf_nam, [options.name '.eps']);
        catch ex
            if ~options.pdf
                % Delete the pdf
                delete(pdf_nam);
            end
            rethrow(ex);
        end
        if ~options.pdf
            % Delete the pdf
            delete(pdf_nam);
        end
    end
end
if cls
    % Close the created figure
    close(fig);
else
    % Reset the hardcopy mode
    set(fig, 'InvertHardcopy', old_mode);
    % Reset the axes limit and tick modes
    for a = 1:numel(Hlims)
        set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a}, 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a});
    end
end
return

function [fig, options] = parse_args(nout, varargin)
% Parse the input arguments
% Set the defaults
fig = get(0, 'CurrentFigure');
options = struct('name', 'export_fig_out', ...
                 'crop', true, ...
                 'transparent', false, ...
                 'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters
                 'pdf', false, ...
                 'eps', false, ...
                 'png', false, ...
                 'tif', false, ...
                 'jpg', false, ...
                 'bmp', false, ...
                 'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray
                 'append', false, ...
                 'im', nout == 1, ...
                 'alpha', nout == 2, ...
                 'aa_factor', 0, ...
                 'magnify', [], ...
                 'resolution', [], ...
                 'bookmark', false, ...
                 'quality', []);
native = false; % Set resolution to native of an image

% Go through the other arguments
for a = 1:nargin-1
    if all(ishandle(varargin{a}))
        fig = varargin{a};
    elseif ischar(varargin{a}) && ~isempty(varargin{a})
        if varargin{a}(1) == '-'
            switch lower(varargin{a}(2:end))
                case 'nocrop'
                    options.crop = false;
                case {'trans', 'transparent'}
                    options.transparent = true;
                case 'opengl'
                    options.renderer = 1;
                case 'zbuffer'
                    options.renderer = 2;
                case 'painters'
                    options.renderer = 3;
                case 'pdf'
                    options.pdf = true;
                case 'eps'
                    options.eps = true;
                case 'png'
                    options.png = true;
                case {'tif', 'tiff'}
                    options.tif = true;
                case {'jpg', 'jpeg'}
                    options.jpg = true;
                case 'bmp'
                    options.bmp = true;
                case 'rgb'
                    options.colourspace = 0;
                case 'cmyk'
                    options.colourspace = 1;
                case {'gray', 'grey'}
                    options.colourspace = 2;
                case {'a1', 'a2', 'a3', 'a4'}
                    options.aa_factor = str2double(varargin{a}(3));
                case 'append'
                    options.append = true;
                case 'bookmark'
                    options.bookmark = true;
                case 'native'
                    native = true;
                otherwise
                    val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q))(\d*\.)?\d+(e-?\d+)?', 'match'));
                    if ~isscalar(val)
                        error('option %s not recognised', varargin{a});
                    end
                    switch lower(varargin{a}(2))
                        case 'm'
                            options.magnify = val;
                        case 'r'
                            options.resolution = val;
                        case 'q'
                            options.quality = max(val, 0);
                    end
            end
        else
            [p, options.name, ext] = fileparts(varargin{a});
            if ~isempty(p)
                options.name = [p filesep options.name];
            end
            switch lower(ext)
                case {'.tif', '.tiff'}
                    options.tif = true;
                case {'.jpg', '.jpeg'}
                    options.jpg = true;
                case '.png'
                    options.png = true;
                case '.bmp'
                    options.bmp = true;
                case '.eps'
                    options.eps = true;
                case '.pdf'
                    options.pdf = true;
                otherwise
                    options.name = varargin{a};
            end
        end
    end
end

% Set default anti-aliasing now we know the renderer
if options.aa_factor == 0
    options.aa_factor = 1 + 2 * (~using_hg2(fig) | (options.renderer == 3));
end

% Convert user dir '~' to full path
if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\')
    options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end));
end

% Compute the magnification and resolution
if isempty(options.magnify)
    if isempty(options.resolution)
        options.magnify = 1;
        options.resolution = 864;
    else
        options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch');
    end
elseif isempty(options.resolution)
    options.resolution = 864;
end

% Check we have a figure handle
if isempty(fig)
    error('No figure found');
end

% Set the default format
if ~isvector(options) && ~isbitmap(options)
    options.png = true;
end

% Check whether transparent background is wanted (old way)
if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none')
    options.transparent = true;
end

% If requested, set the resolution to the native vertical resolution of the
% first suitable image found
if native && isbitmap(options)
    % Find a suitable image
    list = findobj(fig, 'Type', 'image', 'Tag', 'export_fig_native');
    if isempty(list)
        list = findobj(fig, 'Type', 'image', 'Visible', 'on');
    end
    for hIm = list(:)'
        % Check height is >= 2
        height = size(get(hIm, 'CData'), 1);
        if height < 2
            continue
        end
        % Account for the image filling only part of the axes, or vice
        % versa
        yl = get(hIm, 'YData');
        if isscalar(yl)
            yl = [yl(1)-0.5 yl(1)+height+0.5];
        else
            if ~diff(yl)
                continue
            end
            yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1));
        end
        hAx = get(hIm, 'Parent');
        yl2 = get(hAx, 'YLim');
        % Find the pixel height of the axes
        oldUnits = get(hAx, 'Units');
        set(hAx, 'Units', 'pixels');
        pos = get(hAx, 'Position');
        set(hAx, 'Units', oldUnits);
        if ~pos(4)
            continue
        end
        % Found a suitable image
        % Account for stretch-to-fill being disabled
        pbar = get(hAx, 'PlotBoxAspectRatio');
        pos = min(pos(4), pbar(2)*pos(3)/pbar(1));
        % Set the magnification to give native resolution
        options.magnify = (height * diff(yl2)) / (pos * diff(yl));
        break
    end
end
return

function A = downsize(A, factor)
% Downsample an image
if factor == 1
    % Nothing to do
    return
end
try
    % Faster, but requires image processing toolbox
    A = imresize(A, 1/factor, 'bilinear');
catch
    % No image processing toolbox - resize manually
    % Lowpass filter - use Gaussian as is separable, so faster
    % Compute the 1d Gaussian filter
    filt = (-factor-1:factor+1) / (factor * 0.6);
    filt = exp(-filt .* filt);
    % Normalize the filter
    filt = single(filt / sum(filt));
    % Filter the image
    padding = floor(numel(filt) / 2);
    for a = 1:size(A, 3)
        A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid');
    end
    % Subsample
    A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);
end
return

function A = rgb2grey(A)
A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A));
return

function A = check_greyscale(A)
% Check if the image is greyscale
if size(A, 3) == 3 && ...
        all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ...
        all(reshape(A(:,:,2) == A(:,:,3), [], 1))
    A = A(:,:,1); % Save only one channel for 8-bit output
end
return

function [A, v] = crop_background(A, bcol)
% Map the foreground pixels
[h, w, c] = size(A);
if isscalar(bcol) && c > 1
    bcol = bcol(ones(1, c));
end
bail = false;
for l = 1:w
    for a = 1:c
        if ~all(A(:,l,a) == bcol(a))
            bail = true;
            break;
        end
    end
    if bail
        break;
    end
end
bail = false;
for r = w:-1:l
    for a = 1:c
        if ~all(A(:,r,a) == bcol(a))
            bail = true;
            break;
        end
    end
    if bail
        break;
    end
end
bail = false;
for t = 1:h
    for a = 1:c
        if ~all(A(t,:,a) == bcol(a))
            bail = true;
            break;
        end
    end
    if bail
        break;
    end
end
bail = false;
for b = h:-1:t
    for a = 1:c
        if ~all(A(b,:,a) == bcol(a))
            bail = true;
            break;
        end
    end
    if bail
        break;
    end
end
% Crop the background, leaving one boundary pixel to avoid bleeding on
% resize
v = [max(t-1, 1) min(b+1, h) max(l-1, 1) min(r+1, w)];
A = A(v(1):v(2),v(3):v(4),:);
return

function eps_remove_background(fname, count)
% Remove the background of an eps file
% Open the file
fh = fopen(fname, 'r+');
if fh == -1
    error('Not able to open file %s.', fname);
end
% Read the file line by line
while count
    % Get the next line
    l = fgets(fh);
    if isequal(l, -1)
        break; % Quit, no rectangle found
    end
    % Check if the line contains the background rectangle
    if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1)
        % Set the line to whitespace and quit
        l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' ';
        fseek(fh, -numel(l), 0);
        fprintf(fh, l);
        % Reduce the count
        count = count - 1;
    end
end
% Close the file
fclose(fh);
return

function b = isvector(options)
b = options.pdf || options.eps;
return

function b = isbitmap(options)
b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
return

% Helper function
function A = make_cell(A)
if ~iscell(A)
    A = {A};
end
return

function add_bookmark(fname, bookmark_text)
% Adds a bookmark to the temporary EPS file after %%EndPageSetup
% Read in the file
fh = fopen(fname, 'r');
if fh == -1
    error('File %s not found.', fname);
end
try
    fstrm = fread(fh, '*char')';
catch ex
    fclose(fh);
    rethrow(ex);
end
fclose(fh);

% Include standard pdfmark prolog to maximize compatibility
fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse'));
% Add page bookmark
fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text));

% Write out the updated file
fh = fopen(fname, 'w');
if fh == -1
    error('Unable to open %s for writing.', fname);
end
try
    fwrite(fh, fstrm, 'char*1');
catch ex
    fclose(fh);
    rethrow(ex);
end
fclose(fh);
return


% VL_TEST_INIT  Intialize unit test file
%   This is a VLFeat internal function used to initialize an .m file
%   containing a unit test.
%
%   See also: VL_TEST(), VL_HELP().

% Author:: Andrea Vedaldi

% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% Copyright (C) 2013 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

% Obtain the path to the m-file that called VL_TEST_INIT()
stack = dbstack(1) ;
mfilePath = stack(1).file ;
mfileName = stack(1).name ;
fid = fopen(mfilePath, 'r') ;

% Parse the source code of the caller to get the names of its
% subfunctions. One could use which('-subfun', stack(1).name) here,
% but this feature is undocumented.

setupFunc = [] ;
teardownFunc = [] ;

tests = {} ;
l = 0 ;
t = 0 ;
while 1
  tline = fgetl(fid) ;
  l = l + 1 ;
  if ~ischar(tline), break ; end
  mo = regexp(tline, '^\s*function\s+(\w\s*=\s*)?test_(?<name>[\w_]+)\s*\(.*\).*$', ...
              'names') ;
  if length(mo) > 0
    t = t + 1 ;
    tests{t}.name = mo(1).name ;
    tests{t}.func = str2func(['test_' mo(1).name]) ;
    tests{t}.lineNumber = l ;
  end

  mo = regexp(tline, '^\s*function\s+(\w+\s*=\s*)?(?<name>setup|teardown)\s*\(.*\).*$', ...
              'names') ;
  if length(mo) > 0
    switch mo(1).name
      case 'setup'
        if isempty(setupFunc)
          setupFunc = @setup ;
        else
          warning('%s:%d: ignoring redundant definition of the setup function', ...
                  mfilePath) ;
        end
      case 'teardown'
        if isempty(teardownFunc)
          teardownFunc = @teardown ;
        else
          warning('%s:%d: ignoring redundant definition of the setup function', ...
                  mfilePath) ;
        end
      otherwise
        assert(0) ;
    end
  end
end

if ~isempty(setupFunc), state = setupFunc() ; end

if length(varargin) > 0
  testFunc = str2func(sprintf('test_%s', varargin{1})) ;
  if exist('state','var')
    testFunc(state) ;
  else
    testFunc() ;
  end
  if ~isempty(teardownFunc), teardownFunc(state) ; end
  return ;
end

% Run all tests collecting the results.
if length(tests) == 0
  error('No tests found in ''%s''', mfileName)  ;
end

for t = 1:length(tests)
  subTestName = sprintf('test_%s', tests{t}.name) ;
  results{t}.testName = sprintf('%s:%s', mfileName(9:end), tests{t}.name) ;
  results{t}.succeded = true ;
  results{t}.exception = [] ;
  try
    if exist('state', 'var')
      tests{t}.func(state) ;
    else
      tests{t}.func() ;
    end
  catch exception
    results{t}.succeded = false ;
    results{t}.exception = exception ;
  end
end

if ~isempty(teardownFunc), teardownFunc(state) ; end

results = cat(2, results{:}) ;


%--- help for inputParser/parse ---
%
% parse(PARSEOBJ,ARGLIST) parses user inputs based on the input scheme.
%    PARSE matches arguments in the comma separated list ARGLIST with
%    input scheme defined by PARSEOBJ.  The inputParser properties Results,
%    UsingDefaults, and Unmatched are set by calling the PARSE methods.  If
%    the parse fails for any reason, the PARSE method throws an error.
%
%    See also inputParser, inputParser/addOptional, inputParser/addRequired,
%    inputParser/addParameter, inputParser.Results, inputParser.KeepUnmatched, inputParser.UsingDefaults
%
%    Reference page in Doc Center
%       doc inputParser/parse
%
%


%Documentation
% Calls m2html to generate documentation of m code
%
% Author: Jonathan Karr, jkarr@stanford.edu
% Affiliation: Covert Lab, Department of Bioengineering, Stanford University
% Last updated: 6/8/2011
classdef Documentation
    methods (Static)
        function generate()
			import edu.stanford.covert.cell.sim.util.Documentation;

            [~, folder] = fileparts(pwd);
			try
				Documentation.cleanup(['doc' filesep 'm2html']);
			end
			if ~exist(['doc' filesep 'm2html'], 'dir')
				mkdir(['doc' filesep 'm2html']);
			end
            directories = [{folder}; cellfun(@(x) [folder filesep x], [
                edu.stanford.covert.util.IOUtil.getDirectoryNamesRecursively('src')], ...
                'UniformOutput', false)];
            cd('..');
            try
                m2html(...
                    'mFiles', directories, ...
                    'htmlDir', [folder filesep 'doc' filesep 'm2html'], ...
                    'recursive', 'off',...
                    'graph', 'on', ...
                    'todo', 'on', ...
                    'verbose', 'off');
				cd(folder);
            catch exception
				cd(folder);
				exception.rethrow();
			end
        end

		function cleanup(folder)
			import edu.stanford.covert.cell.sim.util.Documentation;

			files = dir(folder);
			for i = 1:numel(files)
				if isequal(files(i).name, '.') || isequal(files(i).name, '..') || isequal(files(i).name, '.svn')
					continue;
				end
				if isdir([folder filesep files(i).name])
					Documentation.cleanup([folder filesep files(i).name]);
				else
					delete([folder filesep files(i).name]);
				end
			end
		end
    end
end


function [nph,nfh] = sbprogress(varargin)
%SBPROGRESS Creates a progress bar in the "status-bar section" of the figure
%[nph,nfh] = sbprogress(varargin)
%   sbprogress creates or updates a progress bar that is created at the
%   status-bar section of a figure. It can either be created on an existing
%   figure or raised along with a newly created figure. At least 2
%   parameters are
%   required (or zero for demo).
%
%   Syntax:
%       sbprogres
%       sbprogress(ph,x)
%       sbprogress([],x)
%       sbprogress(ph,'Close')
%       sbprogress(ph,'Redraw')
%       sbprogress(ph,x,'PropertyName',PropertyValue,...)
%       sbprogress(ph,'PropertyName',PropertyValue,...)
%       sbprogress([],x,'PropertyName',PropertyValue,...)
%       sbprogress([],'PropertyName',PropertyValue,...)
%       [nph,nfh] = sbprogress(...)
%
%   Description:
%       sbprogress runs a demo
%       sbprogress([],x) creates a NEW figure and a NEW progress bar on it with progress being set to x
%       sbprogress(ph,x) updates the progress bar at handles ph with progress being set/changed to x; this also redraws the progress bar
%       sbprogress(ph,'Close') closes an existing progress bar and also a figure if figure was created together with a progress bar otherwise only the progress bar will be removed from the figure
%       sbprogress(ph,'Redraw') redraws an existing progress bar; e.g., when figure is resized
%       sbprogress(...'PropertyName',PropertyValue,...) sets/resets some properties of the progress bar and the newly cretaed figure
%       [nph,nfh] = sbprogress(...) returns handles to newly created progress bar and figure if figure is created along with the progress bar
%
%   Properties:
%       'Parent':   a figure handle on which the progress is to be created
%                   (if empty or not given a new figure will also be raised)
%       'Msg':      a string message that is displayed on the left of a progress bar
%       'Color':    a color of the progress bar and the percentage text (defaults to blue)
%       'Visible':  'on'/'off'; shows/hides the progress bar and its bevel; if a figure is also created then this affect the figure too
%       'Title':    a string title that is displayed in the figure when the
%                   progress bar is created in a new figure; defaults to an empty string
%       'Size':     height of the progress bar; 1..12 (defaults to 1)
%       'Modal':    1 for newly created figure to be modal and 0 to be
%                   non-modal (default)
%       'DisplayMode': 1 (default) percentage and the remaining time are added
%                   to the title string (only when a new figure is raised);
%                   0 - no time info is displayed; 2 - the remaining time is
%                   added to the progress bar (shown only when x > 0);
%                   creating the sbprogress and/or setting the progress (x)
%                   to zero resets the timer
%
%   Notes:
%       X can be a value between -100..100; given x as a negative value
%       means that the percentage number will not be shown.
%       'Modal' and 'Title' are considered only in cases when a new figure is created alogn with the
%       progress bar.
%
%   EXAMPLES:
%   sbprogress
%           Runs a demo
%   sbprogress([],10,'Msg','Progress:','Title','Test progress')
%           Creates a new figure with a progress bar...
%   ph = sbprogress([],-10,'Msg','Progress:','Title','Test progress')
%           Creates a new figure with a progress bar where the percentage
%           number is not shown; a handle array to the progress-bar axis is also returned
%   sbprogress(ph,'Redraw')
%           Redraws the ph progress bar
%   sbprogress(ph,20)
%           Re-sets the progress-bar's progress
%   ph = sbprogress([],20,'Msg','Test','Parent',fh)
%           Creates a progress bar on an existing figure whose handle is fh
%           and returns its handle array for further manipulation
%           (updating, changing,...)
%   set(fh,'UserData',ph,'ResizeFcn','sbprogress(get(gcf,''UserData''),''redraw'')')
%           Sets figure's (the one with the ph handle) resize function to
%           resize progress bar automatically
%
%   See also: STSBAR, ASCIIPROGRESS
%
%   Primoz Cermelj, 08.12.2003
%   (c) Primoz Cermelj, primoz.cermelj@email.si
%
%   Version: 1.1.0
%   Last revision: 19.02.2005
%--------------------------------------------------------------------------

%----------------
% SBPROGRESS history
%----------------
%
% [v.1.1.0] 19.02.2005
% - NEW: DisplayMode option added to display the remaining time
% - FIX: A bug relating to the Size property fixed
%
% [v.1.0.1] 05.09.2004
% - FIX: Minor update for error-checking
%
% [v.1.0.0] 28.05.2004
% - NEW: First official release

global W border

W = 400;        % Width of a newly created figure
border = 3;

% ---------------------
% First parameter-check and demo run
% ---------------------
if nargin == 0
    % Run a demo
    fh = figure;
    uicontrol('Style','text','String','Try to resize the figure...','Position',[150,200,200,25]);
    [nph,nfh] = sbprogress([],48.5,'Msg','Test:','Title','SBPROGRESS demo','Parent',fh);
    set(fh,'UserData',nph,'ResizeFcn','sbprogress(get(gcf,''UserData''),''redraw'')');
    [nph2,nfh2] = sbprogress([],-0.001,'Msg','Test 2:','Title','SBPROGRESS demo 2','Modal',0,'DisplayMode',1,'Color','r','Size',10);
    for ii=1:10
        sbprogress(nph2,-100*ii/10);
        pause(0.2);
    end
    return
elseif nargin < 2
    error('At least progress length should be given or ''Close'' or ''Redraw'' string');
end

ph = varargin{1};
x = varargin{2};
if ~ishandle(ph)
    error('ph is not a handle');
end

% Default properties
Props.Parent = [];
Props.Msg = '';
Props.Color = 'b';
Props.Title = '';
Props.Visible = 'on';
Props.DisplayMode = 1;
Props.Modal = 0;
Props.Size = 23;     % Default height of a newly created figure; this is aslo related to a progress bar height
propChanged = 0;     % if any property is being changed
phExists = ~isempty(ph);
fhExists = 1;
if phExists
    Data = get(ph,'UserData');
    if ~isfield(Data,'Props')
        error('Props field was not found in progress''s user data. Something was either removed or improper progress-bar handle was given.');
    else
        %%%%%%%%%%%%%%
        Props = Data.Props; % read props from current props
        %%%%%%%%%%%%%%
    end
end

% ---------------------
% Either 'Redraw' or 'Close' is assumed given in the second parameter x
% ---------------------
if ischar(x) & (strcmpi(x,'close') | strcmpi(x,'redraw'))
    if strcmpi(x,'close')
        Data = get(ph,'UserData');
        if ~isempty(Data) && isfield(Data,'fhCreated') && isfield(Data,'fh')
            if Data.fhCreated
                delete(Data.fh);
            else
                delete(ph);
            end
        else
            error('Wrong ph handle given');
        end
    elseif strcmpi(x,'redraw')
        Data = get(ph,'UserData');
        if ~isempty(Data) && isfield(Data,'fhCreated') && isfield(Data,'fh')
            progress(ph,Data.x,Props,propChanged,Data.fh,Data.fhCreated,'update');
        else
            error('Wrong ph handle given');
        end
    else
        error('Use sbprogress(ph,''redraw'') or sbprogress(ph,''close'')');
    end
    return
end

% ---------------------
% x might be ommited, empty, numeric value or a property name
% Sets any default values and any given ones given under properties
% ---------------------
if ischar(x)    % x is assumed being ommited (property is given)
    start = 2;
else
    start = 3;
end
if ~isnumeric(x) | isempty(x)
    if phExists
        x = Data.x;
    else
        x = 0;
    end
end
if nargin > 2       % additional properties are being passed
    nProps = nargin - start + 1;
    propChanged = 1;
    if ~logical( 2*floor(nProps/2)==nProps ), error('Additional properties must be given in pairs'), end;
    for ii=start:2:start+nProps-2
        if strcmpi(varargin{ii},'parent')
            Props.Parent = varargin{ii+1};
        elseif strcmpi(varargin{ii},'msg')
            Props.Msg = varargin{ii+1};
        elseif strcmpi(varargin{ii},'color')
            Props.Color = varargin{ii+1};
        elseif strcmpi(varargin{ii},'title')
            Props.Title = varargin{ii+1};
        elseif strcmpi(varargin{ii},'visible')
            Props.Visible = varargin{ii+1};
        elseif strcmpi(varargin{ii},'modal')
            Props.Modal = logical(varargin{ii+1});
        elseif strcmpi(varargin{ii},'size')
            Props.Size = varargin{ii+1};
        elseif strcmpi(varargin{ii},'displaymode')
            Props.DisplayMode = varargin{ii+1};
        else
            error('Unknown property given');
        end
    end
    if (Props.Size < 1) | (Props.Size > 12)
        Props.Size = 23;
    else
        Props.Size = round(Props.Size) + 22;
    end
end

if isempty(Props.Parent) || ~ishandle(Props.Parent)
    fhExists = 0;
else
    if ~ishandle(ph)
        phExists = 0;
    end
end
if ~phExists    % new progress bar is to be created
    fhCreated = 0;
    if ~fhExists
       nfh = createnewfig(Props);
       fh = nfh;
       Props.Parent = fh;
       fhCreated = 1;
    else
       fh = Props.Parent;
    end
    nph = progress([],x,Props,1,fh,fhCreated,'new');
    ph = nph;
else
    progress(ph,x,Props,propChanged,Data.fh,Data.fhCreated,'update');
end

if nargout > 0
    nph = ph;
    if nargout > 1
        nfh = fh;
    end
end
%-------------------------------------

%-------------------------------------
function fh = createnewfig(Props)
global W
H = Props.Size;
if isempty(Props.Title); Props.Title = ''; end;
set(0,'Units','Pixels');
scr = get(0,'ScreenSize');
fh = figure('Visible','off');
set(fh,'Units','Pixels',...
       'Tag','progressBarFigure',...
       'Position',[scr(3)/2-W/2 scr(4)/2-H/2 W H],...
       'MenuBar','none',...
       'Resize','off',...
       'NumberTitle','off',...
       'Name',Props.Title);
if Props.Modal
    set(fh,'WindowStyle','modal');
end
if strcmpi(Props.Visible,'on')
    set(fh,'Visible','On');
end
%-------------------------------------

%-------------------------------------
function [ph,hMsg] = progress(ph,x,Props,propChanged,fh,fhCreated,state)
% Creates a new progress or updates an existing one
global border

H = Props.Size;
[fPos,pPos] = getcoords(fh,H);
w = pPos(3);
if x < -100; x = 0; end;
if x > 100; x = 100; end;
if propChanged
    if isempty(Props.Msg); Props.Msg = ''; end;
    if isempty(Props.Title); Props.Title = ''; end;
    if isempty(Props.Msg)
        Data.xMsgPos = 0;
    else
        Data.xMsgPos = 2*border;
    end
end
timeStr = '';
if nargin < 5 || strcmpi(state,'new')
    Data.startTime = clock;
    if Props.DisplayMode ~= 0
        timeStr = '?? remaining';
    end
    ph = axes;
    set(ph,'Tag','progressBarAxes','Units','Pixels','Position',pPos,'Box','off','Visible','off');
    Data.hMsg = text(Data.xMsgPos,0.55*H,Props.Msg,'Units','Pixels','Tag','progressBarMsg','Visible','off');
else            % update
    Data = get(ph,'UserData');
    if x == 0
        Data.startTime = clock;
    end
    if Props.DisplayMode ~= 0
        remTime = (100/abs(x+0.00000001)-1)*etime(clock,Data.startTime);
        timeStr = sec2timestr(abs(remTime));
    end
    fh = Data.fh;
    set(ph,'Position',pPos);
    set(Data.hMsg,'String',Props.Msg,'Position',[Data.xMsgPos 0.55*H]);
end
%-----
set(ph,'XLim',[0 w],'YLim',[0 H]);
%-----
tPos = get(Data.hMsg,'Extent');
if (tPos(3)+tPos(1)) > 0.5*w;  pStart = 0.5*w; else;  pStart = (tPos(3)+tPos(1)+2*border); end;
pEnd = pStart + abs(x)/100*abs(w-border-pStart);
%-----
if nargin < 5 || strcmpi(state,'new')
    Data.hRec = rectangle('Position',[pStart border w-border-pStart-1 H-2*border-1],'Tag','progressBarRec','Visible','off');
    Data.hPatch = patch([pStart; pEnd; pEnd; pStart],[border; border; H-border-1; H-border-1],Props.Color,'Tag','progressBarPatch','Visible','off');
    if Props.DisplayMode == 2
        addStr = ['   ' timeStr];
    else
        addStr = '';
    end
    Data.hPercTxt = text( (pStart+w-border-1)/2,0.55*H,[num2str(abs(x),'%2.2f') '%' addStr],'Color',Props.Color,'Units','Pixels','FontWeight','bold','Tag','progressBarPercTxt','Visible','Off','EraseMode','xor','HorizontalAlignment','Center');
    Data.hFrame = panel(fh,ph,'new');
else
    set(Data.hRec,'Position',[pStart border w-border-pStart-1 H-2*border-1]);
    set(Data.hPatch,'XData',[pStart; pEnd; pEnd; pStart],'YData',[border; border; H-border-1; H-border-1],'FaceColor',Props.Color);
    if Props.DisplayMode == 2
        addStr = ['   ' timeStr];
    else
        addStr = '';
    end
    set(Data.hPercTxt,'Position',[(pStart+w-border-1)/2 0.55*H],'String',[num2str(abs(x),'%2.2f') '%' addStr],'Color',Props.Color);
    Data.hFrame = panel(fh,ph,'update');
end
%-----
if fhCreated
    fPos = get(fh,'Position');
    fPos(4) = H;
    if Props.DisplayMode == 1
        addStr = ['[' num2str(abs(x),'%2.2f') '%  ' timeStr ']'];
    else
        addStr = '';
    end
    set(fh,'Name',[Props.Title '  ' addStr],'Position',fPos);
    if propChanged
        if Props.Modal
            set(fh,'WindowStyle','modal');
        else
            set(fh,'WindowStyle','normal');
        end
        if strcmpi(Props.Visible,'on')
            set(fh,'Visible','on');
        else
            set(fh,'Visible','off');
        end
    end
end
%-----
if x >= 0 & strcmpi(Props.Visible,'on')
    set(Data.hPercTxt,'Visible','On');
else
    set(Data.hPercTxt,'Visible','Off');
end
if propChanged
    if strcmpi(Props.Visible,'on')
        set(Data.hRec,'Visible','On');
        set(Data.hMsg,'Visible','On');
        set(Data.hPatch,'Visible','On');
        set(Data.hFrame,'Visible','On');
    else
        set(Data.hRec,'Visible','Off');
        set(Data.hMsg,'Visible','Off');
        set(Data.hPatch,'Visible','Off');
        set(Data.hFrame,'Visible','Off');
    end
end
Data.Props = Props;
Data.pStart = pStart;
Data.fh = fh;
Data.fhCreated = fhCreated;
Data.x = x;
Data.msg = Props.Msg;
set(ph,'UserData',Data);
drawnow;
%-------------------------------------

%-------------------------------------
function frame = panel(fh,ph,state);
% Creates a virtual panel surrounding the progress bar.
% fh is the figure's handdle, ph is the progress' handle (axes).
% It returns a handle array designating the frame.
% See also the self-contained function BEVEL.
pos = get(ph,'Position');
x = pos(1);
y = pos(2);
w = pos(3);
h = pos(4);
col = rgb2hsv(get(fh,'Color'));
downColor = col;   downColor(2) = 0.5*downColor(2);  downColor(3) = 0.9; downColor = hsv2rgb(downColor);
upColor = col;    upColor(3) = 0.4;  upColor = hsv2rgb(upColor);
frame = zeros(4,1);
if nargin < 3 || strcmpi(state,'new')
    frame(1) = line([1 w],[h-1 h-1],[0 0],'Color',upColor,'Visible','off');
    frame(2) = line([1 1],[1 h-1],'Color',upColor,'Visible','off');
    frame(3) = line([2 w-1],[1 1],'Color',downColor,'Visible','off');
    frame(4) = line([w-1 w-1],[1 h-1],'Color',downColor,'Visible','off');
else
    Data = get(ph,'UserData');
    frame = Data.hFrame;
    set(frame(1),'XData',[1 w],'YData',[h-1 h-1]);
    set(frame(2),'XData',[1 1],'YData',[1 h-1]);
    set(frame(3),'XData',[2 w-1],'YData',[1 1]);
    set(frame(4),'XData',[w-1 w-1],'YData',[1 h-1]);
end
%-------------------------------------

%-------------------------------------
function [fPos,pPos] = getcoords(fh,H)
% Returns coordinates for axis, frame, and msg for our sbprogress (for
% creation or updating purposes). fPos is figure's position, pPos is
% progress-bar's position, framPos is frame's position
%
% Progress-bar axis
fUnits = get(fh,'Units');
set(fh,'Units','Pixels');
fPos = get(fh,'Position');
set(fh,'Units',fUnits);
pPos = fPos;
pPos(1) = 1;
pPos(2) = 2;
pPos(3) = pPos(3)-2;
pPos(4) = H-1;
%-------------------------------------

%-------------------------------------
function timeStr = sec2timestr(sec)
% Convert a time measurement from seconds into a human readable string.
dd = floor(sec/86400);
hh = floor((sec-dd*86400)/3600);
mm = floor((sec-dd*86400-hh*3600)/60);
ss = ceil(sec-dd*86400-hh*3600-mm*60);
timeStr = '';
if dd
    timeStr = sprintf('%d days, %d hr remaining',dd,hh);
elseif hh
    timeStr = sprintf('%d hr, %d min remaining',hh,mm);
elseif mm
    timeStr = sprintf('%d min, %d sec remaining',mm,ss);
else
    if sec < 0.01
        timeStr = 'completed';
    else
        timeStr = sprintf('%d seconds remaining',ss);
    end
end
%-------------------------------------


%{
    Copyright (c) 2014, Philipp Krähenbühl
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
        * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
        * Neither the name of the Stanford University nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

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


%% A10 WARTHOG FIXED WING AIRCRAFT (A10.m) ///////////////////////////////

% Author: James A. Douthwaite

classdef A10 < fixedWing
    properties
        % Any specific properties of globalhawk
    end
    %  CLASS METHODS
    methods
        % CONSTRUCTOR METHOD
        function obj = A10(varargin)
            % CALL THE SUPERCLASS CONSTRUCTOR
            obj@fixedWing(varargin);  % Create the super class 'fixedWing'

            % //////////////// Check for user overrides ///////////////////
            [obj] = obj.ApplyUserOverrides(varargin); % Recursive overrides
            % /////////////////////////////////////////////////////////////
        end
    end
end


% under construction...

function com = makecommand4history(p, skipfields, type, funcname)
%skipfields = {'ALLEEG', 'Saveas'};
fn     = fieldnames(p.Results);
if length(setindex)==1 && setindex(1)==1
      inputvari = 'EEG'; % Thanks to Felix Bacigalupo for this suggestion. Dic 12, 2011
else
      inputvari = inputname(1);
end
erpcom = sprintf( 'ERP = pop_averager( %s ', inputvari);
for q=1:length(fn)
      fn2com = fn{q};
      if ~ismember_bc2(fn2com, skipfields)
            fn2res = p.Results.(fn2com);
            if ~isempty(fn2res)
                  if ischar(fn2res)
                        if ~strcmpi(fn2res,'off')
                              erpcom = sprintf( '%s, ''%s'', ''%s''', erpcom, fn2com, fn2res);
                        end
                  else
                        if iscell(fn2res)
                              fn2resstr = vect2colon(cell2mat(fn2res), 'Sort','on');
                              fnformat = '{%s}';
                        else
                              fn2resstr = vect2colon(fn2res, 'Sort','on');
                              fnformat = '%s';
                        end
                        erpcom = sprintf( ['%s, ''%s'', ' fnformat], erpcom, fn2com, fn2resstr);
                  end
            end
      end
end
erpcom = sprintf( '%s );', erpcom);


function hlpText = hlp_getFcnPreambleText(functionName)
% Return the 'preamble' text for a given function name.
% This is the initial part of the help text, and is terminated by a
% horizontal dashed line at least 5 characters long. The preamble text
% cannot contain any uncommented line breaks as these will be interpreted
% as indicating the end of the block of help text.
%
% Trailing whitespace is removed from the preamble.
%
% Author: Tim Mullen June 2012, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

% This function is part of the Source Information Flow Toolbox (SIFT)
%
% 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, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% make sure function name is valid
try
    utl_whichfile(functionName);
catch
    error('SIFT:hlp_getFcnPreambleText:badFcnName','Unable to find function %s.m',functionName);
end

% Next, read in the help text
if isdeployed
    hlpText = hlp_readHelpInDeployedMode(functionName);
else
    hlpText = help(functionName);
end

if isempty(hlpText)
    error('Error parsing %s.m: I could not find a block of help text for the function',functionName);
end

% parse the help text. We only want the text preceeding the first
% sufficiently long horizontal dashed line
endpoint = strfind(hlpText,'-----');

if isempty(endpoint)
    disp(hlpText)
    % error('Error parsing %s.m: I could not find the horizontal dashed line separating the preamble from remaining help text',functionName);
    warning('Error parsing %s.m: I could not find the horizontal dashed line separating the preamble from remaining help text',functionName);
    hlpText = '';
end

% return the preamble
hlpText = deblank(hlpText(1:endpoint-1));


%VideoCamera_fg Class to read from local video camera
%
% A concrete subclass of ImageSource that acquires images from a local
% camera using a simple open-source frame grabber interface.
%
% This class is not intended to be used directly, instead use the factory
% method VideoCamera.which will return an instance of this class if the interface
% is supported on your platform (Mac or Linux), for example
%
%         vid = VideoCamera.amera();
%
% Methods::
% grab    Aquire and return the next image
% size    Size of image
% close   Close the image source
% char    Convert the object parameters to human readable string
%
% See also ImageSource, AxisWebCamera, Movie.

% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Machine Vision Toolbox for Matlab (MVTB).
%
% MVTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% MVTB 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with MVTB.  If not, see <http://www.gnu.org/licenses/>.

% mmread brings the whole movie into memory.  Not entirely sure what
% libavbin uses memory-wise, it takes a long time to "open" the file.

classdef VideoCamera_fg < ImageSource

    properties

        name;
    end

    properties(Constant=true)
        % set the operation codes for the camera driver
        CAMERA_OP_LIST = 1;
        CAMERA_OP_OPEN = 2;
        CAMERA_OP_CLOSE = 3;
        CAMERA_OP_START = 4;
        CAMERA_OP_STOP = 5;
        CAMERA_OP_ISRUNNING = 6;
        CAMERA_OP_GRAB = 7;
        CAMERA_OP_GET_PARAMS = 8;
        CAMERA_OP_SET_WIDTH_HEIGHT = 9;
        CAMERA_OP_GET_NAME = 10;
    end

    methods(Static)
        % class method to list the available video sources
        function list()
            framegrabber(VideoCamera_fg.CAMERA_OP_LIST);
        end
    end

    methods

        function m = VideoCamera_fg(varargin)
        %VideoCamera_fg.VideoCamera_fg Video camera constructor
        %
        % V = VideoCamera_fg.CAMERA, OPTIONS) is a VideoCamera_fg.object that acquires
        % images from the local video camera specified by the string CAMERA.
        %
        % If CAMERA is '?' a list of available cameras, and their
        % characteristics is displayed.
        %
        % Options::
        % 'uint8'          Return image with uint8 pixels (default)
        % 'float'          Return image with float pixels
        % 'double'         Return image with double precision pixels
        % 'grey'           Return greyscale image
        % 'gamma',G        Apply gamma correction with gamma=G
        % 'scale',S        Subsample the image by S in both directions.
        % 'resolution',S   Obtain an image of size S=[W H].
        % 'id',I           ID of camera
        %
        % Notes:
        % - The specified 'resolution' must match one that the camera is capable of,
        %   otherwise the result is not predictable.

            % invoke the superclass constructor and process common arguments
            m = m@ImageSource(varargin{:});

            % open the video source

            if length(varargin) == 0
                camera = -1;        % choose default
            else
                camera = varargin{1};
            end
            framegrabber(VideoCamera_fg.CAMERA_OP_OPEN, camera);

            for i=1:10
                k = framegrabber(VideoCamera_fg.CAMERA_OP_ISRUNNING);

                if k > 0
                    break;
                end
                pause(0.5);
            end

            % get the parameters of the video source
            sz = framegrabber(VideoCamera_fg.CAMERA_OP_GET_PARAMS);
            m.width = sz(1);
            m.height = sz(2);
            m.name = framegrabber(VideoCamera_fg.CAMERA_OP_GET_NAME);
        end

        function paramSet(v, a1)
        end

        % destructor
        function delete(m)
            framegrabber(VideoCamera_fg.CAMERA_OP_CLOSE);
        end

        function close(m)
        %VideoCamera_fg.close Close the image source
        %
        % V.close() closes the connection to the camera.
            framegrabber(VideoCamera_fg.CAMERA_OP_STOP);
            pause(2);
            framegrabber(VideoCamera_fg.CAMERA_OP_CLOSE);
        end

        function out = grab(m, opt)
        %VideoCamera_fg.grab Acquire image from the camera
        %
        % IM = V.grab() acquires an image from the camera.
        %
        % Notes::
        % - the function will block until the next frame is acquired.

            im = framegrabber(VideoCamera_fg.CAMERA_OP_GRAB);

            % apply options specified at construction time
            im = m.convert(im);
            m.width = numcols(im);
            m.height = numrows(im);

            if nargout > 0
                out = im;
            else
                idisp(im);
            end
        end

        function s = char(m)
        %VideoCamera_fg.char Convert to string
        %
        % V.char() is a string representing the state of the camera object in
        % human readable form.
            s = '';

            s = strvcat(s, sprintf('VideoCamera. %s %d x %d', m.name, m.width, m.height));

            % show constructor time options
            s2 = char@ImageSource(m);
            if ~isempty(s2)
                s = strvcat(s, strcat(' - ', s2));
            end
        end

    end
end


suite = matlab.unittest.TestSuite.fromFolder(pwd);
suite.run;


function varargout = sendemailGUI(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @sendemailGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @sendemailGUI_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

%---------------------------------------------------------------------------------------------------
function sendemailGUI_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = [];

try
        def = varargin{1};
catch
        def = {'','You got an ERPmail!', 1};
end

memail = def{1}';
nm = length(memail);
memmailto = '';
for k=1:nm
        memmailto = sprintf('%s %s', memmailto, memail{k});
end
memmailto  = strtrim(memmailto);
memmailto  = strrep(memmailto, ' ', ', ');
memsubject = def{2};
memerpset  = def{3};
set(handles.edit_to, 'String', memmailto)
set(handles.edit_subject, 'String', memsubject)
set(handles.edit_erpsets, 'String', num2str(memerpset))

%
% Name & version
%
version = geterplabversion;
set(handles.gui_chassis,'Name', ['ERPLAB ' version '   -   Send Email GUI'])
fromemail = getpref('Internet','SMTP_Username');
if isempty(fromemail)
      fromemail = 'email not found';
end
set(handles.text_myemail, 'String', fromemail)

%
% Color GUI
%
handles = painterplab(handles);

%
% Set font size
%
handles = setfonterplab(handles);

% Update handles structure
guidata(hObject, handles);

% help
% helpbutton

% UIWAIT makes sendemailGUI wait for user response (see UIRESUME)
uiwait(handles.gui_chassis);

%---------------------------------------------------------------------------------------------------
function varargout = sendemailGUI_OutputFcn(hObject, eventdata, handles)
% Get default command line output from handles structure
varargout{1} = handles.output;

% The figure can be deleted now
delete(handles.gui_chassis);
pause(0.1)

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

%---------------------------------------------------------------------------------------------------
function edit_to_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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

%---------------------------------------------------------------------------------------------------
function edit_subject_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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

%---------------------------------------------------------------------------------------------------
function edit_erpsets_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%---------------------------------------------------------------------------------------------------
function pushbutton_cancel_Callback(hObject, eventdata, handles)
handles.output = [];
% Update handles structure
guidata(hObject, handles);
uiresume(handles.gui_chassis);
%---------------------------------------------------------------------------------------------------
function pushbutton_send_Callback(hObject, eventdata, handles)

mailto  = get(handles.edit_to, 'String');
mailto  = regexp(mailto, ',|\s+', 'split');
mailto(cellfun(@isempty,mailto)) = [];
subject = get(handles.edit_subject, 'String');
msg     = cellstr(char(get(handles.edit_editor, 'String')));
attach  = str2num(get(handles.edit_erpsets, 'String'));

handles.output = {mailto, subject, msg, attach};
%sendmail(mailto, subject, msg);
%pause(0.2)

% Update handles structure
guidata(hObject, handles);
uiresume(handles.gui_chassis);

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

%---------------------------------------------------------------------------------------------------
function edit_editor_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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

if isequal(get(handles.gui_chassis, 'waitstatus'), 'waiting')
      % The GUI is still in UIWAIT, us UIRESUME
      uiresume(handles.gui_chassis);
else
      % The GUI is no longer waiting, just close it
      delete(handles.gui_chassis);
end


function varargout = pdftops(cmd)
%PDFTOPS  Calls a local pdftops executable with the input command
%
% Example:
%   [status result] = pdftops(cmd)
%
% Attempts to locate a pdftops executable, finally asking the user to
% specify the directory pdftops was installed into. The resulting path is
% stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have pdftops (from the Xpdf package)
% installed on your system. You can download this from:
% http://www.foolabs.com/xpdf
%
% IN:
%   cmd - Command string to be passed into pdftops.
%
% OUT:
%   status - 0 iff command ran without problem.
%   result - Output from pdftops.

% Copyright: Oliver Woodford, 2009-2010

% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
% Mac OS.
% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path
% under linux.

% Call pdftops
[varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
return

function path = xpdf_path
% Return a valid path
% Start with the currently set path
path = user_string('pdftops');
% Check the path works
if check_xpdf_path(path)
    return
end
% Check whether the binary is on the path
if ispc
    bin = 'pdftops.exe';
else
    bin = 'pdftops';
end
if check_store_xpdf_path(bin)
    path = bin;
    return
end
% Search the obvious places
if ispc
    path = 'C:\Program Files\xpdf\pdftops.exe';
else
    path = '/usr/local/bin/pdftops';
end
if check_store_xpdf_path(path)
    return
end
% Ask the user to enter the path
while 1
    if strncmp(computer,'MAC',3) % Is a Mac
        % Give separate warning as the uigetdir dialogue box doesn't have a
        % title
        uiwait(warndlg('Pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/.'))
    end
    base = uigetdir('/', 'Pdftops not found. Please locate the program.');
    if isequal(base, 0)
        % User hit cancel or closed window
        break;
    end
    base = [base filesep];
    bin_dir = {'', ['bin' filesep], ['lib' filesep]};
    for a = 1:numel(bin_dir)
        path = [base bin_dir{a} bin];
        if exist(path, 'file') == 2
            break;
        end
    end
    if check_store_xpdf_path(path)
        return
    end
end
error('pdftops executable not found.');

function good = check_store_xpdf_path(path)
% Check the path is valid
good = check_xpdf_path(path);
if ~good
    return
end
% Update the current default path to the path found
if ~user_string('pdftops', path)
    warning('Path to pdftops executable could not be saved. Enter it manually in pdftops.txt.');
    return
end
return

function good = check_xpdf_path(path)
% Check the path is valid
[good message] = system(sprintf('"%s" -h', path));
% system returns good = 1 even when the command runs
% Look for something distinct in the help text
good = ~isempty(strfind(message, 'PostScript'));
return


function [] = generateSubsystemLayouts( minerva, cobra_model, color )
% Generates subsystem layouts
%
% USAGE:
%
%    generateSubsystemLayouts( minerva, cobra_model, color )
%
% INPUTS:
%    minerva:           Struct with the information of minerva instance:
%                       address, login, password and model (map)
%    cobra_model:       COBRA model structure
%    color:             Color

    subsystems = getModelSubSystems(cobra_model);

    for i= 1:length(subsystems)

        if nargin < 3
            response = generateSubsytemsLayout(cobra_model, subsystems(i));
        else
            response = generateSubsytemsLayout(cobra_model, subsystems(i), color);
        end

        if ~isempty(regexp(response, strcat('"creator":"', minerva.login, '"')))
            result = [subsystems(i), ' successfully sent to ReconMap.'];
            disp(result)
        else
            result = [subsystems(i), ' failed.'];
            disp(result)
        end

    end
end


function path = vl_root
% VL_ROOT  Obtain VLFeat root path
%   PATH = VL_ROOT() returns the path to the VLFeat installation.
%
%   See also: VL_SETUP(), VL_HELP().

% Authors: Andrea Vedaldi and Brian Fulkerson

% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

[a,b,c] = fileparts(mfilename('fullpath')) ;
[a,b,c] = fileparts(a) ;
path = a ;


function c = comment(d)

%tstoolbox/@description/comment
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt

narginchk(1,1);

c = cellstr(d.comment);


% SnirfSave( filenm, snirf )
%
% This function will save a snirf object to file 'filenm'.
% Recall that you create a snirf object with
%   snirf = SnirfClass();
% and then populate it with the required fields indicated by the SNIRF
% specification.

function SnirfSave( filenm, snirf )

snirf.Save( filenm )


function isargstruct(varargin)
%ISARGSTRUCT tests if the given arg is a struct and returns an error otherwise
%
%   Usage: isargstruct(arg1,arg2,...)
%
%   Input options:
%       args        - list of args
%
%   ISARGSTRUCT(args) tests if all given args are a struct and returns
%   an error otherwise.
%
%   see also: isargchar

%*****************************************************************************
% Copyright (c) 2010-2012 Quality & Usability Lab                            *
%                         Deutsche Telekom Laboratories, TU Berlin           *
%                         Ernst-Reuter-Platz 7, 10587 Berlin, Germany        *
%                                                                            *
% This file is part of the Sound Field Synthesis-Toolbox (SFS).              *
%                                                                            *
% The SFS is free software:  you can redistribute it and/or modify it  under *
% the terms of the  GNU  General  Public  License  as published by the  Free *
% Software Foundation, either version 3 of the License,  or (at your option) *
% any later version.                                                         *
%                                                                            *
% The SFS 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/>.            *
%                                                                            *
% The SFS is a toolbox for Matlab/Octave to  simulate and  investigate sound *
% field  synthesis  methods  like  wave  field  synthesis  or  higher  order *
% ambisonics.                                                                *
%                                                                            *
% http://dev.qu.tu-berlin.de/projects/sfs-toolbox       sfstoolbox@gmail.com *
%*****************************************************************************

% AUTHOR: Hagen Wierstorf
% $LastChangedDate: 2012-04-26 10:12:51 +0200 (Thu, 26 Apr 2012) $
% $LastChangedRevision: 710 $
% $LastChangedBy: wierstorf.hagen $

%% ===== Checking for struct =============================================
for ii = 1:nargin
    if ~isstruct(varargin{ii})
        error('%s need to be a struct.',inputname(ii));
    end
end


function srtlist = fuf (folders,reclev,opt)
%FUF recursively retrieves files under specified folder(s).
%
%   Syntax: srtlist = fuf (folders,reclev,opt)
%
%   INPUT ARGUMENTS
%       - folders       can be a character array or a cell array of strings. Valid strings
%                       are matlab path;
%       - reclev        {1} optional scalar/numeric array  of  booleans: 1 stands for recursive
%                       search, whilst 0 limit the search to the specified folder.
%                       reclev can be either a scalar, or a 1 X length(folders) array.
%                       Use the 2nd option to specify the search rule on a folder-basis.
%                       Default is 1, i.d., each folder is searched for recursively.
%       - opt           {'normal'} | 'detail'  is an optional field: when it's set to 'detail',
%                       FUF returns the full path of files searched for, while, when set to
%                       normal, it returns file names only.
%
%
%   OUTPUT ARGUMENT
%       - srtlist   is a sorted cell array of strings containing the name or the full path
%                       of files recursively found under the given folders.
%
%   FUF applies the wildcard * for searching files through all the directories beneath the given folder(s)
%   if the reclev parameter is set to 1. If you want to have different wildcards for folders belonging
%   to the same tree root, you need to pass them separately as input arguments.
%
%   REMARKS
%       - Folders don't have to belong to the same directory, therefore this function doesn't
%         have to be invoked from a particular directory.
%       - Matlab partial paths are not valid input arguments.
%       - Wildcard * can be used to narrow the search.
%       - To get the full path of a given file, FUF doesn't use the which command,
%         therefore it normally works also with java function that are not loaded.
%       - After completion, the working directory is set to the current directory at the time
%         of the function call.
%
%   EXAMPLES
%
%   To retrieve all files under the folder Utils:
%
%       >>  dir('C:\matlabR12\work\Interface\Utils')
%
%           .                       Contents.m
%           ..                      my_interface_evalmcw.m
%
%   To retrieve recursively the full path of all .m files starting with Cont under the folder work:
%
%       >> fuf('C:\matlabR12\work\Con*.m','detail')
%
%           'C:\matlabR12\work\Laboratorio_modellistica\DTT\Contents.m'
%           'C:\matlabR12\work\Laboratorio_modellistica\SDF\Contents.m'
%           'C:\matlabR12\work\PREPOSTGUIS\Contents.m'
%           'C:\matlabR12\work\PREPOSTGUIS\Utils\Contents.m'
%           'C:\matlabR12\work\Pavia\Contents.m'
%           'C:\matlabR12\work\TwoLe_front_end\Contents.m'
%           [1x74 char]
%           'C:\matlabR12\work\TwoLe_front_end\My_Classes\@Sector\Contents.m'
%           'C:\matlabR12\work\TwoLe_front_end\Utils\Contents.m'
%           'C:\matlabR12\work\Utils\Contents.m'
%
%   To retrieve recursively under the folder PREPOSTGUIS all .fig files and non recursively, under
%   the folder MatlabR12 all .txt files:
%
%       >> fuf({'C:\matlabR12\work\PREPOSTGUIS\*.fig','C:\matlabR12\*.txt'},[1,0],'detail')
%
%               'C:\matlabR12\license.txt'
%               'C:\matlabR12\work\PREPOSTGUIS\Private\MV_Manager.fig'
%               'C:\matlabR12\work\PREPOSTGUIS\R_h.fig'
%               'C:\matlabR12\work\PREPOSTGUIS\TSA.fig'
%               'C:\matlabR12\work\PREPOSTGUIS\Visual_3D.fig'

%                                         -$-$-$-
%
%        Author:    Francesco di Pierro                  Reasearch Assistant
%                                                    Center for Water Systems (CWS)
%                                                Dep. of Engineering and Computer Science
%                                                        University of Exeter
%                                                    e-mail: <F.Di-Pierro@ex.ac.uk>
%
%                                         -$-$-$-

%--------------------CHECK INPUT ARGUMENT TYPE AND SET DEFAULT VALUES------------------------%

%argument cheking and parsing default parameters

error(nargchk(1,3,nargin));
error(nargoutchk(0,1,nargout));
INITIAL_DIR = pwd;
if nargin==1
    if ischar(folders)
        folders = cellstr(folders);
    elseif ~iscellstr(folders)
        error('The 1st argument to the function fuf must be either a string or a cellstring!')
    end
    reclev = ones(size(folders));
    opt = 'normal';
elseif nargin==2
    if ischar(folders)
        folders = cellstr(folders);
    elseif ~iscellstr(folders)
        error('The 1st argument to the function fuf must be either a string or a cellstring!')
    end
    if isnumeric(reclev)
        if ~all(ismember(reclev,[0,1]))
            error('The 2nd argument to the function  must be a scalar/vector of booleans!')
        end
        if prod(size(reclev))==1
            reclev = reclev*ones(size(folders));
        elseif prod(size(reclev))~=prod(size(folders))
            error('The 2nd argument to the function must be a either a scalar or a 1 X length(1st argument) array!')
        end
        opt = 'normal';
    elseif ~ischar(reclev) | ~any(strcmp(reclev,{'normal','detail'}))
        error('Mismatched argument specification; the 3rd argument can be either set to ''normal'' or ''detail''');
    else
        opt = reclev;
        reclev = ones(size(folders));
    end
else
    if ischar(folders)
        folders = cellstr(folders);
    elseif ~iscellstr(folders)
        error('The 1st argument to the function fuf must be either a string or a cellstring!')
    end
    if isnumeric(reclev)
        if ~all(ismember(reclev,[0,1]))
            error('The 2nd argument to the function must be a scalar/vector of booleans!')
        end
        if prod(size(reclev))==1
            reclev = reclev*ones(size(folders));
        elseif prod(size(reclev))~=prod(size(folders))
            error('The 2nd argument to the function must be a either a scalar or a 1 X length(1st argument) array!')
        end
    else
        error('The 2nd argument to the function must be a scalar/vector of booleans!')
    end
    if ~ischar(opt) | ~any(strcmp(opt,{'normal','detail'}))
        error('Mismatched argument specification: Tte 3rd argument to the function must be either set to ''normal'' or ''detail''');
    end
end

%scan folders searching for incorrect folder names and partialpaths!!!
EXIT = 0;
for i=1:length(folders)
    [d,f,e] = fileparts(folders{i});
    if (~isdir(d) & ~isempty(e))
        warning(['"',d,'" is not a valid folder name!'])
        EXIT = 1;
    elseif (~isdir(fullfile(d,f,'')) & isempty(e))
        warning(['"',fullfile(d,f,''),'" is not a valid folder name!'])
        EXIT = 1;
    elseif (isempty(dir(d)) & ~isempty(e)) | (isempty(dir(fullfile(d,f,''))) & isempty(e))
        warning('Matlab PARTIALPATHS not allowed!')
        EXIT = 1;
    else                                                %this cheks the very unlike event arising
        sub = dir(pwd);                                 %when the partial path provided is a directory
        [subel{1:length(sub)}] = deal(sub.name);        %under the current one: this, in fact, is the
        [subtype{1:length(sub)}] = deal(sub.isdir);     %only situation where the dir command handles
        testel1 = strcmp(subel,fullfile(d,f,''));       %partialpaths!!!
        testel2 = strcmp(subel,d);
        if ~isempty(subtype(testel1)) | ~isempty(subtype(testel2))
            warning('Matlab PARTIALPATHS not allowed!')
            EXIT = 1;
        end
    end
end
if EXIT
    disp('')
    error(strvcat('One or more not valid folder names encountered! Function aborted!'))
end

%--------------------------------CORE FUNCTION--------------------------------%

sorted_list = [];                                           %initialize the output list

sorted_list = rec(sorted_list,folders,reclev,opt);          %call the function

sorted_list = sortrows(sorted_list);                        %sort the list

if nargout, srtlist = sorted_list; else disp (' '),disp(sorted_list), end

cd(INITIAL_DIR);                                            %and set current directory back to the initial one

%--------------------------------RECURSIVE FUNCTION--------------------------------%

function sorted_list = rec(sorted_list,folders,reclev,opt)

for i=1:length(folders)
    %first build the new search condition made of all files satistying the
    %search condition and all directories under the current one
    val = []; val1 = []; val2 = []; cnval1 = {}; cnval2 = {}; cdval = {}; cdva2 = {};   %initialize helper variables
    [pth,fname,ext] = fileparts(folders{i});
    cd(pth);                                            %move to the directory: isdir only recognizes directories on the Matlab search path or the current one!
    if isdir(fname)
        wild = '';
        cd(fname)
        pth = fullfile(pth,fname);
        val = dir;
    else
        %get the filenames satisfying the search condition
        val1 = dir(folders{i});
        wild = [fname,ext];
        if isempty(val1)
            cnval1 = [];    cdval1 = [];
        else
            [cnval1{1:length(val1)}] = deal(val1.name); [cdval1{1:length(val1)}] = deal(val1.isdir);
        end
        %and the directory/ies under the current one
        val2 = dir;
        wo = logical(zeros(size(val2)));
        for k=1:length(val2)
            if val2(k).isdir
                wo(k) = 1;
            end
        end
        val2(~wo) = [];
        %and build the new search structure
        [cnval2{1:length(val2)}] = deal(val2.name); [cdval2{1:length(val2)}] = deal(val2.isdir);
        cnval = [cnval1,cnval2];    cdval = [cdval1,cdval2];
        [val(1:length(cnval)).name] = deal(cnval{:}); [val(1:length(cdval)).isdir] = deal(cdval{:});
    end
    for j=1:length(val)
        if (val(j).isdir) & not(strcmp(val(j).name,'.')) & not(strcmp(val(j).name,'..'))    %if the jth object under the ith folder is a valid folder name(directory)...
            new_path = fullfile(pth,val(j).name);                                           %set the current directory to that one:
            cd(new_path);
            if reclev(i)                            %recursively call the function keeping in mind the search condition
                sorted_list = rec(sorted_list,{fullfile(new_path,wild)},reclev(i),opt);
            end
            cd ..                                   %get back to the previous directory
        elseif not(strcmp(val(j).name,'.')) & not(strcmp(val(j).name,'..')) %if the jth object under the ith folder is a valid file name
            if strcmp(opt,'detail')
                sorted_list =[sorted_list; cellstr(fullfile(pwd,val(j).name))];
            else
                sorted_list =[sorted_list; cellstr(val(j).name)];
            end
        end
    end
end


function list = qMRlistModel
if nargout, list = list_models; end
for im = list_models'
    header=qMRinfo(im{:}); % not compatible with octave
    if moxunit_util_platform_is_octave, return; end
    % get the first line
    ind = strfind(header,sprintf('\n'));
    header = header(1:ind-1);
    % remove space
    header = header(find(~isspace(header),1,'first'):end);
    % add tab after colons
    indcolons = strfind(header,':');
    header = ['<strong>' header(1:indcolons) '</strong>' repmat(' ',[1 max(1,30 - indcolons)]) header((indcolons+find(~isspace(header(indcolons+1:end)),1,'first')):end)];
    disp(header)
end


function [v, xml] = loadXML(filename)
%
% Reads a XML file and produces a struct array.
%
% filename = name of the XML file
% v = struct variable containing fields of type char or numeric
%
% filename can also be an URL containing XML

% Read file
if ~strcmp(filename(1:5), 'http:');
    [fid, message] = fopen(filename,'r');
    if fid == -1; error(message); end
    xml = fread(fid, 'uint8=>char');
    fclose(fid);
else
    filename = strrep(filename, '\', '/');
    xml = urlread(filename);
end

% Remove 'new line' characters from the chain
xml = char(xml(:)');
xml = strrep(xml, char(10), '');
xml = strrep(xml, char(13), '');

v = xml2struct(xml);


function cleanmacpollution(loc)
%CLEANMACPOLLUTION deletes the annoying search trace files generated by MAC.
%   CLEANMACPOLLUTION(WHERE) deletes the annoying search trace generated
%   by MAC OS for all subdirectorys under WHERE.
%
%   MAC OS has the bad habit of creating garbage finder data file in every
%   directory it touches. Usually this means your flashdrive will be
%   polluted by numerous unwanted files once you've plugged it into a mac.
%   On OS 9 these garbages are FINDER.DAT; on OS X they are .DS_Store;
%   Use this little tool to remove those unwanted files;

% Written by Siyi Deng; 12-19-2007;

if nargin < 1 || isempty(loc), loc = uigetdir; end
if ~loc, return; end
s = genpath(loc);
p = strfind(s,pathsep);
q = [[1,p(1:end-1)+1];p-1];
mc = {'FINDER.DAT','.DS_Store'}; % OS 9, OS X;
for v = 1:numel(mc)
    for k = 1:size(q,2)
        thePath = [s(q(1,k):q(2,k)),filesep];
        if exist([thePath,mc{v}],'file')
            disp(['Deleting ',thePath,mc{v},'...']);
            delete([thePath,mc{v}]);
        end
        if exist([thePath,'private'],'dir')
            if exist([thePath,'private',filesep,mc{v}],'file')
                disp(['Deleting ',thePath,'private',filesep,mc{v},'...']);
                delete([thePath,'private',filesep,mc{v}]);
            end
        end
    end
end

end % CLEANMACPOLLUTION;


function push_cIX_gIX(hfig,cIX,gIX,numK)
% push cIX, gIX to hfig
if ~exist('numK','var')
    numK=max(gIX);
end

var_script={hfig,cIX,gIX,numK};
GUI_FishExplorer('_place_holder_',0,0,0,1,'push_cIX_gIX',var_script);

end


function [conf, args] = vl_argparse(conf, args, varargin)
% VL_ARGPARSE  Parse list of parameter-value pairs
%   CONF = VL_ARGPARSE(CONF, ARGS) updates the structure CONF based on
%   the specified parameter-value pairs ARGS={PAR1, VAL1, ... PARN,
%   VALN}. The function produces an error if an unknown parameter name
%   is passed in.
%
%   [CONF, ARGS] = VL_ARGPARSE(CONF, ARGS) copies any parameter in
%   ARGS that does not match CONF back to ARGS instead of producing an
%   error.
%
%   Example::
%     The function can be used to parse a list of arguments
%     passed to a MATLAB functions:
%
%       function myFunction(x,y,z,varargin)
%       conf.parameterName = defaultValue ;
%       conf = vl_argparse(conf, varargin)
%
%     If only a subset of the options should be parsed, for example
%     because the other options are interpreted by a subroutine, then
%     use the form
%
%      [conf, varargin] = vl_argparse(conf, varargin)
%
%     that copies back to VARARGIN any unknown parameter.
%
%   See also: VL_OVERRIDE(), VL_HELP().

% Authors: Andrea Vedaldi

% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

if ~isstruct(conf), error('CONF must be a structure') ; end

if length(varargin) > 0, args = {args, varargin{:}} ; end

remainingArgs = {} ;
names = fieldnames(conf) ;

if mod(length(args),2) == 1
  error('Parameter-value pair expected (missing value?).') ;
end

for ai = 1:2:length(args)
  paramName = args{ai} ;
  if ~ischar(paramName)
    error('The name of the parameter number %d is not a string.', (ai-1)/2+1) ;
  end
  value = args{ai+1} ;
  if isfield(conf,paramName)
    conf.(paramName) = value ;
  else
    % try case-insensitive
    i = find(strcmpi(paramName, names)) ;
    if isempty(i)
      if nargout < 2
        error('Unknown parameter ''%s''.', paramName) ;
      else
        remainingArgs(end+1:end+2) = args(ai:ai+1) ;
      end
    else
      conf.(names{i}) = value ;
    end
  end
end

args = remainingArgs ;


classdef TestUtils
    %TestUtils

    methods (Static)
        function test_version
            info = cv.Utils.getBuildInformation();
            validateattributes(info, {'char'}, {'nonempty'});

            v = cv.Utils.version();
            validateattributes(v, {'char'}, {'row', 'nonempty'});
        end

        function test_cpu
            s = cv.Utils.checkHardwareSupport();
            validateattributes(s, {'struct'}, {'scalar'});

            name = cv.Utils.getHardwareFeatureName(int32(1));
            validateattributes(name, {'char'}, {'row', 'nonempty'});
        end

        function test_num_cpu
            n = cv.Utils.getNumberOfCPUs();
            validateattributes(n, {'numeric'}, {'scalar', 'integer', 'nonnegative'});
        end

        function test_num_threads
            n = cv.Utils.getNumThreads();
            validateattributes(n, {'numeric'}, {'scalar', 'integer'});
            cv.Utils.setNumThreads(n);
        end

        function test_optimization
            b = cv.Utils.useOptimized();
            validateattributes(b, {'logical'}, {'scalar'});
            cv.Utils.setUseOptimized(b);
        end

        function test_ipp
            str = cv.Utils.getIppVersion();
            validateattributes(str, {'char'}, {'row', 'nonempty'});

            if ~strcmpi(str, 'disabled')
                b = cv.Utils.useIPP();
                validateattributes(b, {'logical'}, {'scalar'});
                cv.Utils.setUseIPP(b);
            end
        end

        function test_ovx
            b = cv.Utils.haveOpenVX();
            validateattributes(b, {'logical'}, {'scalar'});

            if b
                b = cv.Utils.useOpenVX();
                validateattributes(b, {'logical'}, {'scalar'});
                cv.Utils.setUseOpenVX(b);
            end
        end

        function test_ocl_1
            b = cv.Utils.haveOpenCL();
            validateattributes(b, {'logical'}, {'scalar'});

            b = cv.Utils.haveAmdBlas();
            validateattributes(b, {'logical'}, {'scalar'});

            b = cv.Utils.haveAmdFft();
            validateattributes(b, {'logical'}, {'scalar'});

            b = cv.Utils.haveSVM();
            validateattributes(b, {'logical'}, {'scalar'});
        end

        function test_ocl_2
            if cv.Utils.haveOpenCL()
                b = cv.Utils.useOpenCL();
                validateattributes(b, {'logical'}, {'scalar'});
                cv.Utils.setUseOpenCL(b);
            end
        end

        function test_ocl_3
            if cv.Utils.haveOpenCL()
                p = cv.Utils.getPlatfomsInfo();
                validateattributes(p, {'struct'}, {'vector'});
            end
        end

        function test_cuda
            n = cv.Utils.getCudaEnabledDeviceCount();
            validateattributes(n, {'numeric'}, {'scalar', 'integer'});
            if n > 0
                id = cv.Utils.getDevice();
                validateattributes(id, {'numeric'}, {'scalar', 'integer'});
                cv.Utils.setDevice(id);

                s = cv.Utils.deviceSupports();
                validateattributes(s, {'struct'}, {'scalar'});

                cv.Utils.printShortCudaDeviceInfo(id);
                cv.Utils.printCudaDeviceInfo(id);

                s = cv.Utils.deviceInfo(id);
                validateattributes(s, {'struct'}, {'scalar'});

                cv.Utils.resetDevice();
            end
        end

        function test_tega
            % functions only defined for Tegra SoC
            if false
                b = cv.Utils.useTegra();
                validateattributes(b, {'logical'}, {'scalar'});
                cv.Utils.setUseTegra(b);
            end
        end
    end

end