Index: sm/trunk-jpl/externalpackages/export_fig/README
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/README	(revision 24459)
+++ 	(revision )
@@ -1,17 +1,0 @@
-Downloaded from https://www.mathworks.com/matlabcentral/fileexchange/23629-export-fig
-
-We had to patch export_fig.m to force export_fig to use the renderers painter, otherwise it is just way to slow (opengl is the default if we have patches)
-
-Line  585:
-
-
-if ~options.renderer
-    if hasTransparency || hasPatches
-        % This is *MUCH* slower, but more accurate for patches and transparent annotations (issue #39)
-        renderer = '-opengl';
-    else
-        renderer = '-painters';
-    end
-end
-
-change to painters all the time
Index: /issm/trunk-jpl/externalpackages/export_fig/README.md
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/README.md	(revision 24459)
+++ /issm/trunk-jpl/externalpackages/export_fig/README.md	(revision 24460)
@@ -10,4 +10,6 @@
 
 Perhaps the best way to demonstrate what export_fig can do is with some examples.
+
+*Note: `export_fig` currently supports only figures created with the `figure` function, or GUIDE. Figures created using `uifigure` or AppDesigner are only partially supported. See issues [#287](https://github.com/altmany/export_fig/issues/287), [#261](https://github.com/altmany/export_fig/issues/261) for details.*
   
 ### Examples
@@ -169,5 +171,5 @@
 ```
 
-**Specifying the figure/axes** - if you have mutiple figures open you can specify which figure to export using its handle:  
+**Specifying the figure/axes** - if you have multiple figures open you can specify which figure to export using its handle:  
 ```Matlab
 export_fig(figure_handle, filename);
@@ -212,7 +214,7 @@
 **Smoothed/interpolated images in output PDF** - if you produce a PDF using export_fig and images in the PDF look overly smoothed or interpolated, this is because the software you are using to view the PDF is smoothing or interpolating the image data. The image is not smoothed in the PDF file itself. If the software has an option to disable this feature, you should select it. Alternatively, use another PDF viewer that doesn't exhibit this problem.  
   
-**Locating Ghostscript/pdftops** - You may find a dialogue box appears when using export_fig, asking you to locate either [Ghostscript](http://www.ghostscript.com) or [pdftops](http://www.foolabs.com/xpdf). These are separate applications which export_fig requires to perform certain functions. If such a dialogue appears it is because export_fig can't find the application automatically. This is because you either haven't installed it, or it isn't in the normal place. Make sure you install the applications correctly first. They can be downloaded from the following places:  
+**Locating Ghostscript/pdftops** - You may find a dialogue box appears when using export_fig, asking you to locate either [Ghostscript](http://www.ghostscript.com) or [pdftops (part of the Xpdf package)](http://www.xpdfreader.com). These are separate applications which export_fig requires to perform certain functions. If such a dialogue appears it is because export_fig can't find the application automatically. This is because you either haven't installed it, or it isn't in the normal place. Make sure you install the applications correctly first. They can be downloaded from the following places:  
  1. Ghostscript:     [www.ghostscript.com](http://www.ghostscript.com)
- 2. pdftops (install the Xpdf package): [www.foolabs.com/xpdf](http://www.foolabs.com/xpdf)
+ 2. pdftops (install the Xpdf package): [www.xpdfreader.com](http://www.xpdfreader.com)
 
 If you choose to install them in a non-default location then point export_fig
Index: /issm/trunk-jpl/externalpackages/export_fig/append_pdfs.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/append_pdfs.m	(revision 24459)
+++ /issm/trunk-jpl/externalpackages/export_fig/append_pdfs.m	(revision 24460)
@@ -35,47 +35,90 @@
 % 26/02/15: If temp dir is not writable, use the output folder for temp
 %           files when appending (Javier Paredes); sanity check of inputs
+% 24/01/18: Fixed error in case of existing output file (append mode)
+% 24/01/18: Fixed issue #213: non-ASCII characters in folder names on Windows
+% 06/12/18: Avoid an "invalid escape-char" warning upon error
 
 function append_pdfs(varargin)
 
-if nargin < 2,  return;  end  % sanity check
+    if nargin < 2,  return;  end  % sanity check
 
-% Are we appending or creating a new file
-append = exist(varargin{1}, 'file') == 2;
-output = [tempname '.pdf'];
-try
-    % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
-    fid = fopen(output,'w');
-    fwrite(fid,1);
-    fclose(fid);
-    delete(output);
-    isTempDirOk = true;
-catch
-    % Temp dir is not writable, so use the output folder
-    [dummy,fname,fext] = fileparts(output); %#ok<ASGLU>
-    fpath = fileparts(varargin{1});
-    output = fullfile(fpath,[fname fext]);
-    isTempDirOk = false;
+    % Are we appending or creating a new file
+    append = exist(varargin{1}, 'file') == 2;
+    output = [tempname '.pdf'];
+    try
+        % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
+        fid = fopen(output,'w');
+        fwrite(fid,1);
+        fclose(fid);
+        delete(output);
+        isTempDirOk = true;
+    catch
+        % Temp dir is not writable, so use the output folder
+        [dummy,fname,fext] = fileparts(output); %#ok<ASGLU>
+        fpath = fileparts(varargin{1});
+        output = fullfile(fpath,[fname fext]);
+        isTempDirOk = false;
+    end
+    if ~append
+        output = varargin{1};
+        varargin = varargin(2:end);
+    end
+
+    % Create the command file
+    if isTempDirOk
+        cmdfile = [tempname '.txt'];
+    else
+        cmdfile = fullfile(fpath,[fname '.txt']);
+    end
+    prepareCmdFile(cmdfile, output, varargin{:});
+
+    % Call ghostscript
+    [status, errMsg] = ghostscript(['@"' cmdfile '"']);
+
+    % Check for ghostscript execution errors
+    if status && ~isempty(strfind(errMsg,'undefinedfile')) && ispc %#ok<STREMP>
+        % Fix issue #213: non-ASCII characters in folder names on Windows
+        for fileIdx = 2 : numel(varargin)
+            [fpath,fname,fext] = fileparts(varargin{fileIdx});
+            varargin{fileIdx} = fullfile(normalizePath(fpath),[fname fext]);
+        end
+        % Rerun ghostscript with the normalized folder names
+        prepareCmdFile(cmdfile, output, varargin{:});
+        [status, errMsg] = ghostscript(['@"' cmdfile '"']);
+    end
+
+    % Delete the command file
+    delete(cmdfile);
+
+    % Check for ghostscript execution errors
+    if status
+        errMsg = strrep(errMsg,'\','\\');  % Avoid an "invalid escape-char" warning
+        error('YMA:export_fig:append_pdf',errMsg);
+    end
+
+    % Rename the file if needed
+    if append
+        movefile(output, varargin{1}, 'f');
+    end
 end
-if ~append
-    output = varargin{1};
-    varargin = varargin(2:end);
+
+% Prepare a text file with ghostscript directives
+function prepareCmdFile(cmdfile, output, varargin)
+    fh = fopen(cmdfile, 'w');
+    fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
+    fprintf(fh, ' "%s"', varargin{:});
+    fclose(fh);
 end
-% Create the command file
-if isTempDirOk
-    cmdfile = [tempname '.txt'];
-else
-    cmdfile = fullfile(fpath,[fname '.txt']);
+
+% Convert long/non-ASCII folder names into their short ASCII equivalents
+function pathStr = normalizePath(pathStr)
+    [fpath,fname,fext] = fileparts(pathStr);
+    if isempty(fpath) || strcmpi(fpath,pathStr), return, end
+    dirOutput = evalc(['system(''dir /X /AD "' pathStr '*"'')']);
+    shortName = strtrim(regexprep(dirOutput,{'.*> *',[fname fext '.*']},''));
+    if isempty(shortName)
+        shortName = [fname fext];
+    end
+    fpath = normalizePath(fpath);  %recursive until entire fpath is processed
+    pathStr = fullfile(fpath, shortName);
 end
-fh = fopen(cmdfile, 'w');
-fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
-fprintf(fh, ' "%s"', varargin{:});
-fclose(fh);
-% Call ghostscript
-ghostscript(['@"' cmdfile '"']);
-% Delete the command file
-delete(cmdfile);
-% Rename the file if needed
-if append
-    movefile(output, varargin{1});
-end
-end
Index: /issm/trunk-jpl/externalpackages/export_fig/copyfig.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/copyfig.m	(revision 24459)
+++ /issm/trunk-jpl/externalpackages/export_fig/copyfig.m	(revision 24460)
@@ -14,9 +14,10 @@
 %    fh_new - The handle of the created figure.
 
-% Copyright (C) Oliver Woodford 2012
+% Copyright (C) Oliver Woodford 2012, Yair Altman 2015
 
 % 26/02/15: If temp dir is not writable, use the dest folder for temp
 %           destination files (Javier Paredes)
 % 15/04/15: Suppress warnings during copyobj (Dun Kirk comment on FEX page 2013-10-02)
+% 09/09/18: Fix issue #252: Workaround for cases where copyobj() fails for any reason
 
     % Set the default
@@ -25,10 +26,17 @@
     end
     % Is there a legend?
-    if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'))
+    useCopyobj = isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'));
+    if useCopyobj
         % Safe to copy using copyobj
-        oldWarn = warning('off'); %#ok<WNOFF>  %Suppress warnings during copyobj (Dun Kirk comment on FEX page 2013-10-02)
-        fh = copyobj(fh, 0);
+        oldWarn = warning('off'); %Suppress warnings during copyobj (Dun Kirk comment on FEX page 2013-10-02)
+        try
+            fh = copyobj(fh, 0);
+        catch
+            % Fix issue #252: Workaround for cases where copyobj() fails for any reason
+            useCopyobj = false;  % if copyobj() croaks, use file save/load below
+        end
         warning(oldWarn);
-    else
+    end
+    if ~useCopyobj
         % copyobj will change the figure, so save and then load it instead
         tmp_nam = [tempname '.fig'];
Index: /issm/trunk-jpl/externalpackages/export_fig/eps2pdf.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/eps2pdf.m	(revision 24459)
+++ /issm/trunk-jpl/externalpackages/export_fig/eps2pdf.m	(revision 24460)
@@ -42,12 +42,9 @@
 % http://www.mathworks.com/matlabcentral/fileexchange/23629
 
-% Thank you to Fabio Viola for pointing out compression artifacts, leading
-% to the quality setting.
-% Thank you to Scott for pointing out the subsampling of very small images,
-% which was fixed for lossless compression settings.
-
-% 9/12/2011 Pass font path to ghostscript.
-% 26/02/15: If temp dir is not writable, use the dest folder for temp
-%           destination files (Javier Paredes)
+% Thank you Fabio Viola for pointing out compression artifacts, leading to the quality setting.
+% Thank you Scott for pointing out the subsampling of very small images, which was fixed for lossless compression settings.
+
+% 09/12/11: Pass font path to ghostscript
+% 26/02/15: If temp dir is not writable, use the dest folder for temp destination files (Javier Paredes)
 % 28/02/15: Enable users to specify optional ghostscript options (issue #36)
 % 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve
@@ -57,11 +54,16 @@
 % 22/02/16: Bug fix from latest release of this file (workaround for issue #41)
 % 20/03/17: Added informational message in case of GS croak (issue #186)
+% 16/01/18: Improved appending of multiple EPS files into single PDF (issue #233; thanks @shartjen)
+% 18/10/19: Workaround for GS 9.51+ .setpdfwrite removal problem (issue #285)
+% 18/10/19: Warn when ignoring GS fontpath or quality options; clarified error messages
 
     % Intialise the options string for ghostscript
     options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
+
     % Set crop option
     if nargin < 3 || crop
         options = [options ' -dEPSCrop'];
     end
+
     % Set the font path
     fp = font_path();
@@ -69,21 +71,27 @@
         options = [options ' -sFONTPATH="' fp '"'];
     end
+
     % Set the grayscale option
     if nargin > 4 && gray
         options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
     end
+
     % Set the bitmap quality
+    qualityOptions = '';
     if nargin > 5 && ~isempty(quality)
-        options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
+        qualityOptions = ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false';
         if quality > 100
-            options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
+            qualityOptions = [qualityOptions ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode'];
+            qualityOptions = [qualityOptions ' -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
         else
-            options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
+            qualityOptions = [qualityOptions ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
             v = 1 + (quality < 80);
             quality = 1 - quality / 100;
             s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
-            options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
-        end
-    end
+            qualityOptions = [qualityOptions ' -c ".setpdfwrite << /ColorImageDict ' s ' /GrayImageDict ' s ' >> setdistillerparams"'];
+        end
+        options = [options qualityOptions];
+    end
+
     % Enable users to specify optional ghostscript options (issue #36)
     if nargin > 6 && ~isempty(gs_options)
@@ -97,8 +105,10 @@
         options = [options gs_options];
     end
+
     % Check if the output file exists
     if nargin > 3 && append && exist(dest, 'file') == 2
         % File exists - append current figure to the end
-        tmp_nam = tempname;
+        tmp_nam = [tempname '.pdf'];
+        [fpath,fname,fext] = fileparts(tmp_nam);
         try
             % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
@@ -109,29 +119,37 @@
         catch
             % Temp dir is not writable, so use the dest folder
-            [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
             fpath = fileparts(dest);
             tmp_nam = fullfile(fpath,[fname fext]);
         end
-        % Copy the file
+        % Copy the existing (dest) pdf file to temporary folder
         copyfile(dest, tmp_nam);
-        % Add the output file names
-        options = [options ' -f "' tmp_nam '" "' source '"'];
+        % Produce an interim pdf of the source eps, rather than adding the eps directly (issue #233)
+        ghostscript([options ' -f "' source '"']);
+        [~,fname] = fileparts(tempname);
+        tmp_nam2 = fullfile(fpath,[fname fext]); % ensure using a writable folder (not necessarily tempdir)
+        copyfile(dest, tmp_nam2);
+        % Add the existing pdf and interim pdf as inputs to ghostscript
+        %options = [options ' -f "' tmp_nam '" "' source '"'];  % append the source eps to dest pdf
+        options = [options ' -f "' tmp_nam '" "' tmp_nam2 '"']; % append the interim pdf to dest pdf
         try
             % Convert to pdf using ghostscript
             [status, message] = ghostscript(options);
         catch me
-            % Delete the intermediate file
+            % Delete the intermediate files and rethrow the error
             delete(tmp_nam);
+            delete(tmp_nam2);
             rethrow(me);
         end
-        % Delete the intermediate file
+        % Delete the intermediate (temporary) files
         delete(tmp_nam);
+        delete(tmp_nam2);
     else
         % File doesn't exist or should be over-written
-        % Add the output file names
+        % Add the source eps file as input to ghostscript
         options = [options ' -f "' source '"'];
         % Convert to pdf using ghostscript
         [status, message] = ghostscript(options);
     end
+
     % Check for error
     if status
@@ -142,10 +160,24 @@
             options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
             status = ghostscript(options);
-            if ~status, return; end  % hurray! (no error)
-        end
+            if ~status % hurray! (no error)
+                warning('export_fig:GS:fontpath','Export_fig font option is ignored - not supported by your Ghostscript version')
+                return
+            end
+        end
+
+        % Retry without quality options (may solve problems with GS 9.51+, issue #285)
+        if ~isempty(qualityOptions)
+            options = strrep(orig_options, qualityOptions, '');
+            [status, message] = ghostscript(options);
+            if ~status % hurray! (no error)
+                warning('export_fig:GS:quality','Export_fig quality option is ignored - not supported by your Ghostscript version')
+                return
+            end
+        end
+
         % Report error
         if isempty(message)
-            error('Unable to generate pdf. Check destination directory is writable.');
-        elseif ~isempty(strfind(message,'/typecheck in /findfont'))
+            error('Unable to generate pdf. Ensure that the destination folder is writable.');
+        elseif ~isempty(strfind(message,'/typecheck in /findfont')) %#ok<STREMP>
             % Suggest a workaround for issue #41 (missing font path)
             font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
@@ -158,5 +190,5 @@
             fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest);
             if ~isempty(gs_options)
-                fprintf(2, '  or maybe the%s option(s) are not accepted by your GS version\n', gs_options);
+                fprintf(2, '  or maybe your Ghostscript version does not accept the extra "%s" option(s) that you requested\n', gs_options);
             end
             fprintf(2, '  or maybe you have another gs executable in your system''s path\n');
Index: /issm/trunk-jpl/externalpackages/export_fig/export_fig.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/export_fig.m	(revision 24459)
+++ /issm/trunk-jpl/externalpackages/export_fig/export_fig.m	(revision 24460)
@@ -1,3 +1,3 @@
-function [imageData, alpha] = export_fig(varargin)
+function [imageData, alpha] = export_fig(varargin) %#ok<*STRCL1>
 %EXPORT_FIG  Exports figures in a publication-quality format
 %
@@ -25,5 +25,9 @@
 %   export_fig ... -update
 %   export_fig ... -nofontswap
+%   export_fig ... -font_space <char>
 %   export_fig ... -linecaps
+%   export_fig ... -noinvert
+%   export_fig ... -preserve_size
+%   export_fig ... -options <optionsStruct>
 %   export_fig(..., handle)
 %
@@ -38,11 +42,11 @@
 %   - Render images at native resolution (optional for bitmap formats)
 %   - Transparent background supported (pdf, eps, png, tif)
-%   - Semi-transparent patch objects supported (png & tif only)
-%   - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff)
+%   - Semi-transparent patch objects supported (png, tif)
+%   - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tif)
 %   - 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
-%   - Rounded line-caps (optional; pdf & eps only)
+%   - Optional rounded line-caps (pdf, eps)
+%   - Optionally append to file (pdf, tif)
+%   - Vector formats: pdf, eps, svg
+%   - Bitmap formats: png, tif, jpg, bmp, export to workspace
 %
 % This function is especially suited to exporting figures for use in
@@ -58,13 +62,13 @@
 % background; only TIF & PNG formats support transparency of patch objects.
 %
-% The choice of renderer (opengl, zbuffer or painters) has a large impact
-% on the quality of output. The default value (opengl for bitmaps, painters
-% for vector formats) generally gives good results, but 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.
+% The choice of renderer (opengl/zbuffer/painters) has a large impact on the
+% output quality. The default value (opengl for bitmaps, painters for vector
+% formats) generally gives good results, but if you aren't satisfied
+% then try another renderer.  Notes:
+%   1) For vector formats (EPS,PDF), only painters generates vector graphics
+%   2) For bitmap formats, only opengl correctly renders transparent patches
+%   3) For bitmap formats, only painters correctly scales 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
@@ -72,29 +76,32 @@
 % 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
+% When exporting to EPS it additionally requires pdftops, from the Xpdf
+% suite of functions. You can download this from: http://xpdfreader.com
+%
+% SVG output uses the fig2svg (https://github.com/kupiqu/fig2svg) or plot2svg
+% (https://github.com/jschwizer99/plot2svg) utilities, or Matlab's built-in
+% SVG export if neither of these utilities are available on Matlab's path.
+% Note: cropping/padding are not supported in export_fig's SVG output.
 %
 % Inputs:
 %   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.
+%             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.
+%   -<format> - string(s) containing the output file extension(s). Options:
+%             '-pdf', '-eps', '-svg', '-png', '-tif', '-jpg' and '-bmp'.
+%             Multiple formats can be specified, without restriction.
+%             For example: export_fig('-jpg', '-pdf', '-png', ...)
+%             Either '-tif','-tiff' can be specified, and either '-jpg','-jpeg'.
+%   -nocrop - option indicating that empty margins should not be cropped.
 %   -c[<val>,<val>,<val>,<val>] - option indicating crop amounts. Must be
 %             a 4-element vector of numeric values: [top,right,bottom,left]
 %             where NaN/Inf indicate auto-cropping, 0 means no cropping,
 %             and any other value mean cropping in pixel amounts.
-%   -transparent - option indicating that the figure background is to be
-%                  made transparent (png, pdf, tif and eps output only).
+%   -transparent - option indicating that the figure background is to be made
+%             transparent (PNG,PDF,TIF,EPS formats only). Implies -noinvert.
 %   -m<val> - option where val indicates the factor to magnify the
 %             on-screen figure pixel dimensions by when generating bitmap
@@ -116,20 +123,19 @@
 %             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).
+%             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). Default value: opengl for bitmap formats or
-%                 figures with patches and/or transparent annotations;
-%                 painters for vector formats without patches/transparencies.
+%             zbuffer). Default value: opengl for bitmap formats or
+%             figures with patches and/or transparent annotations;
+%             painters for vector formats without patches/transparencies.
 %   -<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.
+%             be saved in: RGB (default), CMYK or gray. Usage example: '-gray'.
+%             Note: CMYK is only supported in PDF, EPS and TIF formats.
+%   -q<val> - option to vary bitmap image quality (PDF, EPS, JPG formats only).
+%             A larger val, in the range 0-100, produces higher quality and
+%             lower compression. val > 100 results in 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 image type.
 %   -p<val> - option to pad a border of width val to exported files, where
 %             val is either a relative size with respect to cropped image
@@ -139,13 +145,13 @@
 %             If used, the -nocrop flag will be ignored, i.e. the image will
 %             always be cropped and then padded. Default: 0 (i.e. no padding).
-%   -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).
+%   -append - option indicating that if the file already exists the figure is to
+%             be appended as a new page, instead of being overwritten (default).
+%             PDF & TIF output formats only.
 %   -bookmark - option to indicate that a bookmark with the name of the
-%               figure is to be created in the output file (pdf only).
+%             figure is to be created in the output file (PDF format only).
 %   -clipboard - option to save output as an image on the system clipboard.
-%                Note: background transparency is not preserved in clipboard
+%             Note: background transparency is not preserved in clipboard
 %   -d<gs_option> - option to indicate a ghostscript setting. For example,
-%                   -dMaxBitmap=0 or -dNoOutputFonts (Ghostscript 9.15+).
+%             -dMaxBitmap=0 or -dNoOutputFonts (Ghostscript 9.15+).
 %   -depsc -  option to use EPS level-3 rather than the default level-2 print
 %             device. This solves some bugs with Matlab's default -depsc2 device
@@ -155,8 +161,19 @@
 %             done in vector formats (only): 11 standard Matlab fonts are
 %             replaced by the original figure fonts. This option prevents this.
+%   -font_space <char> - option to set a spacer character for font-names that
+%             contain spaces, used by EPS/PDF. Default: ''
 %   -linecaps - option to create rounded line-caps (vector formats only).
+%   -noinvert - option to avoid setting figure's InvertHardcopy property to
+%             'off' during output (this solves some problems of empty outputs).
+%   -preserve_size - option to preserve the figure's PaperSize property in output
+%             file (PDF/EPS formats only; default is to not preserve it).
+%   -options <optionsStruct> - format-specific parameters as defined in Matlab's
+%             documentation of the imwrite function, contained in a struct under
+%             the format name. For example to specify the JPG Comment parameter,
+%             pass a struct such as this: options.JPG.Comment='abc'. Similarly,
+%             options.PNG.BitDepth=4. Valid only for PNG,TIF,JPG output formats.
 %   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.
+%             handles, but the objects must be in the same figure) which is
+%             to be saved. Default: gcf (handle of current figure).
 %
 % Outputs:
@@ -248,4 +265,30 @@
 % 22/03/17: Fixed issue #187: only set manual ticks when no exponent is present
 % 09/04/17: Added -linecaps option (idea by Baron Finer, issue #192)
+% 15/09/17: Fixed issue #205: incorrect tick-labels when Ticks number don't match the TickLabels number
+% 15/09/17: Fixed issue #210: initialize alpha map to ones instead of zeros when -transparent is not used
+% 18/09/17: Added -font_space option to replace font-name spaces in EPS/PDF (workaround for issue #194)
+% 18/09/17: Added -noinvert option to solve some export problems with some graphic cards (workaround for issue #197)
+% 08/11/17: Fixed issue #220: axes exponent is removed in HG1 when TickMode is 'manual' (internal Matlab bug)
+% 08/11/17: Fixed issue #221: alert if the requested folder does not exist
+% 19/11/17: Workaround for issue #207: alert when trying to use transparent bgcolor with -opengl
+% 29/11/17: Workaround for issue #206: warn if exporting PDF/EPS for a figure that contains an image
+% 11/12/17: Fixed issue #230: use OpenGL renderer when exported image contains transparency (also see issue #206)
+% 30/01/18: Updated SVG message to point to https://github.com/kupiqu/plot2svg and display user-selected filename if available
+% 27/02/18: Fixed issue #236: axes exponent cropped from output if on right-hand axes
+% 29/05/18: Fixed issue #245: process "string" inputs just like 'char' inputs
+% 13/08/18: Fixed issue #249: correct black axes color to off-black to avoid extra cropping with -transparent
+% 27/08/18: Added a possible file-open reason in EPS/PDF write-error message (suggested by "craq" on FEX page)
+% 22/09/18: Xpdf website changed to xpdfreader.com
+% 23/09/18: Fixed issue #243: only set non-bold font (workaround for issue #69) in R2015b or earlier; warn if changing font
+% 23/09/18: Workaround for issue #241: don't use -r864 in EPS/PDF outputs when -native is requested (solves black lines problem)
+% 18/11/18: Issue #261: Added informative alert when trying to export a uifigure (which is not currently supported)
+% 13/12/18: Issue #261: Fixed last commit for cases of specifying axes/panel handle as input, rather than a figure handle
+% 13/01/19: Issue #72: Added basic SVG output support
+% 04/02/19: Workaround for issues #207 and #267: -transparent implies -noinvert
+% 08/03/19: Issue #269: Added ability to specify format-specific options for PNG,TIF,JPG outputs; fixed help section
+% 21/03/19: Fixed the workaround for issues #207 and #267 from 4/2/19 (-transparent now does *NOT* imply -noinvert; -transparent output should now be ok in all formats)
+% 12/06/19: Issue #277: Enabled preservation of figure's PaperSize in output PDF/EPS file
+% 06/08/19: Remove warning message about obsolete JavaFrame in R2019b
+% 30/10/19: Fixed issue #261: added support for exporting uifigures and uiaxes (thanks to idea by @MarvinILA)
 %}
 
@@ -266,7 +309,63 @@
     % Ensure that we have a figure handle
     if isequal(fig,-1)
-        return;  % silent bail-out
+        return  % silent bail-out
     elseif isempty(fig)
         error('No figure found');
+    else
+        oldWarn = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
+        warning off MATLAB:ui:javaframe:PropertyToBeRemoved
+        uifig = handle(ancestor(fig,'figure'));
+        try jf = get(uifig,'JavaFrame'); catch, jf=1; end
+        warning(oldWarn);
+        if isempty(jf)  % this is a uifigure
+            %error('Figures created using the uifigure command or App Designer are not supported by export_fig. See <a href="https://github.com/altmany/export_fig/issues/261">issue #261</a> for details.');
+            if numel(fig) > 1
+                error('export_fig:uifigure:multipleHandles', 'export_fig only supports exporting a single uifigure handle at a time; array of handles is not currently supported.')
+            elseif ~any(strcmpi(fig.Type,{'figure','axes'}))
+                error('export_fig:uifigure:notFigureOrAxes', 'export_fig only supports exporting a uifigure or uiaxes handle; other handles of a uifigure are not currently supported.')
+            end
+            % fig is either a uifigure or uiaxes handle
+            isUiaxes = strcmpi(fig.Type,'axes');
+            if isUiaxes
+                % Label the specified axes so that we can find it in the legacy figure
+                oldUserData = fig.UserData;
+                tempStr = tempname;
+                fig.UserData = tempStr;
+            end
+            try
+                % Create an invisible legacy figure at the same position/size as the uifigure
+                hNewFig = figure('Units',uifig.Units, 'Position',uifig.Position, 'MenuBar','none', 'ToolBar','none', 'Visible','off');
+                % Copy the uifigure contents onto the new invisible legacy figure
+                try
+                    hChildren = allchild(uifig); %=uifig.Children;
+                    copyobj(hChildren,hNewFig);
+                catch
+                    warning('export_fig:uifigure:controls', 'Some uifigure controls cannot be exported by export_fig and will not appear in the generated output.');
+                end
+                try fig.UserData = oldUserData; catch, end  % restore axes UserData, if modified above
+                % Replace the uihandle in the input args with the legacy handle
+                if isUiaxes  % uiaxes
+                    % Locate the corresponding axes handle in the new legacy figure
+                    hAxes = findall(hNewFig,'type','axes','UserData',tempStr);
+                    if isempty(hAxes) % should never happen, check just in case
+                        hNewHandle = hNewFig;  % export the figure instead of the axes
+                    else
+                        hNewHandle = hAxes;  % new axes handle found: use it instead of the uiaxes
+                    end
+                else  % uifigure
+                    hNewHandle = hNewFig;
+                end
+                varargin(cellfun(@(c)isequal(c,fig),varargin)) = {hNewHandle};
+                % Rerun export_fig on the legacy figure (with the replaced handle)
+                [imageData, alpha] = export_fig(varargin{:});
+                % Delete the temp legacy figure and bail out
+                try delete(hNewFig); catch, end
+                return
+            catch err
+                % Clean up the temp legacy figure and report the error
+                try delete(hNewFig); catch, end
+                rethrow(err)
+            end
+        end
     end
 
@@ -337,7 +436,14 @@
             % Set the FontWeight of axes labels/titles to 'normal'
             % Fix issue #69: set non-bold font only if the string contains symbols (\beta etc.)
-            texLabels = findall(fig, 'type','text', 'FontWeight','bold');
-            symbolIdx = ~cellfun('isempty',strfind({texLabels.String},'\'));
-            set(texLabels(symbolIdx), 'FontWeight','normal');
+            % Issue #243: only set non-bold font (workaround for issue #69) in R2015b or earlier
+            try isPreR2016a = verLessThan('matlab','8.7'); catch, isPreR2016a = true; end
+            if isPreR2016a
+                texLabels = findall(fig, 'type','text', 'FontWeight','bold');
+                symbolIdx = ~cellfun('isempty',strfind({texLabels.String},'\'));
+                if ~isempty(symbolIdx)
+                    set(texLabels(symbolIdx), 'FontWeight','normal');
+                    warning('export_fig:BoldTexLabels', 'Bold labels with Tex symbols converted into non-bold in export_fig (fix for issue #69)');
+                end
+            end
         end
     catch
@@ -365,5 +471,8 @@
 
     % Set to print exactly what is there
-    set(fig, 'InvertHardcopy', 'off');
+    if options.invert_hardcopy
+        try set(fig, 'InvertHardcopy', 'off'); catch, end  % fail silently in uifigures
+    end
+
     % Set the renderer
     switch options.renderer
@@ -377,4 +486,6 @@
             renderer = '-opengl'; % Default for bitmaps
     end
+
+    hImages = findall(fig,'type','image');
 
     % Handle transparent patches
@@ -390,4 +501,13 @@
         elseif ~options.png && ~options.tif  % issue #168
             warning('export_fig:transparency', '%s\nTo export the transparency correctly, try using the ScreenCapture utility on the Matlab File Exchange: http://bit.ly/1QFrBip', msg);
+        end
+    elseif ~isempty(hImages)
+        % Fix for issue #230: use OpenGL renderer when exported image contains transparency
+        for idx = 1 : numel(hImages)
+            cdata = get(hImages(idx),'CData');
+            if any(isnan(cdata(:)))
+                hasTransparency = true;
+                break
+            end
         end
     end
@@ -428,4 +548,9 @@
                 set(hCB(yCol==0), 'YColor', [0 0 0]);
                 set(hCB(xCol==0), 'XColor', [0 0 0]);
+                % Correct black axes color to off-black (issue #249)
+                hAxes = findall(fig, 'Type','axes');
+                hXs = fixBlackAxle(hAxes, 'XColor');
+                hYs = fixBlackAxle(hAxes, 'YColor');
+                hZs = fixBlackAxle(hAxes, 'ZColor');
 
                 % The following code might cause out-of-memory errors
@@ -445,4 +570,8 @@
                 set(hCB(yCol==3), 'YColor', [1 1 1]);
                 set(hCB(xCol==3), 'XColor', [1 1 1]);
+                % Revert the black axes colors
+                set(hXs, 'XColor', [0,0,0]);
+                set(hYs, 'YColor', [0,0,0]);
+                set(hZs, 'ZColor', [0,0,0]);
 
                 % The following code might cause out-of-memory errors
@@ -487,5 +616,12 @@
                     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);
+                    [format_options, bitDepth] = getFormatOptions(options, 'png');  %Issue #269
+                    if ~isempty(bitDepth) && bitDepth < 16 && size(A,3) == 3
+                        % BitDepth specification requires using a color-map
+                        [A, map] = rgb2ind(A, 256);
+                        imwrite(A, map, [options.name '.png'], 'Alpha',double(alpha), 'ResolutionUnit','meter', 'XResolution',res, 'YResolution',res, format_options{:});
+                    else
+                        imwrite(A, [options.name '.png'], 'Alpha',double(alpha), 'ResolutionUnit','meter', 'XResolution',res, 'YResolution',res, format_options{:});
+                    end
                     % Clear the png bit
                     options.png = false;
@@ -544,5 +680,5 @@
                 if options.alpha
                     imageData = A;
-                    alpha = zeros(size(A, 1), size(A, 2), 'single');
+                    alpha = ones(size(A, 1), size(A, 2), 'single');
                 end
             end
@@ -550,5 +686,12 @@
             if options.png
                 res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
-                imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
+                [format_options, bitDepth] = getFormatOptions(options, 'png');  %Issue #269
+                if ~isempty(bitDepth) && bitDepth < 16 && size(A,3) == 3
+                    % BitDepth specification requires using a color-map
+                    [A, map] = rgb2ind(A, 256);
+                    imwrite(A, map, [options.name '.png'], 'ResolutionUnit','meter', 'XResolution',res, 'YResolution',res, format_options{:});
+                else
+                    imwrite(A, [options.name '.png'], 'ResolutionUnit','meter', 'XResolution',res, 'YResolution',res, format_options{:});
+                end
             end
             if options.bmp
@@ -561,8 +704,9 @@
                     quality = 95;
                 end
+                format_options = getFormatOptions(options, 'jpg');  %Issue #269
                 if quality > 100
-                    imwrite(A, [options.name '.jpg'], 'Mode', 'lossless');
+                    imwrite(A, [options.name '.jpg'], 'Mode','lossless', format_options{:});
                 else
-                    imwrite(A, [options.name '.jpg'], 'Quality', quality);
+                    imwrite(A, [options.name '.jpg'], 'Quality',quality, format_options{:});
                 end
             end
@@ -580,5 +724,6 @@
                 end
                 append_mode = {'overwrite', 'append'};
-                imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1});
+                format_options = getFormatOptions(options, 'tif');  %Issue #269
+                imwrite(A, [options.name '.tif'], 'Resolution',options.magnify*get(0,'ScreenPixelsPerInch'), 'WriteMode',append_mode{options.append+1}, format_options{:});
             end
         end
@@ -590,5 +735,5 @@
                 if hasTransparency || hasPatches
                     % This is *MUCH* slower, but more accurate for patches and transparent annotations (issue #39)
-                    renderer = '-painters'; %ISSM fix
+                    renderer = '-opengl';
                 else
                     renderer = '-painters';
@@ -624,26 +769,55 @@
             end
             % Generate the options for print
-            p2eArgs = {renderer, sprintf('-r%d', options.resolution)};
+            printArgs = {renderer};
+            if ~isempty(options.resolution)  % issue #241
+                printArgs{end+1} = sprintf('-r%d', options.resolution);
+            end
             if options.colourspace == 1  % CMYK
                 % Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option
-                %p2eArgs{end+1} = '-cmyk';
+                %printArgs{end+1} = '-cmyk';
             end
             if ~options.crop
                 % Issue #56: due to internal bugs in Matlab's print() function, we can't use its internal cropping mechanism,
                 % therefore we always use '-loose' (in print2eps.m) and do our own cropping (in crop_borders)
-                %p2eArgs{end+1} = '-loose';
+                %printArgs{end+1} = '-loose';
             end
             if any(strcmpi(varargin,'-depsc'))
                 % Issue #45: lines in image subplots are exported in invalid color.
                 % The workaround is to use the -depsc parameter instead of the default -depsc2
-                p2eArgs{end+1} = '-depsc';
+                printArgs{end+1} = '-depsc';
             end
             try
+                % Remove background if requested (issue #207)
+                originalBgColor = get(fig, 'Color');
+                [hXs, hYs, hZs] = deal([]);
+                if options.transparent %&& ~isequal(get(fig, 'Color'), 'none')
+                    if options.renderer == 1  % OpenGL
+                        warning('export_fig:openglTransparentBG', '-opengl sometimes fails to produce transparent backgrounds; in such a case, try to use -painters instead');
+                    end
+
+                    % Fix for issue #207, #267 (corrected)
+                    set(fig,'Color','none');
+
+                    % Correct black axes color to off-black (issue #249)
+                    hAxes = findall(fig, 'Type','axes');
+                    hXs = fixBlackAxle(hAxes, 'XColor');
+                    hYs = fixBlackAxle(hAxes, 'YColor');
+                    hZs = fixBlackAxle(hAxes, 'ZColor');
+                end
                 % Generate an eps
-                print2eps(tmp_nam, fig, options, p2eArgs{:});
+                print2eps(tmp_nam, fig, options, printArgs{:});
+                % {
                 % Remove the background, if desired
-                if options.transparent && ~isequal(get(fig, 'Color'), 'none')
+                if options.transparent %&& ~isequal(get(fig, 'Color'), 'none')
                     eps_remove_background(tmp_nam, 1 + using_hg2(fig));
-                end
+
+                    % Revert the black axes colors
+                    set(hXs, 'XColor', [0,0,0]);
+                    set(hYs, 'YColor', [0,0,0]);
+                    set(hZs, 'ZColor', [0,0,0]);
+                end
+                %}
+                % Restore the figure's previous background color (if modified)
+                try set(fig,'Color',originalBgColor); drawnow; catch, end
                 % Fix colorspace to CMYK, if requested (workaround for issue #33)
                 if options.colourspace == 1  % CMYK
@@ -671,5 +845,6 @@
                     % Alert in case of error creating output PDF/EPS file (issue #179)
                     if exist(pdf_nam_tmp, 'file')
-                        error(['Could not create ' pdf_nam ' - perhaps the folder does not exist, or you do not have write permissions']);
+                        errMsg = ['Could not create ' pdf_nam ' - perhaps the folder does not exist, or you do not have write permissions, or the file is open in another application'];
+                        error(errMsg);
                     else
                         error('Could not generate the intermediary EPS file.');
@@ -677,6 +852,9 @@
                 end
             catch ex
+                % Restore the figure's previous background color (in case it was not already restored)
+                try set(fig,'Color',originalBgColor); drawnow; catch, end
                 % Delete the eps
                 delete(tmp_nam);
+                % Rethrow the EPS/PDF-generation error
                 rethrow(ex);
             end
@@ -718,4 +896,54 @@
                 end
             end
+            % Issue #206: warn if the figure contains an image
+            if ~isempty(hImages) && strcmpi(renderer,'-opengl')  % see addendum to issue #206
+                warnMsg = ['exporting images to PDF/EPS may result in blurry images on some viewers. ' ...
+                           'If so, try to change viewer, or increase the image''s CData resolution, or use -opengl renderer, or export via the print function. ' ...
+                           'See <a href="matlab:web(''https://github.com/altmany/export_fig/issues/206'',''-browser'');">issue #206</a> for details.'];
+                warning('export_fig:pdf_eps:blurry_image', warnMsg);
+            end
+        end
+
+        % SVG format
+        if options.svg
+            oldUnits = get(fig,'Units');
+            filename = [options.name '.svg'];
+            % Adapted from Dan Joshea's https://github.com/djoshea/matlab-save-figure :
+            try %if verLessThan('matlab', '8.4')
+                % Try using the fig2svg/plot2svg utilities
+                try
+                    fig2svg(filename, fig);  %https://github.com/kupiqu/fig2svg
+                catch
+                    plot2svg(filename, fig); %https://github.com/jschwizer99/plot2svg
+                    warning('export_fig:SVG:plot2svg', 'export_fig used the plot2svg utility for SVG output. Better results may be gotten via the fig2svg utility (https://github.com/kupiqu/fig2svg).');
+                end
+            catch %else  % (neither fig2svg nor plot2svg are available)
+                % Try Matlab's built-in svg engine (from Batik Graphics2D for java)
+                try
+                    set(fig,'Units','pixels');   % All data in the svg-file is saved in pixels
+                    printArgs = {renderer};
+                    if ~isempty(options.resolution)
+                        printArgs{end+1} = sprintf('-r%d', options.resolution);
+                    end
+                    print(fig, '-dsvg', printArgs{:}, filename);
+                    warning('export_fig:SVG:print', 'export_fig used Matlab''s built-in SVG output engine. Better results may be gotten via the fig2svg utility (https://github.com/kupiqu/fig2svg).');
+                catch err  % built-in print() failed - maybe an old Matlab release (no -dsvg)
+                    set(fig,'Units',oldUnits);
+                    filename = strrep(filename,'export_fig_out','filename');
+                    msg = ['SVG output is not supported for your figure: ' err.message '\n' ...
+                        'Try one of the following alternatives:\n' ...
+                        '  1. saveas(gcf,''' filename ''')\n' ...
+                        '  2. fig2svg utility: https://github.com/kupiqu/fig2svg\n' ...  % Note: replaced defunct https://github.com/jschwizer99/plot2svg with up-to-date fork on https://github.com/kupiqu/fig2svg
+                        '  3. export_fig to EPS/PDF, then convert to SVG using non-Matlab tools\n'];
+                    error(sprintf(msg)); %#ok<SPERR>
+                end
+            end
+            % SVG output was successful if we reached this point
+            % Restore original figure units
+            set(fig,'Units',oldUnits);
+            % Add warning about unsupported export_fig options with SVG output
+            if any(~isnan(options.crop_amounts)) || any(options.bb_padding)
+                warning('export_fig:SVG:options', 'export_fig''s SVG output does not [currently] support cropping/padding.');
+            end
         end
 
@@ -726,5 +954,5 @@
         else
             % Reset the hardcopy mode
-            set(fig, 'InvertHardcopy', old_mode);
+            try set(fig, 'InvertHardcopy', old_mode); catch, end  % fail silently in uifigures
             % Reset the axes limit and tick modes
             for a = 1:numel(Hlims)
@@ -775,5 +1003,5 @@
                 error(javachk('awt', 'export_fig -clipboard output'));
             catch
-                warning('export_fig -clipboard output failed: requires Java to work');
+                warning('export_fig:clipboardJava', 'export_fig -clipboard output failed: requires Java to work');
                 return;
             end
@@ -821,5 +1049,5 @@
                 cb.setContents(imSelection, []);
             catch
-                warning('export_fig -clipboard output failed: %s', lasterr); %#ok<LERR>
+                warning('export_fig:clipboardFailed', 'export_fig -clipboard output failed: %s', lasterr); %#ok<LERR>
             end
         end
@@ -835,12 +1063,14 @@
             fprintf(2, 'Please ensure:\n');
             fprintf(2, '  that you are using the <a href="https://github.com/altmany/export_fig/archive/master.zip">latest version</a> of export_fig\n');
-            if ismac
-                fprintf(2, '  and that you have <a href="http://pages.uoregon.edu/koch">Ghostscript</a> installed\n');
-            else
-                fprintf(2, '  and that you have <a href="http://www.ghostscript.com">Ghostscript</a> installed\n');
+            if isvector(options)
+                if ismac
+                    fprintf(2, '  and that you have <a href="http://pages.uoregon.edu/koch">Ghostscript</a> installed\n');
+                else
+                    fprintf(2, '  and that you have <a href="http://www.ghostscript.com">Ghostscript</a> installed\n');
+                end
             end
             try
                 if options.eps
-                    fprintf(2, '  and that you have <a href="http://www.foolabs.com/xpdf">pdftops</a> installed\n');
+                    fprintf(2, '  and that you have <a href="http://xpdfreader.com/download.html">pdftops</a> installed\n');
                 end
             catch
@@ -866,35 +1096,43 @@
     % Default options used by export_fig
     options = struct(...
-        'name',         'export_fig_out', ...
-        'crop',         true, ...
-        'crop_amounts', nan(1,4), ...  % auto-crop all 4 image sides
-        'transparent',  false, ...
-        'renderer',     0, ...         % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters
-        'pdf',          false, ...
-        'eps',          false, ...
-        'png',          false, ...
-        'tif',          false, ...
-        'jpg',          false, ...
-        'bmp',          false, ...
-        'clipboard',    false, ...
-        'colourspace',  0, ...         % 0: RGB/gray, 1: CMYK, 2: gray
-        'append',       false, ...
-        'im',           false, ...
-        'alpha',        false, ...
-        'aa_factor',    0, ...
-        'bb_padding',   0, ...
-        'magnify',      [], ...
-        'resolution',   [], ...
-        'bookmark',     false, ...
-        'closeFig',     false, ...
-        'quality',      [], ...
-        'update',       false, ...
-        'fontswap',     true, ...
-        'linecaps',     false, ...
-        'gs_options',   {{}});
+        'name',            'export_fig_out', ...
+        'crop',            true, ...
+        'crop_amounts',    nan(1,4), ...  % auto-crop all 4 image sides
+        'transparent',     false, ...
+        'renderer',        0, ...         % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters
+        'pdf',             false, ...
+        'eps',             false, ...
+        'svg',             false, ...
+        'png',             false, ...
+        'tif',             false, ...
+        'jpg',             false, ...
+        'bmp',             false, ...
+        'clipboard',       false, ...
+        'colourspace',     0, ...         % 0: RGB/gray, 1: CMYK, 2: gray
+        'append',          false, ...
+        'im',              false, ...
+        'alpha',           false, ...
+        'aa_factor',       0, ...
+        'bb_padding',      0, ...
+        'magnify',         [], ...
+        'resolution',      [], ...
+        'bookmark',        false, ...
+        'closeFig',        false, ...
+        'quality',         [], ...
+        'update',          false, ...
+        'fontswap',        true, ...
+        'font_space',      '', ...
+        'linecaps',        false, ...
+        'invert_hardcopy', true, ...
+        'format_options',  struct, ...
+        'preserve_size',   false, ...
+        'gs_options',      {{}});
 end
 
 function [fig, options] = parse_args(nout, fig, varargin)
     % Parse the input arguments
+
+    % Convert strings => chars
+    varargin = cellfun(@str2char,varargin,'un',false);
 
     % Set the defaults
@@ -931,4 +1169,6 @@
                     case 'eps'
                         options.eps = true;
+                    case 'svg'
+                        options.svg = true;
                     case 'png'
                         options.png = true;
@@ -957,10 +1197,4 @@
                         options.im = true;
                         options.alpha = true;
-                    case 'svg'
-                        msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\n' ...
-                               '  1. saveas(gcf,''filename.svg'')\n' ...
-                               '  2. plot2svg utility: http://github.com/jschwizer99/plot2svg\n' ...
-                               '  3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\n'];
-                        error(sprintf(msg)); %#ok<SPERR>
                     case 'update'
                         % Download the latest version of export_fig into the export_fig folder
@@ -969,5 +1203,5 @@
                             folderName = fileparts(which(mfilename('fullpath')));
                             targetFileName = fullfile(folderName, datestr(now,'yyyy-mm-dd.zip'));
-                            urlwrite(zipFileName,targetFileName);
+                            urlwrite(zipFileName,targetFileName); %#ok<URLWR>
                         catch
                             error('Could not download %s into %s\n',zipFileName,targetFileName);
@@ -982,6 +1216,26 @@
                     case 'nofontswap'
                         options.fontswap = false;
+                    case 'font_space'
+                        options.font_space = varargin{a+1};
+                        skipNext = true;
                     case 'linecaps'
                         options.linecaps = true;
+                    case 'noinvert'
+                        options.invert_hardcopy = false;
+                    case 'preserve_size'
+                        options.preserve_size = true;
+                    case 'options'
+                        % Issue #269: format-specific options
+                        inputOptions = varargin{a+1};
+                        %options.format_options  = inputOptions;
+                        if isempty(inputOptions), continue, end
+                        formats = fieldnames(inputOptions(1));
+                        for idx = 1 : numel(formats)
+                            optionsStruct = inputOptions.(formats{idx});
+                            %optionsCells = [fieldnames(optionsStruct) struct2cell(optionsStruct)]';
+                            formatName = regexprep(lower(formats{idx}),{'tiff','jpeg'},{'tif','jpg'});
+                            options.format_options.(formatName) = optionsStruct; %=optionsCells(:)';
+                        end
+                        skipNext = true;
                     otherwise
                         try
@@ -1044,4 +1298,6 @@
                 [p, options.name, ext] = fileparts(varargin{a});
                 if ~isempty(p)
+                    % Issue #221: alert if the requested folder does not exist
+                    if ~exist(p,'dir'),  error(['Folder ' p ' does not exist!']);  end
                     options.name = [p filesep options.name];
                 end
@@ -1072,9 +1328,5 @@
                         end
                     case '.svg'
-                        msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\n' ...
-                               '  1. saveas(gcf,''filename.svg'')\n' ...
-                               '  2. plot2svg utility: http://github.com/jschwizer99/plot2svg\n' ...
-                               '  3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\n'];
-                        error(sprintf(msg)); %#ok<SPERR>
+                        options.svg = true;
                     otherwise
                         options.name = varargin{a};
@@ -1127,45 +1379,56 @@
     % 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 = findall(fig, 'Type','image', 'Tag','export_fig_native');
-        if isempty(list)
-            list = findall(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
-                yl = [min(yl), max(yl)];  % fix issue #151 (case of yl containing more than 2 elements)
-                if ~diff(yl)
+    if native
+        if isbitmap(options)
+            % Find a suitable image
+            list = findall(fig, 'Type','image', 'Tag','export_fig_native');
+            if isempty(list)
+                list = findall(fig, 'Type','image', 'Visible','on');
+            end
+            for hIm = list(:)'
+                % Check height is >= 2
+                height = size(get(hIm, 'CData'), 1);
+                if height < 2
                     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 = abs((height * diff(yl2)) / (pos * diff(yl)));  % magnification must never be negative: issue #103
-            break
-        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
+                    yl = [min(yl), max(yl)];  % fix issue #151 (case of yl containing more than 2 elements)
+                    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 = abs((height * diff(yl2)) / (pos * diff(yl)));  % magnification must never be negative: issue #103
+                break
+            end
+        elseif options.resolution == 864  % don't use -r864 in vector mode if user asked for -native
+            options.resolution = []; % issue #241 (internal Matlab bug produces black lines with -r864)
+        end
+    end
+end
+
+% Convert a possible string => char (issue #245)
+function value = str2char(value)
+    if isa(value,'string')
+        value = char(value);
     end
 end
@@ -1304,9 +1567,22 @@
             hAxes = Hlims(idx(idx2));
             props = {[ax 'TickMode'],'manual', [ax 'TickLabelMode'],'manual'};
-            if isempty(strtrim(hAxes.([ax 'Ruler']).SecondaryLabel.String))
-                set(hAxes, props{:});  % no exponent, so update moth ticks and tick labels to manual
+            tickVals = get(hAxes,[ax 'Tick']);
+            tickStrs = get(hAxes,[ax 'TickLabel']);
+            try % Fix issue #236
+                exponents = [hAxes.([ax 'Axis']).SecondaryLabel];
+            catch
+                exponents = [hAxes.([ax 'Ruler']).SecondaryLabel];
+            end
+            if isempty([exponents.String])
+                % Fix for issue #205 - only set manual ticks when the Ticks number match the TickLabels number
+                if numel(tickVals) == numel(tickStrs)
+                    set(hAxes, props{:});  % no exponent and matching ticks, so update both ticks and tick labels to manual
+                end
             end
         catch  % probably HG1
-            set(hAxes, props{:});  % revert back to old behavior
+            % Fix for issue #220 - exponent is removed in HG1 when TickMode is 'manual' (internal Matlab bug)
+            if isequal(tickVals, str2num(tickStrs)') %#ok<ST2NM>
+                set(hAxes, props{:});  % revert back to old behavior
+            end
         end
     end
@@ -1332,2 +1608,38 @@
     end
 end
+
+function hBlackAxles = fixBlackAxle(hAxes, axleName)
+    hBlackAxles = [];
+    for idx = 1 : numel(hAxes)
+        ax = hAxes(idx);
+        axleColor = get(ax, axleName);
+        if isequal(axleColor,[0,0,0]) || isequal(axleColor,'k')
+            hBlackAxles(end+1) = ax; %#ok<AGROW>
+        end
+    end
+    set(hBlackAxles, axleName, [0,0,0.01]);  % off-black
+end
+
+% Issue #269: format-specific options
+function [optionsCells, bitDepth] = getFormatOptions(options, formatName)
+    bitDepth = [];
+    try
+        optionsStruct = options.format_options.(lower(formatName));
+    catch
+        % User did not specify any extra parameters for this format
+        optionsCells = {};
+        return
+    end
+    optionNames = fieldnames(optionsStruct);
+    optionVals  = struct2cell(optionsStruct);
+    optionsCells = [optionNames, optionVals]';
+    if nargout < 2, return, end  % bail out if BitDepth is not required
+    try
+        idx = find(strcmpi(optionNames,'BitDepth'), 1, 'last');
+        if ~isempty(idx)
+            bitDepth = optionVals{idx};
+        end
+    catch
+        % never mind - ignore
+    end
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/im2gif.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/im2gif.m	(revision 24459)
+++ /issm/trunk-jpl/externalpackages/export_fig/im2gif.m	(revision 24460)
@@ -42,145 +42,164 @@
 % Copyright (C) Oliver Woodford 2011
 
+%{
+% 14/02/18: Merged issue #235: reduced memory usage, improved performance (thanks to @numb7rs)
+% 30/11/19: Merged issue #288: Fix im2gif.m for greyscale TIFF images (thanks @Blackbelt1221)
+%}
+
 function im2gif(A, varargin)
 
-% Parse the input arguments
-[A, options] = parse_args(A, varargin{:});
-
-if options.crop ~= 0
-    % Crop
-    A = crop_borders(A, A(ceil(end/2),1,:,1));
-end
-
-% Convert to indexed image
-[h, w, c, n] = size(A);
-A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
-map = unique(reshape(A, h*w*n, c), 'rows');
-if size(map, 1) > 256
-    dither_str = {'dither', 'nodither'};
-    dither_str = dither_str{1+(options.dither==0)};
-    if options.ncolors <= 1
-        [B, map] = rgb2ind(A, options.ncolors, dither_str);
-        if size(map, 1) > 256
-            [B, map] = rgb2ind(A, 256, dither_str);
+    % Parse the input arguments
+    [A, options] = parse_args(A, varargin{:});
+
+    if options.crop ~= 0
+        % Crop
+        A = crop_borders(A, A(ceil(end/2),1,:,1));
+    end
+
+    % Convert to indexed image
+    [h, w, c, n] = size(A);
+
+    % Issue #235: Using unique(A,'rows') on the whole image stack at once causes
+    % massive memory usage when dealing with large images (at least on Matlab 2017b).
+    % Running unique(...) on individual frames, then again on the results drastically
+    % reduces the memory usage & slightly improves the execution time (@numb7rs).
+    uns = cell(1,size(A,4));
+    for nn=1:size(A,4)
+        uns{nn}=unique(reshape(A(:,:,:,nn), h*w, c),'rows');
+    end
+    map=unique(cell2mat(uns'),'rows');
+
+    A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
+
+    if size(map, 1) > 256
+        dither_str = {'dither', 'nodither'};
+        dither_str = dither_str{1+(options.dither==0)};
+        if options.ncolors <= 1
+            [B, map] = rgb2ind(A, options.ncolors, dither_str);
+            if size(map, 1) > 256
+                [B, map] = rgb2ind(A, 256, dither_str);
+            end
+        else
+            [B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
         end
     else
-        [B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
-    end
-else
-    if max(map(:)) > 1
-        map = double(map) / 255;
-        A = double(A) / 255;
-    end
-    B = rgb2ind(im2double(A), map);
-end
-B = reshape(B, h, w, 1, n);
-
-% Bug fix to rgb2ind
-map(B(1)+1,:) = im2double(A(1,1,:));
-
-% Save as a gif
-imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
+        if max(map(:)) > 1
+            map = double(map) / 255;
+            A = double(A) / 255;
+        end
+        B = rgb2ind(im2double(A), map);
+    end
+    B = reshape(B, h, w, 1, n);
+
+    % Bug fix to rgb2ind
+    map(B(1)+1,:) = im2double(A(1,1,:));
+
+    % Save as a gif
+    imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
 end
 
 %% Parse the input arguments
 function [A, options] = parse_args(A, varargin)
-% Set the defaults
-options = struct('outfile', '', ...
-                 'dither', true, ...
-                 'crop', true, ...
-                 'ncolors', 256, ...
-                 'loops', 65535, ...
-                 'delay', 1/15);
-
-% Go through the arguments
-a = 0;
-n = numel(varargin);
-while a < n
-    a = a + 1;
-    if ischar(varargin{a}) && ~isempty(varargin{a})
-        if varargin{a}(1) == '-'
-            opt = lower(varargin{a}(2:end));
-            switch opt
-                case 'nocrop'
-                    options.crop = false;
-                case 'nodither'
-                    options.dither = false;
-                otherwise
-                    if ~isfield(options, opt)
-                        error('Option %s not recognized', varargin{a});
-                    end
-                    a = a + 1;
-                    if ischar(varargin{a}) && ~ischar(options.(opt))
-                        options.(opt) = str2double(varargin{a});
-                    else
-                        options.(opt) = varargin{a};
-                    end
-            end
-        else
-            options.outfile = varargin{a};
-        end
-    end
-end
-
-if isempty(options.outfile)
-    if ~ischar(A)
-        error('No output filename given.');
-    end
-    % Generate the output filename from the input filename
-    [path, outfile] = fileparts(A);
-    options.outfile = fullfile(path, [outfile '.gif']);
-end
-
-if ischar(A)
-    % Read in the image
-    A = imread_rgb(A);
-end
+    % Set the defaults
+    options = struct('outfile', '', ...
+                     'dither', true, ...
+                     'crop', true, ...
+                     'ncolors', 256, ...
+                     'loops', 65535, ...
+                     'delay', 1/15);
+
+    % Go through the arguments
+    a = 0;
+    n = numel(varargin);
+    while a < n
+        a = a + 1;
+        if ischar(varargin{a}) && ~isempty(varargin{a})
+            if varargin{a}(1) == '-'
+                opt = lower(varargin{a}(2:end));
+                switch opt
+                    case 'nocrop'
+                        options.crop = false;
+                    case 'nodither'
+                        options.dither = false;
+                    otherwise
+                        if ~isfield(options, opt)
+                            error('Option %s not recognized', varargin{a});
+                        end
+                        a = a + 1;
+                        if ischar(varargin{a}) && ~ischar(options.(opt))
+                            options.(opt) = str2double(varargin{a});
+                        else
+                            options.(opt) = varargin{a};
+                        end
+                end
+            else
+                options.outfile = varargin{a};
+            end
+        end
+    end
+
+    if isempty(options.outfile)
+        if ~ischar(A)
+            error('No output filename given.');
+        end
+        % Generate the output filename from the input filename
+        [path, outfile] = fileparts(A);
+        options.outfile = fullfile(path, [outfile '.gif']);
+    end
+
+    if ischar(A)
+        % Read in the image
+        A = imread_rgb(A);
+    end
 end
 
 %% Read image to uint8 rgb array
 function [A, alpha] = imread_rgb(name)
-% Get file info
-info = imfinfo(name);
-% Special case formats
-switch lower(info(1).Format)
-    case 'gif'
-        [A, map] = imread(name, 'frames', 'all');
-        if ~isempty(map)
-            map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
-            A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
-            A = permute(A, [1 2 5 4 3]);
-        end
-    case {'tif', 'tiff'}
-        A = cell(numel(info), 1);
-        for a = 1:numel(A)
-            [A{a}, map] = imread(name, 'Index', a, 'Info', info);
+    % Get file info
+    info = imfinfo(name);
+    % Special case formats
+    switch lower(info(1).Format)
+        case 'gif'
+            [A, map] = imread(name, 'frames', 'all');
             if ~isempty(map)
                 map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
-                A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
-            end
-            if size(A{a}, 3) == 4
-                % TIFF in CMYK colourspace - convert to RGB
-                if isfloat(A{a})
-                    A{a} = A{a} * 255;
-                else
-                    A{a} = single(A{a});
+                A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
+                A = permute(A, [1 2 5 4 3]);
+            end
+        case {'tif', 'tiff'}
+            A = cell(numel(info), 1);
+            for a = 1:numel(A)
+                [A{a}, map] = imread(name, 'Index', a, 'Info', info);
+                if ~isempty(map)
+                    map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
+                    A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
                 end
-                A{a} = 255 - A{a};
-                A{a}(:,:,4) = A{a}(:,:,4) / 255;
-                A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
-            end
-        end
-        A = cat(4, A{:});
-    otherwise
-        [A, map, alpha] = imread(name);
-        A = A(:,:,:,1); % Keep only first frame of multi-frame files
-        if ~isempty(map)
-            map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
-            A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
-        elseif size(A, 3) == 4
-            % Assume 4th channel is an alpha matte
-            alpha = A(:,:,4);
-            A = A(:,:,1:3);
-        end
+                if size(A{a}, 3) == 4
+                    % TIFF in CMYK colourspace - convert to RGB
+                    if isfloat(A{a})
+                        A{a} = A{a} * 255;
+                    else
+                        A{a} = single(A{a});
+                    end
+                    A{a} = 255 - A{a};
+                    A{a}(:,:,4) = A{a}(:,:,4) / 255;
+                    A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
+                elseif size(A{a}, 3) < 3 %Check whether TIFF has been read in as greyscale
+                    %Convert from greyscale to RGB colorspace (issue #288)
+                    A{a} = cat(3, A{a}, A{a}, A{a});
+                end
+            end
+            A = cat(4, A{:});
+        otherwise
+            [A, map, alpha] = imread(name);
+            A = A(:,:,:,1); % Keep only first frame of multi-frame files
+            if ~isempty(map)
+                map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
+                A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
+            elseif size(A, 3) == 4
+                % Assume 4th channel is an alpha matte
+                alpha = A(:,:,4);
+                A = A(:,:,1:3);
+            end
+    end
 end
-end
Index: sm/trunk-jpl/externalpackages/export_fig/license.txt
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/license.txt	(revision 24459)
+++ 	(revision )
@@ -1,24 +1,0 @@
-Copyright (c) 2012, Oliver Woodford
-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
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGE.
Index: /issm/trunk-jpl/externalpackages/export_fig/pdf2eps.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/pdf2eps.m	(revision 24459)
+++ /issm/trunk-jpl/externalpackages/export_fig/pdf2eps.m	(revision 24460)
@@ -8,7 +8,7 @@
 % This function requires that you have pdftops, from the Xpdf suite of
 % functions, installed on your system. This can be downloaded from:
-% http://www.foolabs.com/xpdf  
+% http://xpdfreader.com
 %
-%IN:
+% Inputs:
 %   source - filename of the source pdf file to convert. The filename is
 %            assumed to already have the extension ".pdf".
@@ -16,36 +16,40 @@
 %          already have the extension ".eps".
 
-% Copyright (C) Oliver Woodford 2009-2010
+% Copyright (C) Oliver Woodford 2009-2010, Yair Altman 2015-
 
 % Thanks to Aldebaro Klautau for reporting a bug when saving to
 % non-existant directories.
 
+% 22/09/2018 - Xpdf website changed to xpdfreader.com
+
 function pdf2eps(source, dest)
-% Construct the options string for pdftops
-options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
-% Convert to eps using pdftops
-[status, message] = pdftops(options);
-% Check for error
-if status
-    % Report error
-    if isempty(message)
-        error('Unable to generate eps. Check destination directory is writable.');
-    else
-        error(message);
+    % Construct the options string for pdftops
+    options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
+
+    % Convert to eps using pdftops
+    [status, message] = pdftops(options);
+
+    % Check for error
+    if status
+        % Report error
+        if isempty(message)
+            error('Unable to generate eps. Check destination directory is writable.');
+        else
+            error(message);
+        end
     end
+
+    % Fix the DSC error created by pdftops
+    fid = fopen(dest, 'r+');
+    if fid == -1
+        % Cannot open the file
+        return
+    end
+    fgetl(fid); % Get the first line
+    str = fgetl(fid); % Get the second line
+    if strcmp(str(1:min(13, end)), '% Produced by')
+        fseek(fid, -numel(str)-1, 'cof');
+        fwrite(fid, '%'); % Turn ' ' into '%'
+    end
+    fclose(fid);
 end
-% Fix the DSC error created by pdftops
-fid = fopen(dest, 'r+');
-if fid == -1
-    % Cannot open the file
-    return
-end
-fgetl(fid); % Get the first line
-str = fgetl(fid); % Get the second line
-if strcmp(str(1:min(13, end)), '% Produced by')
-    fseek(fid, -numel(str)-1, 'cof');
-    fwrite(fid, '%'); % Turn ' ' into '%'
-end
-fclose(fid);
-end
-
Index: /issm/trunk-jpl/externalpackages/export_fig/pdftops.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/pdftops.m	(revision 24459)
+++ /issm/trunk-jpl/externalpackages/export_fig/pdftops.m	(revision 24460)
@@ -12,6 +12,5 @@
 %
 % 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
+% installed on your system. You can download this from: http://xpdfreader.com
 %
 % IN:
@@ -31,4 +30,6 @@
 % 02/05/2016 - Search additional possible paths suggested by Jonas Stein (issue #147)
 % 03/05/2016 - Display the specific error message if pdftops fails for some reason (issue #148)
+% 22/09/2018 - Xpdf website changed to xpdfreader.com; improved popup logic
+% 03/02/2019 - Fixed one-off 'pdftops not found' error after install (Mac/Linux) (issue #266)
 
     % Call pdftops
@@ -69,5 +70,5 @@
     % Ask the user to enter the path
     errMsg1 = 'Pdftops not found. Please locate the program, or install xpdf-tools from ';
-    url1 = 'http://foolabs.com/xpdf';
+    url1 = 'http://xpdfreader.com/download.html'; %='http://foolabs.com/xpdf';
     fprintf(2, '%s\n', [errMsg1 '<a href="matlab:web(''-browser'',''' url1 ''');">' url1 '</a>']);
     errMsg1 = [errMsg1 url1];
@@ -83,5 +84,5 @@
     errMsg2 = [errMsg2 url1];
 
-    state = 0;
+    state = 1;
     while 1
         if state
@@ -95,4 +96,5 @@
             case 'Install pdftops'
                 web('-browser',url1);
+                state = 0;
             case 'Issue #137'
                 web('-browser',url2);
@@ -141,8 +143,9 @@
     % system returns good = 1 even when the command runs
     % Look for something distinct in the help text
-    good = ~isempty(strfind(message, 'PostScript'));
+    good = ~isempty(strfind(message, 'PostScript')); %#ok<STREMP>
 
     % Display the error message if the pdftops executable exists but fails for some reason
-    if ~good && exist(path_,'file')  % file exists but generates an error
+    % Note: on Mac/Linux, exist('pdftops','file') will always return 2 due to pdftops.m => check for '/','.' (issue #266)
+    if ~good && exist(path_,'file') && ~isempty(regexp(path_,'[/.]')) %#ok<RGXP1> % file exists but generates an error
         fprintf('Error running %s:\n', path_);
         fprintf(2,'%s\n\n',message);
Index: /issm/trunk-jpl/externalpackages/export_fig/print2array.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/print2array.m	(revision 24459)
+++ /issm/trunk-jpl/externalpackages/export_fig/print2array.m	(revision 24460)
@@ -51,4 +51,5 @@
 % 07/07/15: Fixed issue #83: use numeric handles in HG1
 % 11/12/16: Fixed cropping issue reported by Harry D.
+% 29/09/18: Fixed issue #254: error in print2array>read_tif_img
 %}
 
@@ -208,4 +209,5 @@
 % Function to create a TIF image of the figure and read it into an array
 function [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam)
+    A =  [];  % fix for issue #254
     err = false;
     ex = [];
Index: /issm/trunk-jpl/externalpackages/export_fig/print2eps.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/print2eps.m	(revision 24459)
+++ /issm/trunk-jpl/externalpackages/export_fig/print2eps.m	(revision 24460)
@@ -14,5 +14,5 @@
 % where these have been changed by MATLAB, for up to 11 different fonts.
 %
-%IN:
+% Inputs:
 %   filename - string containing the name (optionally including full or
 %              relative path) of the file the figure is to be saved as. A
@@ -26,4 +26,8 @@
 %       crop       - Cropping flag. Deafult: 0
 %       fontswap   - Whether to swap non-default fonts in figure. Default: true
+%       preserve_size - Whether to preserve the figure's PaperSize. Default: false
+%       font_space - Character used to separate font-name terms in the EPS output
+%                    e.g. "Courier New" => "Courier-New". Default: ''
+%                    (available only via the struct alternative)
 %       renderer   - Renderer used to generate bounding-box. Default: 'opengl'
 %                    (available only via the struct alternative)
@@ -89,4 +93,15 @@
 % 12/06/16: Improved the fix for issue #159 (in the previous commit)
 % 12/06/16: Fixed issue #158: transparent patch color in PDF/EPS
+% 18/09/17: Fixed issue #194: incorrect fonts in EPS/PDF output
+% 18/09/17: Fixed issue #195: relaxed too-tight cropping in EPS/PDF
+% 14/11/17: Workaround for issue #211: dashed/dotted lines in 3D axes appear solid
+% 15/11/17: Updated issue #211: only set SortMethod='ChildOrder' in HG2, and when it looks the same onscreen; support multiple figure axes
+% 18/11/17: Fixed issue #225: transparent/translucent dashed/dotted lines appear solid in EPS/PDF
+% 24/03/18: Fixed issue #239: black title meshes with temporary black background figure bgcolor, causing bad cropping
+% 21/03/19: Improvement for issue #258: missing fonts in output EPS/PDF (still *NOT* fully solved)
+% 21/03/19: Fixed issues #166,#251: Arial font is no longer replaced with Helvetica but rather treated as a non-standard user font
+% 14/05/19: Made Helvetica the top default font-swap, replacing Courier
+% 12/06/19: Issue #277: Enabled preservation of figure's PaperSize in output PDF/EPS file
+% 06/08/19: Issue #281: only fix patch/textbox color if it's not opaque
 %}
 
@@ -104,11 +119,19 @@
     crop_amounts = nan(1,4);  % auto-crop all 4 sides by default
     if isstruct(export_options)
-        try fontswap     = export_options.fontswap;     catch, fontswap = true;     end
-        try bb_crop      = export_options.crop;         catch, bb_crop = 0;         end
-        try crop_amounts = export_options.crop_amounts; catch,                      end
-        try bb_padding   = export_options.bb_padding;   catch, bb_padding = 0;      end
-        try renderer     = export_options.rendererStr;  catch, renderer = 'opengl'; end  % fix for issue #110
+        try preserve_size = export_options.preserve_size; catch, preserve_size = false; end
+        try fontswap      = export_options.fontswap;      catch, fontswap = true;       end
+        try font_space    = export_options.font_space;    catch, font_space = '';       end
+        font_space(2:end) = '';
+        try bb_crop       = export_options.crop;          catch, bb_crop = 0;           end
+        try crop_amounts  = export_options.crop_amounts;  catch,                        end
+        try bb_padding    = export_options.bb_padding;    catch, bb_padding = 0;        end
+        try renderer      = export_options.rendererStr;   catch, renderer = 'opengl';   end  % fix for issue #110
         if renderer(1)~='-',  renderer = ['-' renderer];  end
     else
+        if numel(export_options) > 3  % preserve_size
+            preserve_size = export_options(4);
+        else
+            preserve_size = false;
+        end
         if numel(export_options) > 2  % font-swapping
             fontswap = export_options(3);
@@ -127,4 +150,5 @@
         end
         renderer = '-opengl';
+        font_space = '';
     end
 
@@ -135,7 +159,8 @@
 
     % Set paper size
-    old_pos_mode = get(fig, 'PaperPositionMode');
+    old_pos_mode    = get(fig, 'PaperPositionMode');
     old_orientation = get(fig, 'PaperOrientation');
-    set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
+    old_paper_units = get(fig, 'PaperUnits');
+    set(fig, 'PaperPositionMode','auto', 'PaperOrientation','portrait', 'PaperUnits','points');
 
     % Find all the used fonts in the figure
@@ -155,7 +180,7 @@
         switch f
             case {'times', 'timesnewroman', 'times-roman'}
-                fontsl{a} = 'times-roman';
-            case {'arial', 'helvetica'}
-                fontsl{a} = 'helvetica';
+                fontsl{a} = 'times';
+            %case {'arial', 'helvetica'}  % issues #166, #251
+            %    fontsl{a} = 'helvetica';
             case {'newcenturyschoolbook', 'newcenturyschlbk'}
                 fontsl{a} = 'newcenturyschlbk';
@@ -167,6 +192,11 @@
     % Determine the font swap table
     if fontswap
-        matlab_fonts = {'Helvetica', 'Times-Roman', 'Palatino', 'Bookman', 'Helvetica-Narrow', 'Symbol', ...
-                        'AvantGarde', 'NewCenturySchlbk', 'Courier', 'ZapfChancery', 'ZapfDingbats'};
+        % Issue #258: Rearrange standard fonts list based on decending "problematicness"
+        % The issue is still *NOT* fully solved because I cannot figure out how to force
+        % the EPS postscript engine to look for the user's font on disk
+        % Also see: https://stat.ethz.ch/pipermail/r-help/2005-January/064374.html
+        matlab_fonts = {'Helvetica', 'Times', 'Courier', 'Symbol', 'ZapfDingbats', ...
+                        'Palatino', 'Bookman', 'ZapfChancery', 'AvantGarde', ...
+                        'NewCenturySchlbk', 'Helvetica-Narrow'};
         matlab_fontsl = lower(matlab_fonts);
         require_swap = find(~ismember(fontslu, matlab_fontsl));
@@ -211,5 +241,5 @@
         % Compute the order to revert fonts later, without the need of a loop
         [update, M] = unique(update(1:c));
-        [M, M] = sort(M);
+        [dummy, M] = sort(M); %#ok<ASGLU>
         update = reshape(update(M), 1, []);
     end
@@ -228,4 +258,34 @@
     % Set the line color slightly off white
     set(white_line_handles, 'Color', [1 1 1] - 0.00001);
+
+    % MATLAB bug fix (issue #211): dashed/dotted lines in 3D axes appear solid
+    % Note: this "may limit other functionality in plotting such as hidden line/surface removal"
+    % reference: Technical Support Case #02838114, https://mail.google.com/mail/u/0/#inbox/15fb7659f70e7bd8
+    hAxes = findall(fig, 'Type', 'axes');
+    if using_hg2 && ~isempty(hAxes)  % issue #211 presumably happens only in HG2, not HG1
+        try
+            % If there are any axes using SortMethod~='ChildOrder'
+            oldSortMethods = get(hAxes,{'SortMethod'});  % use {'SortMethod'} to ensure we get a cell array, even for single axes
+            if any(~strcmpi('ChildOrder',oldSortMethods))  % i.e., any oldSortMethods=='depth'
+                % Check if the axes look visually different onscreen when SortMethod='ChildOrder'
+                imgBefore = print2array(fig);
+                set(hAxes,'SortMethod','ChildOrder');
+                imgAfter  = print2array(fig);
+                if isequal(imgBefore, imgAfter)
+                    % They look the same, so use SortMethod='ChildOrder' when generating the EPS
+                else
+                    % They look different, so revert SortMethod and issue a warning message
+                    warning('YMA:export_fig:issue211', ...
+                            ['You seem to be using axes that have overlapping/hidden graphic elements. ' 10 ...
+                             'Setting axes.SortMethod=''ChildOrder'' may solve potential problems in EPS/PDF export. ' 10 ...
+                             'Additional info: https://github.com/altmany/export_fig/issues/211'])
+                    set(hAxes,{'SortMethod'},oldSortMethods);
+                end
+            end
+        catch err
+            % ignore
+            a=err;  %#ok<NASGU> % debug breakpoint
+        end
+    end
 
     % Workaround for issue #45: lines in image subplots are exported in invalid color
@@ -259,4 +319,7 @@
     print(fig, options{:}, name);
 
+    % Restore the original axes SortMethods (if updated)
+    try set(hAxes,{'SortMethod'},oldSortMethods); catch, end
+
     % Do post-processing on the eps file
     try
@@ -291,7 +354,13 @@
     end
 
+    % Bail out if EPS post-processing is not possible
+    if isempty(fstrm)
+        warning('Loading EPS file failed, so unable to perform post-processing. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
+        return
+    end
+
     % Fix for Matlab R2014b bug (issue #31): LineWidths<0.75 are not set in the EPS (default line width is used)
     try
-        if ~isempty(fstrm) && using_hg2(fig)
+        if using_hg2(fig)
             % Convert miter joins to line joins
             %fstrm = regexprep(fstrm, '\n10.0 ML\n', '\n1 LJ\n');
@@ -376,6 +445,13 @@
     set(white_line_handles, 'Color', [1 1 1]);
 
+    % Preserve the figure's PaperSize in the output file, if requested (issue #277)
+    if preserve_size
+        % https://stackoverflow.com/questions/19646329/postscript-document-size
+        paper_size = get(fig, 'PaperSize');  % in [points]
+        fstrm = sprintf('<< /PageSize [%d %d] >> setpagedevice\n%s', paper_size, fstrm);
+    end
+
     % Reset paper size
-    set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
+    set(fig, 'PaperPositionMode',old_pos_mode, 'PaperOrientation',old_orientation, 'PaperUnits',old_paper_units);
 
     % Reset the font names in the figure
@@ -386,15 +462,25 @@
     end
 
-    % Bail out if EPS post-processing is not possible
-    if isempty(fstrm)
-        warning('Loading EPS file failed, so unable to perform post-processing. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
-        return
-    end
-
     % Replace the font names
     if ~isempty(font_swap)
         for a = 1:size(font_swap, 2)
-            %fstrm = regexprep(fstrm, [font_swap{1,a} '-?[a-zA-Z]*\>'], font_swap{3,a}(~isspace(font_swap{3,a})));
-            fstrm = regexprep(fstrm, font_swap{2,a}, font_swap{3,a}(~isspace(font_swap{3,a})));
+            fontName = font_swap{3,a};
+            %fontName = fontName(~isspace(font_swap{3,a}));
+            if length(fontName) > 29
+                warning('YMA:export_fig:font_name','Font name ''%s'' is longer than 29 characters. This might cause problems in some EPS/PDF readers. Consider using a different font.',fontName);
+            end
+            if isempty(font_space)
+                fontName(fontName==' ') = '';
+            else
+                fontName(fontName==' ') = char(font_space);
+            end
+
+            % Replace all instances of the standard Matlab fonts with the original user's font names
+            %fstrm = regexprep(fstrm, [font_swap{1,a} '-?[a-zA-Z]*\>'], fontName);
+            %fstrm = regexprep(fstrm, [font_swap{2,a} '([ \n])'], [fontName '$1']);
+            %fstrm = regexprep(fstrm, font_swap{2,a}, fontName);  % also replace -Bold, -Italic, -BoldItalic
+
+            % Times-Roman's Bold/Italic fontnames don't include '-Roman'
+            fstrm = regexprep(fstrm, [font_swap{2,a} '(\-Roman)?'], fontName);
         end
     end
@@ -426,8 +512,28 @@
         pagebb_matlab = cell2mat(textscan(aa,'%f32%f32%f32%f32'));  % dimensions bb - STEP2
 
+        % 1b. Fix issue #239: black title meshes with temporary black background figure bgcolor, causing bad cropping
+        hTitles = [];
+        if isequal(get(fig,'Color'),'none')
+            hAxes = findall(fig,'type','axes');
+            for idx = 1 : numel(hAxes)
+                hAx = hAxes(idx);
+                try
+                    hTitle = hAx.Title;
+                    oldColor = hTitle.Color;
+                    if all(oldColor < 5*eps) || (ischar(oldColor) && lower(oldColor(1))=='k')
+                        hTitles(end+1) = hTitle; %#ok<AGROW>
+                        hTitle.Color = [0,0,.01];
+                    end
+                catch
+                end
+            end
+        end
+
         % 2. Create a bitmap image and use crop_borders to create the relative
         %    bb with respect to the PageBoundingBox
         [A, bcol] = print2array(fig, 1, renderer);
-        [aa, aa, aa, bb_rel] = crop_borders(A, bcol, bb_padding, crop_amounts);
+        [aa, aa, aa, bb_rel] = crop_borders(A, bcol, bb_padding, crop_amounts); %#ok<ASGLU>
+
+        try set(hTitles,'Color','k'); catch, end
 
         % 3. Calculate the new Bounding Box
@@ -437,5 +543,5 @@
         %          pagebb_matlab(1)+pagew*bb_rel(3) pagebb_matlab(2)+pageh*bb_rel(4)];
         bb_new = pagebb_matlab([1,2,1,2]) + [pagew,pageh,pagew,pageh].*bb_rel;  % clearer
-        bb_offset = (bb_new-bb_matlab) + [-1,-1,1,1];  % 1px margin so that cropping is not TOO tight
+        bb_offset = (bb_new-bb_matlab) + [-2,-2,2,2];  % 2px margin so that cropping is not TOO tight (issue #195)
 
         % Apply the bounding box padding
@@ -444,7 +550,7 @@
                 bb_padding = round((mean([bb_new(3)-bb_new(1) bb_new(4)-bb_new(2)])*bb_padding)/0.5)*0.5; % ADJUST BB_PADDING
             end
-            add_padding = @(n1, n2, n3, n4) sprintf(' %d', str2double({n1, n2, n3, n4}) + [-bb_padding -bb_padding bb_padding bb_padding] + bb_offset);
+            add_padding = @(n1, n2, n3, n4) sprintf(' %.0f', str2double({n1, n2, n3, n4}) + bb_offset + bb_padding*[-1,-1,1,1]); %#ok<NASGU>
         else
-            add_padding = @(n1, n2, n3, n4) sprintf(' %d', str2double({n1, n2, n3, n4}) + bb_offset); % fix small but noticeable bounding box shift
+            add_padding = @(n1, n2, n3, n4) sprintf(' %.0f', str2double({n1, n2, n3, n4}) + bb_offset); %#ok<NASGU> % fix small but noticeable bounding box shift
         end
         fstrm = regexprep(fstrm, '%%BoundingBox:[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)', '%%BoundingBox:${add_padding($1, $2, $3, $4)}');
@@ -478,9 +584,11 @@
                     propName = propNames{propIdx};
                     if strcmp(hObj.(propName).ColorType, 'truecoloralpha')
-                        nColors = length(StoredColors);
                         oldColor = hObj.(propName).ColorData;
-                        newColor = uint8([101; 102+floor(nColors/255); mod(nColors,255); 255]);
-                        StoredColors{end+1} = {hObj, propName, oldColor, newColor};
-                        hObj.(propName).ColorData = newColor;
+                        if numel(oldColor)>3 && oldColor(4)~=255  % issue #281: only fix patch/textbox color if it's not opaque
+                            nColors = length(StoredColors);
+                            newColor = uint8([101; 102+floor(nColors/255); mod(nColors,255); 255]);
+                            StoredColors{end+1} = {hObj, propName, oldColor, newColor}; %#ok<AGROW>
+                            hObj.(propName).ColorData = newColor;
+                        end
                     end
                 catch
@@ -508,11 +616,11 @@
                 %Find and replace the RGBA values within the EPS text fstrm
                 if strcmpi(propName,'Face')
-                    oldStr = sprintf(['\n' colorID ' RC\nN\n']);
-                    newStr = sprintf(['\n' origRGB ' RC\n' origAlpha ' .setopacityalpha true\nN\n']);
+                    oldStr = sprintf(['\n' colorID ' RC\n']);  % ...N\n (removed to fix issue #225)
+                    newStr = sprintf(['\n' origRGB ' RC\n' origAlpha ' .setopacityalpha true\n']);  % ...N\n
                 else  %'Edge'
-                    oldStr = sprintf(['\n' colorID ' RC\n1 LJ\n']);
+                    oldStr = sprintf(['\n' colorID ' RC\n']);  % ...1 LJ\n (removed to fix issue #225)
                     newStr = sprintf(['\n' origRGB ' RC\n' origAlpha ' .setopacityalpha true\n']);
                 end
-                foundFlags(objIdx) = ~isempty(strfind(fstrm, oldStr));
+                foundFlags(objIdx) = ~isempty(strfind(fstrm, oldStr)); %#ok<STREMP>
                 fstrm = strrep(fstrm, oldStr, newStr);
 
Index: /issm/trunk-jpl/externalpackages/export_fig/user_string.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/user_string.m	(revision 24459)
+++ /issm/trunk-jpl/externalpackages/export_fig/user_string.m	(revision 24460)
@@ -33,4 +33,5 @@
 %              errors. Thanks to Christian for pointing this out.
 % 29/05/2015 - Save file in prefdir if current folder is non-writable (issue #74)
+% 09/01/2018 - Fix issue #232: if the string looks like a file/folder path, ensure it actually exists
 
     if ~ischar(string_name)
@@ -102,4 +103,9 @@
         string = fgetl(fid);
         fclose(fid);
+
+        % Fix issue #232: if the string looks like a file/folder path, ensure it actually exists
+        if ~isempty(string) && any(string=='\' | string=='/') && ~exist(string) %#ok<EXIST>
+            string = '';
+        end
     end
 end
