Index: issm/trunk/externalpackages/export_fig/ImageSelection.java
===================================================================
--- issm/trunk/externalpackages/export_fig/ImageSelection.java	(revision 21341)
+++ issm/trunk/externalpackages/export_fig/ImageSelection.java	(revision 21341)
@@ -0,0 +1,38 @@
+/*
+ * Based on code snippet from
+ * http://java.sun.com/developer/technicalArticles/releases/data/
+ *
+ * Copyright © 2008, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms.
+ */
+
+import java.awt.image.BufferedImage;
+import java.awt.datatransfer.*;
+
+public class ImageSelection implements Transferable {
+    
+    private static final DataFlavor flavors[] =
+    {DataFlavor.imageFlavor};
+    
+    private BufferedImage image;
+    
+    public ImageSelection(BufferedImage image) {
+        this.image = image;
+    }
+    
+    // Transferable
+    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
+        if (flavor.equals(flavors[0]) == false) {
+            throw new UnsupportedFlavorException(flavor);
+        }
+        return image;
+    }
+    
+    public DataFlavor[] getTransferDataFlavors() {
+        return flavors;
+    }
+    
+    public boolean isDataFlavorSupported(DataFlavor
+    flavor) {
+        return flavor.equals(flavors[0]);
+    }
+}
Index: issm/trunk/externalpackages/export_fig/LICENSE
===================================================================
--- issm/trunk/externalpackages/export_fig/LICENSE	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/LICENSE	(revision 21341)
@@ -1,3 +1,3 @@
-Copyright (c) 2014, Oliver J. Woodford
+Copyright (c) 2014, Oliver J. Woodford, Yair M. Altman
 All rights reserved.
 
Index: issm/trunk/externalpackages/export_fig/README
===================================================================
--- issm/trunk/externalpackages/export_fig/README	(revision 21341)
+++ issm/trunk/externalpackages/export_fig/README	(revision 21341)
@@ -0,0 +1,17 @@
+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/externalpackages/export_fig/README.md
===================================================================
--- issm/trunk/externalpackages/export_fig/README.md	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/README.md	(revision 21341)
@@ -25,5 +25,5 @@
 |![](https://farm6.staticflickr.com/5616/15589249291_16e485c29a_o_d.png)|![](https://farm4.staticflickr.com/3944/15406302850_4d2e1c7afa_o_d.png)|![](https://farm6.staticflickr.com/5607/15568225476_8ce9bd5f6b_o_d.png)|
 
-Note that the size and background colour of test2.png (the output of export_fig) are the same as those of the on screen figure, in contrast to test.png. Of course, if you want want the figure background to be white (or any other colour) in the exported file then you can set this prior to exporting using:
+Note that the size and background colour of test2.png (the output of export_fig) are the same as those of the on screen figure, in contrast to test.png. Of course, if you want the figure background to be white (or any other colour) in the exported file then you can set this prior to exporting using:
 ```Matlab
 set(gcf, 'Color', 'w');
@@ -149,5 +149,5 @@
 **Cropping** - by default, export_fig crops its output to minimize the amount of empty space around the figure. If you'd prefer the figure to be uncropped, and instead have the same appearance (in terms of border width) as the on screen figure, then use the `-nocrop` option.  
   
-**Colourspace** - by default, export_fig generates files in the RGB [colourspace](http://en.wikipedia.org/wiki/Color_space). However, you can also export in greyscale or the CMYK colourspace, using the `-grey` (or `-gray`) and `-cmyk` options respectively. The CMYK option is useful for publishers who require documents in this colourspace, but the option is only supported for PDF, EPS and TIFF files.
+**Colourspace** - by default, export_fig generates files in the RGB [colourspace](https://en.wikipedia.org/wiki/Color_space). However, you can also export in greyscale or the CMYK colourspace, using the `-grey` (or `-gray`) and `-cmyk` options respectively. The CMYK option is useful for publishers who require documents in this colourspace, but the option is only supported for PDF, EPS and TIFF files.
 
 **Specifying a target directory** - you can get export_fig to save output files to any directory (for which you have write permission), simply by specifying the full or relative path in the filename. For example:
@@ -171,9 +171,9 @@
 **Specifying the figure/axes** - if you have mutiple figures open you can specify which figure to export using its handle:  
 ```Matlab
-export_fig(figure_handle, 'filename.fmt');
+export_fig(figure_handle, filename);
 ```
 Equally, if your figure contains several subplots then you can export just one of them by giving export_fig the handle to the relevant axes:
 ```Matlab
-export_fig(axes_handle, 'filename.fmt');
+export_fig(axes_handle, filename);
 ```
 
@@ -195,7 +195,12 @@
 **Appending to a file** - you can use the `-append` option to append the figure to the end of an image/document, if it already exists. This is supported for PDF and TIFF files only. Note that if you wish to append a lot of figures consecutively to a PDF, it can be more efficient to save all the figures to PDF separately then append them all in one go at the end (e.g. using [append_pdfs](http://www.mathworks.com/matlabcentral/fileexchange/31215-appendpdfs)).  
   
+**Output to clipboard** - you can use the `-clipboard` option to copy the specified figure or axes to the system clipboard, for easy paste into other documents (e.g., Word or PowerPoint). Note that the image is copied in bitmap (not vector) format.  
+  
 **Font size** - if you want to place an exported figure in a document with the font a particular size then you need to set the font to that size in the figure, and not resize the output of export_fig in the document. To avoid resizing, simply make sure that the on screen figure is the size you want the output to be in the document before exporting.  
   
-**Renderers** - MATLAB has three renderers for displaying and exporting figures: painters, OpenGL and ZBuffer. The different renderers have different [features](http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/f3-84337.html#f3-102410), so if you aren't happy with the result from one renderer try another. By default, vector formats (i.e. PDF and EPS outputs) use the painters renderer, while other formats use the OpenGL renderer. Non-default renderers can be selected by using one of these three export_fig input options: `-painters`, `-opengl`, `-zbuffer`.  
+**Renderers** - MATLAB has three renderers for displaying and exporting figures: painters, OpenGL and ZBuffer. The different renderers have different [features](http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/f3-84337.html#f3-102410), so if you aren't happy with the result from one renderer try another. By default, vector formats (i.e. PDF and EPS outputs) use the painters renderer, while other formats use the OpenGL renderer. Non-default renderers can be selected by using one of these three export_fig input options: `-painters`, `-opengl`, `-zbuffer`:  
+```Matlab
+export_fig test.png -painters
+```
   
 **Artifacts** - sometimes the output that you get from export_fig is not what you expected. If an output file contains artifacts that aren't in the on screen figure then make sure that the renderer used for rendering the figure on screen is the same as that used for exporting. To set the renderer used to display the figure, use:  
@@ -215,5 +220,5 @@
 
 **Undefined function errors** - If you download and run export_fig and get an error similar to this:  
-```Matlab
+```
 ??? Undefined function or method 'print2array' for input arguments of type 'double'.
 ```
@@ -221,11 +226,11 @@
   
 ### Known issues
-There are lots of problems with MATLAB's exporting functions, and unfortunately export_fig, which is simply a glorified wrapper for MATLAB's print function, doesn't solve all of them (yet?). Some of the problems I know about are:
-  
-**Fonts** - when using the painters renderer, MATLAB can only export a small number of fonts, details of which can be found [here](http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/f3-103191.html#f3-96545). Export_fig attempts to correct font names in the resulting EPS file (for upto a maximum of 11 different fonts in one figure), but this is not always guaranteed to work. In particular, the text positions will be affected. It also does not work for text blocks where the 'Interpreter' property is set to 'latex'.
-
-Also, when using the painters renderer, ghostscript will sometimes throw an error such as `Error: /undefined in /findfont`. This suggests that ghostscript could not find a definition file for one of your fonts. One possible fix for this is to make sure the file `EXPORT_FIG_PATH/.ignore/gs_font_path.txt` exists and contains a list of paths to the folder(s) containing the necessary font definitions (make sure they're TrueType definitions), separated by a semicolon.
-
-**RGB color data not yet supported in Painter's mode** - you will see this as a warning if you try to export a figure which contains patch objects whose face or vertex colors are specified as a an RGB colour, rather than an index into the colormap, using the painters renderer (the default renderer for vector output). This problem can arise if you use `pcolor`, for example. This is a problem with MATLAB's painters renderer, which also affects `print`; there is currently no fix available in export_fig (other than to export to bitmap). The suggested workaround is to avoid colouring patches using RGB. First, try to use colours in the figure's colourmap (instructions [here](http://www.mathworks.co.uk/support/solutions/en/data/1-6OTPQE/)) - change the colourmap, if necessary. If you are using `pcolor`, try using [uimagesc](http://www.mathworks.com/matlabcentral/fileexchange/11368) (on the file exchange) instead.  
+There are lots of problems with MATLAB's exporting functions, especially `print`. Export_fig is simply a glorified wrapper for MATLAB's `print` function, and doesn't solve all of its bugs (yet?). Some of the problems I know about are:
+  
+**Fonts** - when using the painters renderer, MATLAB can only export a small number of fonts, details of which can be found [here](http://www.mathworks.com/help/releases/R2014a/matlab/creating_plots/choosing-a-printer-driver.html#f3-96545). Export_fig attempts to correct font names in the resulting EPS file (up to a maximum of 11 different fonts in one figure), but this is not always guaranteed to work. In particular, the text positions will be affected. It also does not work for text blocks where the 'Interpreter' property is set to 'latex'.
+
+Also, when using the painters renderer, ghostscript will sometimes throw an error such as `Error: /undefined in /findfont`. This suggests that ghostscript could not find a definition file for one of your fonts. One possible fix for this is to make sure the file `EXPORT_FIG_PATH/.ignore/gs_font_path.txt` exists and contains a list of paths to the folder(s) containing the necessary font definitions (make sure that they are TrueType definitions!), separated by a semicolon.
+
+**RGB color data not yet supported in Painter's mode** - you will see this as a warning if you try to export a figure which contains patch objects whose face or vertex colors are specified as an RGB colour, rather than an index into the colormap, using the painters renderer (the default renderer for vector output). This problem can arise if you use `pcolor`, for example. This is a problem with MATLAB's painters renderer, which also affects `print`; there is currently no fix available in export_fig (other than to export to bitmap). The suggested workaround is to avoid colouring patches using RGB. First, try to use colours in the figure's colourmap (instructions [here](http://www.mathworks.co.uk/support/solutions/en/data/1-6OTPQE/)) - change the colourmap, if necessary. If you are using `pcolor`, try using [uimagesc](http://www.mathworks.com/matlabcentral/fileexchange/11368) (on the file exchange) instead.  
 
 **Dashed contour lines appear solid** - when using the painters renderer, MATLAB cannot generate dashed lines using the `contour` function (either on screen or in exported PDF and EPS files). Details can be found [here](http://www.mathworks.com/support/solutions/en/data/1-14PPHB/?solution=1-14PPHB).  
@@ -233,12 +238,13 @@
 **Text size** - when using the OpenGL or ZBuffer renderers, large text can be resized relative to the figure when exporting at non-screen-resolution (including using anti-alising at screen resolution). This is a feature of MATLAB's `print `function. In this case, try using the `-painters` option.  
   
-**Lighting and transparency** - when using the painters renderer, transparency and lighting effects are not supported. Sorry, but this is a feature of the renderer. To find out more about the capabilities of each rendering method, see [here](http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/f3-84337.html#f3-102410). You can still export transparent objects to vector format (SVG) using the excellent [plot2svg](http://www.mathworks.com/matlabcentral/fileexchange/7401) package, then convert this to PDF, for example using [Inkscape](http://inkscape.org/). However, it can't handle lighting.  
-  
-**Lines in patch objects** - when exporting patch objects to PDF using the painters renderer (default), sometimes the output can appear to have lines across the middle of rectangular patches; these lines are the colour of the background, as if there is a crack in the patch, allowing you to see through. This issue is a feature of the software used to display the PDF, rather than the PDF itself. Sometimes disabling anti-aliasing in this software can get rid of the lines.  
+**Lighting and transparency** - when using the painters renderer, transparency and lighting effects are not supported. Sorry, but this is an inherent feature of MATLAB's painters renderer. To find out more about the capabilities of each rendering method, see [here](http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/f3-84337.html#f3-102410). You can still export transparent objects to vector format (SVG) using the excellent [plot2svg](http://www.mathworks.com/matlabcentral/fileexchange/7401) package, then convert this to PDF, for example using [Inkscape](http://inkscape.org/). However, it can't handle lighting.  
+  
+**Lines in patch objects** - when exporting patch objects to PDF using the painters renderer (default), sometimes the output can appear to have lines across the middle of rectangular patches; these lines are the colour of the background, as if there is a crack in the patch, allowing you to see through. This appears to be due to bugs in MATLAB's internal vector rendering code. These lines can often be removed from the PDF using software such as [InkScape](https://inkscape.org). Sometimes disabling anti-aliasing in the PDF-reader software can get rid of the lines ([discussion](https://github.com/altmany/export_fig/issues/44)).  
   
 **Out of memory** - if you run into memory issues when using export_fig, some ways to get round this are:  
  1. Reduce the level of anti-aliasing.
- 2. Reduce the size of the on screen figure.
- 3. Reduce the resolution (dpi) the figure is exported at.  
+ 2. Reduce the size of the figure.
+ 3. Reduce the export resolution (dpi). 
+ 4. Change the renderer to painters or ZBuffer.  
   
 **Errors** - the other common type of errors people get with export_fig are OpenGL errors. This isn't a fault of export_fig, but either a bug in MATLAB's `print`, or your graphics driver getting itself into a state. Always make sure your graphics driver is up-to-date. If it still doesn't work, try using the ZBuffer renderer.  
@@ -249,5 +255,7 @@
 Secondly, if exporting to bitmap, do try all the renderers (i.e. try the options `-opengl`, `-zbuffer` and `-painters` separately), to see if one of them does produce an acceptable output, and if so, use that.
 
-If the figure looks correct on screen, but an error exists in the exported output (which cannot be solved using a different renderer) then please feel free to raise an [issue](https://github.com/ojwoodford/export_fig/issues). Please be sure to include the .fig file, the export_fig command you use, the output you get, and a description of what you expected. I can't promise anything, but if it's easy to fix I probably will do it. Often I will find that the error is due to a bug in MATLAB's print function, in which case I will suggest you submit it as a bug to TheMathWorks, and inform me of any fix they suggest. Also, if there's a feature you'd like that isn't supported please tell me what it is and I'll consider implementing it.
+If this still does not help, then ensure that you are using the latest version of export_fig, which is available [here](https://github.com/altmany/export_fig/archive/master.zip).  
+ 
+If the figure looks correct on screen, but an error exists in the exported output (which cannot be solved using a different renderer) then please feel free to raise an [issue](https://github.com/altmany/export_fig/issues). Please be sure to include the .fig file, the export_fig command you use, the output you get, and a description of what you expected. I can't promise anything, but if it's easy to fix I may indeed do it. Often I will find that the error is due to a bug in MATLAB's `print` function, in which case I will suggest you submit it as a bug to TheMathWorks, and inform me of any fix they suggest. Also, if there's a feature you'd like that isn't supported please tell me what it is and I'll consider implementing it.
 
 ### And finally...
@@ -255,5 +263,8 @@
 ![](https://farm4.staticflickr.com/3956/15591911455_b9008bd77e_o_d.jpg)
 
-If you've ever wondered what's going on in the icon on the export_fig download page (reproduced on the left), then this explanantion is for you. The icon is designed to demonstrate as many of export_fig's features as possible. Given a
-figure containing a translucent mesh (top right), export_fig can export to pdf (bottom centre), which allows the figure to be zoomed in without losing quality (because it's a vector graphic), but isn't able to reproduce the translucency, and also, depending on the viewer, creates small gaps between the patches, which are seen here as thin white lines. By contrast, when exporting to png (top left), translucency is preserved (see how the graphic below shows through), the figure is anti-aliased, but zooming in does not reveal more detail.
-
+If you've ever wondered what's going on in the logo on the export_fig download page (reproduced here), then this explanantion is for you. The logo is designed to demonstrate as many of export_fig's features as possible: 
+ 
+Given a figure containing a translucent mesh (top right), export_fig can export to pdf (bottom centre), which allows the figure to be zoomed-in without losing quality (because it's a vector graphic), but isn't able to reproduce the translucency. Also, depending on the PDF viewer program, small gaps appear between the patches, which are seen here as thin white lines. 
+ 
+By contrast, when exporting to png (top left), translucency is preserved (see how the graphic below shows through), and the figure is anti-aliased. However, zooming-in does not reveal more detail since png is a bitmap format. Also, lines appear less sharp than in the pdf output.
+
Index: issm/trunk/externalpackages/export_fig/append_pdfs.m
===================================================================
--- issm/trunk/externalpackages/export_fig/append_pdfs.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/append_pdfs.m	(revision 21341)
@@ -33,15 +33,38 @@
 % setting
 
+% 26/02/15: If temp dir is not writable, use the output folder for temp
+%           files when appending (Javier Paredes); sanity check of inputs
+
 function append_pdfs(varargin)
+
+if nargin < 2,  return;  end  % sanity check
+
 % Are we appending or creating a new file
 append = exist(varargin{1}, 'file') == 2;
-if append
-    output = [tempname '.pdf'];
-else
+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
-cmdfile = [tempname '.txt'];
+if isTempDirOk
+    cmdfile = [tempname '.txt'];
+else
+    cmdfile = fullfile(fpath,[fname '.txt']);
+end
 fh = fopen(cmdfile, 'w');
 fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
Index: issm/trunk/externalpackages/export_fig/copyfig.m
===================================================================
--- issm/trunk/externalpackages/export_fig/copyfig.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/copyfig.m	(revision 21341)
@@ -1,2 +1,3 @@
+function fh = copyfig(fh)
 %COPYFIG Create a copy of a figure, without changing the figure
 %
@@ -15,19 +16,36 @@
 % Copyright (C) Oliver Woodford 2012
 
-function fh = copyfig(fh)
-% Set the default
-if nargin == 0
-    fh = gcf;
+% 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)
+
+    % Set the default
+    if nargin == 0
+        fh = gcf;
+    end
+    % Is there a legend?
+    if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'))
+        % 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);
+        warning(oldWarn);
+    else
+        % copyobj will change the figure, so save and then load it instead
+        tmp_nam = [tempname '.fig'];
+        try
+            % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
+            fid = fopen(tmp_nam,'w');
+            fwrite(fid,1);
+            fclose(fid);
+            delete(tmp_nam);  % cleanup
+        catch
+            % Temp dir is not writable, so use the current folder
+            [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
+            fpath = pwd;
+            tmp_nam = fullfile(fpath,[fname fext]);
+        end
+        hgsave(fh, tmp_nam);
+        fh = hgload(tmp_nam);
+        delete(tmp_nam);
+    end
 end
-% Is there a legend?
-if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'))
-    % Safe to copy using copyobj
-    fh = copyobj(fh, 0);
-else
-    % copyobj will change the figure, so save and then load it instead
-    tmp_nam = [tempname '.fig'];
-    hgsave(fh, tmp_nam);
-    fh = hgload(tmp_nam);
-    delete(tmp_nam);
-end
-end
Index: issm/trunk/externalpackages/export_fig/crop_borders.m
===================================================================
--- issm/trunk/externalpackages/export_fig/crop_borders.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/crop_borders.m	(revision 21341)
@@ -1,81 +1,157 @@
+function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding, crop_amounts)
 %CROP_BORDERS Crop the borders of an image or stack of images
 %
-%   [B, v] = crop_borders(A, bcol, [padding])
+%   [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding])
 %
 %IN:
 %   A - HxWxCxN stack of images.
 %   bcol - Cx1 background colour vector.
-%   padding - scalar indicating how many pixels padding to have. Default: 0.
+%   padding - scalar indicating how much padding to have in relation to
+%             the cropped-image-size (0<=padding<=1). Default: 0
+%   crop_amounts - 4-element vector of crop amounts: [top,right,bottom,left]
+%             where NaN/Inf indicate auto-cropping, 0 means no cropping,
+%             and any other value mean cropping in pixel amounts.
 %
 %OUT:
 %   B - JxKxCxN cropped stack of images.
-%   v - 1x4 vector of start and end indices for first two dimensions, s.t.
-%       B = A(v(1):v(2),v(3):v(4),:,:).
+%   vA     - coordinates in A that contain the cropped image
+%   vB     - coordinates in B where the cropped version of A is placed
+%   bb_rel - relative bounding box (used for eps-cropping)
 
-function [A, v] = crop_borders(A, bcol, padding)
-if nargin < 3
-    padding = 0;
-end
-[h, w, c, n] = size(A);
-if isscalar(bcol)
-    bcol = bcol(ones(c, 1));
-end
-bail = false;
-for l = 1:w
-    for a = 1:c
-        if ~all(col(A(:,l,a,:)) == bcol(a))
-            bail = true;
-            break;
+%{
+% 06/03/15: Improved image cropping thanks to Oscar Hartogensis
+% 08/06/15: Fixed issue #76: case of transparent figure bgcolor
+% 21/02/16: Enabled specifying non-automated crop amounts
+% 04/04/16: Fix per Luiz Carvalho for old Matlab releases
+% 23/10/16: Fixed issue #175: there used to be a 1px minimal padding in case of crop, now removed
+%}
+
+    if nargin < 3
+        padding = 0;
+    end
+    if nargin < 4
+        crop_amounts = nan(1,4);  % =auto-cropping
+    end
+    crop_amounts(end+1:4) = NaN;  % fill missing values with NaN
+
+    [h, w, c, n] = size(A);
+    if isempty(bcol)  % case of transparent bgcolor
+        bcol = A(ceil(end/2),1,:,1);
+    end
+    if isscalar(bcol)
+        bcol = bcol(ones(c, 1));
+    end
+
+    % Crop margin from left
+    if ~isfinite(crop_amounts(4))
+        bail = false;
+        for l = 1:w
+            for a = 1:c
+                if ~all(col(A(:,l,a,:)) == bcol(a))
+                    bail = true;
+                    break;
+                end
+            end
+            if bail
+                break;
+            end
         end
+    else
+        l = 1 + abs(crop_amounts(4));
     end
-    if bail
-        break;
+
+    % Crop margin from right
+    if ~isfinite(crop_amounts(2))
+        bcol = A(ceil(end/2),w,:,1);
+        bail = false;
+        for r = w:-1:l
+            for a = 1:c
+                if ~all(col(A(:,r,a,:)) == bcol(a))
+                    bail = true;
+                    break;
+                end
+            end
+            if bail
+                break;
+            end
+        end
+    else
+        r = w - abs(crop_amounts(2));
     end
-end
-bcol = A(ceil(end/2),w,:,1);
-bail = false;
-for r = w:-1:l
-    for a = 1:c
-        if ~all(col(A(:,r,a,:)) == bcol(a))
-            bail = true;
-            break;
+
+    % Crop margin from top
+    if ~isfinite(crop_amounts(1))
+        bcol = A(1,ceil(end/2),:,1);
+        bail = false;
+        for t = 1:h
+            for a = 1:c
+                if ~all(col(A(t,:,a,:)) == bcol(a))
+                    bail = true;
+                    break;
+                end
+            end
+            if bail
+                break;
+            end
         end
+    else
+        t = 1 + abs(crop_amounts(1));
     end
-    if bail
-        break;
+
+    % Crop margin from bottom
+    bcol = A(h,ceil(end/2),:,1);
+    if ~isfinite(crop_amounts(3))
+        bail = false;
+        for b = h:-1:t
+            for a = 1:c
+                if ~all(col(A(b,:,a,:)) == bcol(a))
+                    bail = true;
+                    break;
+                end
+            end
+            if bail
+                break;
+            end
+        end
+    else
+        b = h - abs(crop_amounts(3));
     end
-end
-bcol = A(1,ceil(end/2),:,1);
-bail = false;
-for t = 1:h
-    for a = 1:c
-        if ~all(col(A(t,:,a,:)) == bcol(a))
-            bail = true;
-            break;
+
+    if padding == 0  % no padding
+        % Issue #175: there used to be a 1px minimal padding in case of crop, now removed
+        %{
+        if ~isequal([t b l r], [1 h 1 w]) % Check if we're actually croppping
+            padding = 1; % Leave one boundary pixel to avoid bleeding on resize
+            bcol(:) = nan;  % make the 1px padding transparent
         end
+        %}
+    elseif abs(padding) < 1  % pad value is a relative fraction of image size
+        padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING
+    else  % pad value is in units of 1/72" points
+        padding = round(padding);  % fix cases of non-integer pad value
     end
-    if bail
-        break;
+
+    if padding > 0  % extra padding
+        % Create an empty image, containing the background color, that has the
+        % cropped image size plus the padded border
+        B = repmat(bcol,[(b-t)+1+padding*2,(r-l)+1+padding*2,1,n]);  % Fix per Luiz Carvalho
+        % vA - coordinates in A that contain the cropped image
+        vA = [t b l r];
+        % vB - coordinates in B where the cropped version of A will be placed
+        vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding];
+        % Place the original image in the empty image
+        B(vB(1):vB(2), vB(3):vB(4), :, :) = A(vA(1):vA(2), vA(3):vA(4), :, :);
+        A = B;
+    else  % extra cropping
+        vA = [t-padding b+padding l-padding r+padding];
+        A = A(vA(1):vA(2), vA(3):vA(4), :, :);
+        vB = [NaN NaN NaN NaN];
     end
-end
-bcol = A(h,ceil(end/2),:,1);
-bail = false;
-for b = h:-1:t
-    for a = 1:c
-        if ~all(col(A(b,:,a,:)) == bcol(a))
-            bail = true;
-            break;
-        end
-    end
-    if bail
-        break;
-    end
-end
-% Crop the background, leaving one boundary pixel to avoid bleeding on resize
-v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)];
-A = A(v(1):v(2),v(3):v(4),:,:);
+
+    % For EPS cropping, determine the relative BoundingBox - bb_rel
+    bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h];
 end
 
 function A = col(A)
-A = A(:);
+    A = A(:);
 end
Index: issm/trunk/externalpackages/export_fig/eps2pdf.m
===================================================================
--- issm/trunk/externalpackages/export_fig/eps2pdf.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/eps2pdf.m	(revision 21341)
@@ -1,2 +1,3 @@
+function eps2pdf(source, dest, crop, append, gray, quality, gs_options)
 %EPS2PDF  Convert an eps file to pdf format using ghostscript
 %
@@ -7,4 +8,5 @@
 %   eps2pdf(source, dest, crop, append, gray)
 %   eps2pdf(source, dest, crop, append, gray, quality)
+%   eps2pdf(source, dest, crop, append, gray, quality, gs_options)
 %
 % This function converts an eps file to pdf format. The output can be
@@ -17,21 +19,23 @@
 % system. Ghostscript can be downloaded from: http://www.ghostscript.com
 %
-%IN:
-%   source - filename of the source eps file to convert. The filename is
-%            assumed to already have the extension ".eps".
-%   dest - filename of the destination pdf file. The filename is assumed to
-%          already have the extension ".pdf".
-%   crop - boolean indicating whether to crop the borders off the pdf.
-%          Default: true.
-%   append - boolean indicating whether the eps should be appended to the
-%            end of the pdf as a new page (if the pdf exists already).
-%            Default: false.
-%   gray - boolean indicating whether the output pdf should be grayscale or
-%          not. Default: false.
+% Inputs:
+%   source  - filename of the source eps file to convert. The filename is
+%             assumed to already have the extension ".eps".
+%   dest    - filename of the destination pdf file. The filename is assumed
+%             to already have the extension ".pdf".
+%   crop    - boolean indicating whether to crop the borders off the pdf.
+%             Default: true.
+%   append  - boolean indicating whether the eps should be appended to the
+%             end of the pdf as a new page (if the pdf exists already).
+%             Default: false.
+%   gray    - boolean indicating whether the output pdf should be grayscale
+%             or not. Default: false.
 %   quality - scalar indicating the level of image bitmap quality to
 %             output. A larger value gives a higher quality. quality > 100
 %             gives lossless output. Default: ghostscript prepress default.
+%   gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
+%                multiple options are needed, enclose in call array: {'-a','-b'}
 
-% Copyright (C) Oliver Woodford 2009-2011
+% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-
 
 % Suggestion of appending pdf files provided by Matt C at:
@@ -44,91 +48,142 @@
 
 % 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)
+% 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
+%           some /findfont errors according to James Rankin, FEX Comment 23/01/15)
+% 23/06/15: Added extra debug info in case of ghostscript error; code indentation
+% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)
+% 22/02/16: Bug fix from latest release of this file (workaround for issue #41)
 
-function eps2pdf(source, dest, crop, append, gray, quality)
-% 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();
-if ~isempty(fp)
-    options = [options ' -sFONTPATH="' fp '"'];
-end
-% Set the grayscale option
-if nargin > 4 && gray
-    options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
-end
-% Set the bitmap quality
-if nargin > 5 && ~isempty(quality)
-    options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
-    if quality > 100
-        options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
+    % 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();
+    if ~isempty(fp)
+        options = [options ' -sFONTPATH="' fp '"'];
+    end
+    % Set the grayscale option
+    if nargin > 4 && gray
+        options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
+    end
+    % Set the bitmap quality
+    if nargin > 5 && ~isempty(quality)
+        options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
+        if quality > 100
+            options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
+        else
+            options = [options ' -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
+    % Enable users to specify optional ghostscript options (issue #36)
+    if nargin > 6 && ~isempty(gs_options)
+        if iscell(gs_options)
+            gs_options = sprintf(' %s',gs_options{:});
+        elseif ~ischar(gs_options)
+            error('gs_options input argument must be a string or cell-array of strings');
+        else
+            gs_options = [' ' gs_options];
+        end
+        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;
+        try
+            % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
+            fid = fopen(tmp_nam,'w');
+            fwrite(fid,1);
+            fclose(fid);
+            delete(tmp_nam);
+        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
+        copyfile(dest, tmp_nam);
+        % Add the output file names
+        options = [options ' -f "' tmp_nam '" "' source '"'];
+        try
+            % Convert to pdf using ghostscript
+            [status, message] = ghostscript(options);
+        catch me
+            % Delete the intermediate file
+            delete(tmp_nam);
+            rethrow(me);
+        end
+        % Delete the intermediate file
+        delete(tmp_nam);
     else
-        options = [options ' -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
-% 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;
-    % Copy the file
-    copyfile(dest, tmp_nam);
-    % Add the output file names
-    options = [options ' -f "' tmp_nam '" "' source '"'];
-    try
+        % File doesn't exist or should be over-written
+        % Add the output file names
+        options = [options ' -f "' source '"'];
         % Convert to pdf using ghostscript
         [status, message] = ghostscript(options);
-    catch me
-        % Delete the intermediate file
-        delete(tmp_nam);
-        rethrow(me);
     end
-    % Delete the intermediate file
-    delete(tmp_nam);
-else
-    % File doesn't exist or should be over-written
-    % Add the output file names
-    options = [options ' -f "' source '"'];
-    % Convert to pdf using ghostscript
-    [status, message] = ghostscript(options);
-end
-% Check for error
-if status
-    % Report error
-    if isempty(message)
-        error('Unable to generate pdf. Check destination directory is writable.');
-    else
-        error(message);
+    % Check for error
+    if status
+        % Retry without the -sFONTPATH= option (this might solve some GS
+        % /findfont errors according to James Rankin, FEX Comment 23/01/15)
+        orig_options = options;
+        if ~isempty(fp)
+            options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
+            status = ghostscript(options);
+            if ~status, return; end  % hurray! (no error)
+        end
+        % Report error
+        if isempty(message)
+            error('Unable to generate pdf. Check destination directory is writable.');
+        elseif ~isempty(strfind(message,'/typecheck in /findfont'))
+            % Suggest a workaround for issue #41 (missing font path)
+            font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
+            fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name);
+            fpath = fileparts(mfilename('fullpath'));
+            gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');
+            fprintf(2, '  try to add the font''s folder to your %s file\n\n', gs_fonts_file);
+            error('export_fig error');
+        else
+            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);
+            end
+            fprintf(2, 'Ghostscript options: %s\n\n', orig_options);
+            error(message);
+        end
     end
-end
 end
 
 % Function to return (and create, where necessary) the font path
 function fp = font_path()
-fp = user_string('gs_font_path');
-if ~isempty(fp)
-    return
+    fp = user_string('gs_font_path');
+    if ~isempty(fp)
+        return
+    end
+    % Create the path
+    % Start with the default path
+    fp = getenv('GS_FONTPATH');
+    % Add on the typical directories for a given OS
+    if ispc
+        if ~isempty(fp)
+            fp = [fp ';'];
+        end
+        fp = [fp getenv('WINDIR') filesep 'Fonts'];
+    else
+        if ~isempty(fp)
+            fp = [fp ':'];
+        end
+        fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
+    end
+    user_string('gs_font_path', fp);
 end
-% Create the path
-% Start with the default path
-fp = getenv('GS_FONTPATH');
-% Add on the typical directories for a given OS
-if ispc
-    if ~isempty(fp)
-        fp = [fp ';'];
-    end
-    fp = [fp getenv('WINDIR') filesep 'Fonts'];
-else
-    if ~isempty(fp)
-        fp = [fp ':'];
-    end
-    fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
-end
-user_string('gs_font_path', fp);
-end
Index: issm/trunk/externalpackages/export_fig/export_fig.m
===================================================================
--- issm/trunk/externalpackages/export_fig/export_fig.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/export_fig.m	(revision 21341)
@@ -1,10 +1,12 @@
-%EXPORT_FIG  Exports figures suitable for publication
+function [imageData, alpha] = export_fig(varargin)
+%EXPORT_FIG  Exports figures in a publication-quality format
 %
 % Examples:
-%   im = export_fig
-%   [im alpha] = export_fig
+%   imageData = export_fig
+%   [imageData, alpha] = export_fig
 %   export_fig filename
 %   export_fig filename -format1 -format2
 %   export_fig ... -nocrop
+%   export_fig ... -c[<val>,<val>,<val>,<val>]
 %   export_fig ... -transparent
 %   export_fig ... -native
@@ -14,13 +16,18 @@
 %   export_fig ... -q<val>
 %   export_fig ... -p<val>
+%   export_fig ... -d<gs_option>
+%   export_fig ... -depsc
 %   export_fig ... -<renderer>
 %   export_fig ... -<colorspace>
 %   export_fig ... -append
 %   export_fig ... -bookmark
+%   export_fig ... -clipboard
+%   export_fig ... -update
+%   export_fig ... -nofontswap
 %   export_fig(..., handle)
 %
 % This function saves a figure or single axes to one or more vector and/or
-% bitmap file formats, and/or outputs a rasterized version to the
-% workspace, with the following properties:
+% bitmap file formats, and/or outputs a rasterized version to the workspace,
+% with the following properties:
 %   - Figure/axes reproduced as it appears on screen
 %   - Cropped borders (optional)
@@ -29,12 +36,12 @@
 %   - Anti-aliased graphics (bitmap formats)
 %   - Render images at native resolution (optional for bitmap formats)
-%   - Transparent background supported (pdf, eps, png)
-%   - Semi-transparent patch objects supported (png only)
+%   - 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)
 %   - 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 
-%   
+%   - Bitmap formats: png, tiff, jpg, bmp, export to workspace
+%
 % This function is especially suited to exporting figures for use in
 % publications and presentations, because of the high quality and
@@ -46,13 +53,12 @@
 % objects), use the -transparent option or set the figure 'Color' property
 % to 'none'. To make axes transparent set the axes 'Color' property to
-% 'none'. Pdf, eps and png are the only file formats to support a
-% transparent background, whilst the png format alone supports transparency
-% of patch objects.
+% 'none'. PDF, EPS, TIF & PNG are the only formats that support a transparent
+% 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. Whilst the default value (opengl for bitmaps,
-% painters for vector formats) generally gives good results, if you aren't
-% satisfied then try another renderer.  Notes: 1) For vector formats (eps,
-% pdf), only painters generates vector graphics. 2) For bitmaps, only
+% 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
@@ -60,5 +66,5 @@
 % using painters.
 %
-% When exporting to vector format (pdf & eps) and bitmap format using the
+% When exporting to vector format (PDF & EPS) and bitmap format using the
 % painters renderer, this function requires that ghostscript is installed
 % on your system. You can download this from:
@@ -68,5 +74,5 @@
 %   http://www.foolabs.com/xpdf
 %
-%IN:
+% Inputs:
 %   filename - string containing the name (optionally including full or
 %              relative path) of the file the figure is to be saved as. If
@@ -83,9 +89,13 @@
 %   -nocrop - option indicating that the borders of the output are not to
 %             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 and eps output only).
+%                  made transparent (png, pdf, tif and eps output only).
 %   -m<val> - option where val indicates the factor to magnify the
 %             on-screen figure pixel dimensions by when generating bitmap
-%             outputs. Default: '-m1'.
+%             outputs (does not affect vector formats). Default: '-m1'.
 %   -r<val> - option val indicates the resolution (in pixels per inch) to
 %             export bitmap and vector outputs at, keeping the dimensions
@@ -106,7 +116,8 @@
 %                        use for bitmap outputs. '-a1' means no anti-
 %                        aliasing; '-a4' is the maximum amount (default).
-%   -<renderer> - option to force a particular renderer (painters, opengl
-%                 or zbuffer) to be used over the default: opengl for
-%                 bitmaps; painters for vector formats.
+%   -<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.
 %   -<colorspace> - option indicating which colorspace color figures should
 %                   be saved in: RGB (default), CMYK or gray. CMYK is only
@@ -119,7 +130,11 @@
 %             sometimes give a smaller file size than the default lossy
 %             compression, depending on the type of images.
-%   -p<val> - option to add a border of width val to eps and pdf files,
-%             where val is in units of the intermediate eps file. Default:
-%             0 (i.e. no padding).
+%   -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
+%             size (i.e. p=0.01 adds a 1% border). For EPS & PDF formats,
+%             val can also be integer in units of 1/72" points (abs(val)>1).
+%             val can be positive (padding) or negative (extra cropping).
+%             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
@@ -127,19 +142,31 @@
 %   -bookmark - option to indicate that a bookmark with the name of the
 %               figure is to be created in the output file (pdf only).
-%   handle - The handle of the figure, axes or uipanels (can be an array of
-%            handles, but the objects must be in the same figure) to be
-%            saved. Default: gcf.
+%   -clipboard - option to save output as an image on the system 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+).
+%   -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
+%             such as discolored subplot lines on images (vector formats only).
+%   -update - option to download and install the latest version of export_fig
+%   -nofontswap - option to avoid font swapping. Font swapping is automatically
+%             done in vector formats (only): 11 standard Matlab fonts are
+%             replaced by the original figure fonts. This option prevents this.
+%   handle -  The handle of the figure, axes or uipanels (can be an array of
+%             handles, but the objects must be in the same figure) to be
+%             saved. Default: gcf.
 %
-%OUT:
-%   im - MxNxC uint8 image array of the figure.
-%   alpha - MxN single array of alphamatte values in range [0,1], for the
-%           case when the background is transparent.
+% Outputs:
+%   imageData - MxNxC uint8 image array of the exported image.
+%   alpha     - MxN single array of alphamatte values in the range [0,1],
+%               for the case when the background is transparent.
 %
 %   Some helpful examples and tips can be found at:
-%      https://github.com/ojwoodford/export_fig
+%      https://github.com/altmany/export_fig
 %
-%   See also PRINT, SAVEAS.
-
-% Copyright (C) Oliver Woodford 2008-2014
+%   See also PRINT, SAVEAS, ScreenCapture (on the Matlab File Exchange)
+
+%{
+% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
 
 % The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG
@@ -162,638 +189,1094 @@
 % Thanks to Tammy Threadgill for reporting a bug where an axes is not
 % isolated from gui objects.
-
+%}
+%{
 % 23/02/12: Ensure that axes limits don't change during printing
-% 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for
-%           reporting it).
-% 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling
-%           bookmarking of figures in pdf files.
-% 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep
-%           tick marks fixed.
-% 12/12/12: Add support for isolating uipanels. Thanks to michael for
-%           suggesting it.
-% 25/09/13: Add support for changing resolution in vector formats. Thanks
-%           to Jan Jaap Meijer for suggesting it.
-% 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner
-%           for suggesting it.
-
-function [im, alpha] = export_fig(varargin)
-% Make sure the figure is rendered correctly _now_ so that properties like
-% axes limits are up-to-date.
-drawnow;
-% Parse the input arguments
-[fig, options] = parse_args(nargout, varargin{:});
-% Isolate the subplot, if it is one
-cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'}));
-if cls
-    % Given handles of one or more axes, so isolate them from the rest
-    fig = isolate_axes(fig);
-else
-    % Check we have a figure
-    if ~isequal(get(fig, 'Type'), 'figure');
-        error('Handle must be that of a figure, axes or uipanel');
-    end
-    % Get the old InvertHardcopy mode
-    old_mode = get(fig, 'InvertHardcopy');
+% 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for reporting it).
+% 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling bookmarking of figures in pdf files.
+% 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep tick marks fixed.
+% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it.
+% 25/09/13: Add support for changing resolution in vector formats. Thanks to Jan Jaap Meijer for suggesting it.
+% 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner for suggesting it.
+% 24/02/15: Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual'
+% 25/02/15: Fix issue #4 (using HG2 on R2014a and earlier)
+% 25/02/15: Fix issue #21 (bold TeX axes labels/titles in R2014b)
+% 26/02/15: If temp dir is not writable, use the user-specified folder for temporary EPS/PDF files (Javier Paredes)
+% 27/02/15: Modified repository URL from github.com/ojwoodford to /altmany
+%           Indented main function
+%           Added top-level try-catch block to display useful workarounds
+% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
+% 06/03/15: Improved image padding & cropping thanks to Oscar Hartogensis
+% 26/03/15: Fixed issue #49 (bug with transparent grayscale images); fixed out-of-memory issue
+% 26/03/15: Fixed issue #42: non-normalized annotations on HG1
+% 26/03/15: Fixed issue #46: Ghostscript crash if figure units <> pixels
+% 27/03/15: Fixed issue #39: bad export of transparent annotations/patches
+% 28/03/15: Fixed issue #50: error on some Matlab versions with the fix for issue #42
+% 29/03/15: Fixed issue #33: bugs in Matlab's print() function with -cmyk
+% 29/03/15: Improved processing of input args (accept space between param name & value, related to issue #51)
+% 30/03/15: When exporting *.fig files, then saveas *.fig if figure is open, otherwise export the specified fig file
+% 30/03/15: Fixed edge case bug introduced yesterday (commit #ae1755bd2e11dc4e99b95a7681f6e211b3fa9358)
+% 09/04/15: Consolidated header comment sections; initialize output vars only if requested (nargout>0)
+% 14/04/15: Workaround for issue #45: lines in image subplots are exported in invalid color
+% 15/04/15: Fixed edge-case in parsing input parameters; fixed help section to show the -depsc option (issue #45)
+% 21/04/15: Bug fix: Ghostscript croaks on % chars in output PDF file (reported by Sven on FEX page, 15-Jul-2014)
+% 22/04/15: Bug fix: Pdftops croaks on relative paths (reported by Tintin Milou on FEX page, 19-Jan-2015)
+% 04/05/15: Merged fix #63 (Kevin Mattheus Moerman): prevent tick-label changes during export
+% 07/05/15: Partial fix for issue #65: PDF export used painters rather than opengl renderer (thanks Nguyenr)
+% 08/05/15: Fixed issue #65: bad PDF append since commit #e9f3cdf 21/04/15 (thanks Robert Nguyen)
+% 12/05/15: Fixed issue #67: exponent labels cropped in export, since fix #63 (04/05/15)
+% 28/05/15: Fixed issue #69: set non-bold label font only if the string contains symbols (\beta etc.), followup to issue #21
+% 29/05/15: Added informative error message in case user requested SVG output (issue #72)
+% 09/06/15: Fixed issue #58: -transparent removed anti-aliasing when exporting to PNG
+% 19/06/15: Added -update option to download and install the latest version of export_fig
+% 07/07/15: Added -nofontswap option to avoid font-swapping in EPS/PDF
+% 16/07/15: Fixed problem with anti-aliasing on old Matlab releases
+% 11/09/15: Fixed issue #103: magnification must never become negative; also fixed reported error msg in parsing input params
+% 26/09/15: Alert if trying to export transparent patches/areas to non-PNG outputs (issue #108)
+% 04/10/15: Do not suggest workarounds for certain errors that have already been handled previously
+% 01/11/15: Fixed issue #112: use same renderer in print2eps as export_fig (thanks to Jesús Pestana Puerta)
+% 10/11/15: Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX
+% 19/11/15: Fixed clipboard export in R2015b (thanks to Dan K via FEX)
+% 21/02/16: Added -c option for indicating specific crop amounts (idea by Cedric Noordam on FEX)
+% 08/05/16: Added message about possible error reason when groot.Units~=pixels (issue #149)
+% 17/05/16: Fixed case of image YData containing more than 2 elements (issue #151)
+% 08/08/16: Enabled exporting transparency to TIF, in addition to PNG/PDF (issue #168)
+%}
+
+    if nargout
+        [imageData, alpha] = deal([]);
+    end
+    hadError = false;
+    displaySuggestedWorkarounds = true;
+
+    % Ensure the figure is rendered correctly _now_ so that properties like axes limits are up-to-date
+    drawnow;
+    pause(0.05);  % this solves timing issues with Java Swing's EDT (http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem)
+
+    % Parse the input arguments
+    fig = get(0, 'CurrentFigure');
+    [fig, options] = parse_args(nargout, fig, varargin{:});
+
+    % Ensure that we have a figure handle
+    if isequal(fig,-1)
+        return;  % silent bail-out
+    elseif isempty(fig)
+        error('No figure found');
+    end
+
+    % Isolate the subplot, if it is one
+    cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'}));
+    if cls
+        % Given handles of one or more axes, so isolate them from the rest
+        fig = isolate_axes(fig);
+    else
+        % Check we have a figure
+        if ~isequal(get(fig, 'Type'), 'figure');
+            error('Handle must be that of a figure, axes or uipanel');
+        end
+        % Get the old InvertHardcopy mode
+        old_mode = get(fig, 'InvertHardcopy');
+    end
+
+    % Hack the font units where necessary (due to a font rendering bug in print?).
+    % This may not work perfectly in all cases.
+    % Also it can change the figure layout if reverted, so use a copy.
+    magnify = options.magnify * options.aa_factor;
+    if isbitmap(options) && magnify ~= 1
+        fontu = findall(fig, 'FontUnits', 'normalized');
+        if ~isempty(fontu)
+            % Some normalized font units found
+            if ~cls
+                fig = copyfig(fig);
+                set(fig, 'Visible', 'off');
+                fontu = findall(fig, 'FontUnits', 'normalized');
+                cls = true;
+            end
+            set(fontu, 'FontUnits', 'points');
+        end
+    end
+
+    try
+        % MATLAB "feature": axes limits and tick marks can change when printing
+        Hlims = findall(fig, 'Type', 'axes');
+        if ~cls
+            % Record the old axes limit and tick modes
+            Xlims = make_cell(get(Hlims, 'XLimMode'));
+            Ylims = make_cell(get(Hlims, 'YLimMode'));
+            Zlims = make_cell(get(Hlims, 'ZLimMode'));
+            Xtick = make_cell(get(Hlims, 'XTickMode'));
+            Ytick = make_cell(get(Hlims, 'YTickMode'));
+            Ztick = make_cell(get(Hlims, 'ZTickMode'));
+            Xlabel = make_cell(get(Hlims, 'XTickLabelMode')); 
+            Ylabel = make_cell(get(Hlims, 'YTickLabelMode')); 
+            Zlabel = make_cell(get(Hlims, 'ZTickLabelMode')); 
+        end
+
+        % Set all axes limit and tick modes to manual, so the limits and ticks can't change
+        % Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual'
+        set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual');
+        set_tick_mode(Hlims, 'X');
+        set_tick_mode(Hlims, 'Y');
+        if ~using_hg2(fig)
+            set(Hlims,'ZLimMode', 'manual');
+            set_tick_mode(Hlims, 'Z');
+        end
+    catch
+        % ignore - fix issue #4 (using HG2 on R2014a and earlier)
+    end
+
+    % Fix issue #21 (bold TeX axes labels/titles in R2014b when exporting to EPS/PDF)
+    try
+        if using_hg2(fig) && isvector(options)
+            % 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');
+        end
+    catch
+        % ignore
+    end
+
+    % Fix issue #42: non-normalized annotations on HG1 (internal Matlab bug)
+    annotationHandles = [];
+    try
+        if ~using_hg2(fig)
+            annotationHandles = findall(fig,'Type','hggroup','-and','-property','Units','-and','-not','Units','norm');
+            try  % suggested by Jesús Pestana Puerta (jespestana) 30/9/2015
+                originalUnits = get(annotationHandles,'Units');
+                set(annotationHandles,'Units','norm');
+            catch
+            end
+        end
+    catch
+        % should never happen, but ignore in any case - issue #50
+    end
+
+    % Fix issue #46: Ghostscript crash if figure units <> pixels
+    oldFigUnits = get(fig,'Units');
+    set(fig,'Units','pixels');
+
+    % Set to print exactly what is there
+    set(fig, 'InvertHardcopy', 'off');
+    % Set the renderer
+    switch options.renderer
+        case 1
+            renderer = '-opengl';
+        case 2
+            renderer = '-zbuffer';
+        case 3
+            renderer = '-painters';
+        otherwise
+            renderer = '-opengl'; % Default for bitmaps
+    end
+
+    % Handle transparent patches
+    hasTransparency = ~isempty(findall(fig,'-property','FaceAlpha','-and','-not','FaceAlpha',1));
+    hasPatches      = ~isempty(findall(fig,'type','patch'));
+    if hasTransparency
+        % Alert if trying to export transparent patches/areas to non-supported outputs (issue #108)
+        % http://www.mathworks.com/matlabcentral/answers/265265-can-export_fig-or-else-draw-vector-graphics-with-transparent-surfaces
+        % TODO - use transparency when exporting to PDF by not passing via print2eps
+        msg = 'export_fig currently supports transparent patches/areas only in PNG output. ';
+        if options.pdf
+            warning('export_fig:transparency', '%s\nTo export transparent patches/areas to PDF, use the print command:\n print(gcf, ''-dpdf'', ''%s.pdf'');', msg, options.name);
+        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
+    end
+
+    try
+        % Do the bitmap formats first
+        if isbitmap(options)
+            if abs(options.bb_padding) > 1
+                displaySuggestedWorkarounds = false;
+                error('For bitmap output (png,jpg,tif,bmp) the padding value (-p) must be between -1<p<1')
+            end
+            % Get the background colour
+            if options.transparent && (options.png || options.alpha)
+                % Get out an alpha channel
+                % MATLAB "feature": black colorbar axes can change to white and vice versa!
+                hCB = findall(fig, 'Type','axes', 'Tag','Colorbar');
+                if isempty(hCB)
+                    yCol = [];
+                    xCol = [];
+                else
+                    yCol = get(hCB, 'YColor');
+                    xCol = get(hCB, 'XColor');
+                    if iscell(yCol)
+                        yCol = cell2mat(yCol);
+                        xCol = cell2mat(xCol);
+                    end
+                    yCol = sum(yCol, 2);
+                    xCol = sum(xCol, 2);
+                end
+                % MATLAB "feature": apparently figure size can change when changing
+                % colour in -nodisplay mode
+                pos = get(fig, 'Position');
+                % Set the background colour to black, and set size in case it was
+                % changed internally
+                tcol = get(fig, 'Color');
+                set(fig, 'Color', 'k', 'Position', pos);
+                % Correct the colorbar axes colours
+                set(hCB(yCol==0), 'YColor', [0 0 0]);
+                set(hCB(xCol==0), 'XColor', [0 0 0]);
+
+                % The following code might cause out-of-memory errors
+                try
+                    % Print large version to array
+                    B = print2array(fig, magnify, renderer);
+                    % Downscale the image
+                    B = downsize(single(B), options.aa_factor);
+                catch
+                    % This is more conservative in memory, but kills transparency (issue #58)
+                    B = single(print2array(fig, magnify/options.aa_factor, renderer));
+                end
+
+                % Set background to white (and set size)
+                set(fig, 'Color', 'w', 'Position', pos);
+                % Correct the colorbar axes colours
+                set(hCB(yCol==3), 'YColor', [1 1 1]);
+                set(hCB(xCol==3), 'XColor', [1 1 1]);
+
+                % The following code might cause out-of-memory errors
+                try
+                    % Print large version to array
+                    A = print2array(fig, magnify, renderer);
+                    % Downscale the image
+                    A = downsize(single(A), options.aa_factor);
+                catch
+                    % This is more conservative in memory, but kills transparency (issue #58)
+                    A = single(print2array(fig, magnify/options.aa_factor, renderer));
+                end
+
+                % Set the background colour (and size) back to normal
+                set(fig, 'Color', tcol, 'Position', pos);
+                % Compute the alpha map
+                alpha = round(sum(B - A, 3)) / (255 * 3) + 1;
+                A = alpha;
+                A(A==0) = 1;
+                A = B ./ A(:,:,[1 1 1]);
+                clear B
+                % Convert to greyscale
+                if options.colourspace == 2
+                    A = rgb2grey(A);
+                end
+                A = uint8(A);
+                % Crop the background
+                if options.crop
+                    %[alpha, v] = crop_borders(alpha, 0, 1, options.crop_amounts);
+                    %A = A(v(1):v(2),v(3):v(4),:);
+                    [alpha, vA, vB] = crop_borders(alpha, 0, options.bb_padding, options.crop_amounts);
+                    if ~any(isnan(vB)) % positive padding
+                        B = repmat(uint8(zeros(1,1,size(A,3))),size(alpha));
+                        B(vB(1):vB(2), vB(3):vB(4), :) = A(vA(1):vA(2), vA(3):vA(4), :); % ADDED BY OH
+                        A = B;
+                    else  % negative padding
+                        A = A(vA(1):vA(2), vA(3):vA(4), :);
+                    end
+                end
+                if options.png
+                    % Compute the resolution
+                    res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
+                    % Save the png
+                    imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
+                    % Clear the png bit
+                    options.png = false;
+                end
+                % Return only one channel for greyscale
+                if isbitmap(options)
+                    A = check_greyscale(A);
+                end
+                if options.alpha
+                    % Store the image
+                    imageData = A;
+                    % Clear the alpha bit
+                    options.alpha = false;
+                end
+                % Get the non-alpha image
+                if isbitmap(options)
+                    alph = alpha(:,:,ones(1, size(A, 3)));
+                    A = uint8(single(A) .* alph + 255 * (1 - alph));
+                    clear alph
+                end
+                if options.im
+                    % Store the new image
+                    imageData = A;
+                end
+            else
+                % Print large version to array
+                if options.transparent
+                    % MATLAB "feature": apparently figure size can change when changing
+                    % colour in -nodisplay mode
+                    pos = get(fig, 'Position');
+                    tcol = get(fig, 'Color');
+                    set(fig, 'Color', 'w', 'Position', pos);
+                    A = print2array(fig, magnify, renderer);
+                    set(fig, 'Color', tcol, 'Position', pos);
+                    tcol = 255;
+                else
+                    [A, tcol] = print2array(fig, magnify, renderer);
+                end
+                % Crop the background
+                if options.crop
+                    A = crop_borders(A, tcol, options.bb_padding, options.crop_amounts);
+                end
+                % Downscale the image
+                A = downsize(A, options.aa_factor);
+                if options.colourspace == 2
+                    % Convert to greyscale
+                    A = rgb2grey(A);
+                else
+                    % Return only one channel for greyscale
+                    A = check_greyscale(A);
+                end
+                % Outputs
+                if options.im
+                    imageData = A;
+                end
+                if options.alpha
+                    imageData = A;
+                    alpha = zeros(size(A, 1), size(A, 2), 'single');
+                end
+            end
+            % Save the images
+            if options.png
+                res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
+                imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
+            end
+            if options.bmp
+                imwrite(A, [options.name '.bmp']);
+            end
+            % Save jpeg with given quality
+            if options.jpg
+                quality = options.quality;
+                if isempty(quality)
+                    quality = 95;
+                end
+                if quality > 100
+                    imwrite(A, [options.name '.jpg'], 'Mode', 'lossless');
+                else
+                    imwrite(A, [options.name '.jpg'], 'Quality', quality);
+                end
+            end
+            % Save tif images in cmyk if wanted (and possible)
+            if options.tif
+                if options.colourspace == 1 && size(A, 3) == 3
+                    A = double(255 - A);
+                    K = min(A, [], 3);
+                    K_ = 255 ./ max(255 - K, 1);
+                    C = (A(:,:,1) - K) .* K_;
+                    M = (A(:,:,2) - K) .* K_;
+                    Y = (A(:,:,3) - K) .* K_;
+                    A = uint8(cat(3, C, M, Y, K));
+                    clear C M Y K K_
+                end
+                append_mode = {'overwrite', 'append'};
+                imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1});
+            end
+        end
+
+        % Now do the vector formats
+        if isvector(options)
+            % Set the default renderer to painters
+            if ~options.renderer
+                if hasTransparency || hasPatches
+                    % This is *MUCH* slower, but more accurate for patches and transparent annotations (issue #39)
+                    renderer = '-painters';
+                else
+                    renderer = '-painters';
+                end
+            end
+            options.rendererStr = renderer;  % fix for issue #112
+            % Generate some filenames
+            tmp_nam = [tempname '.eps'];
+            try
+                % Ensure that the temp dir is writable (Javier Paredes 30/1/15)
+                fid = fopen(tmp_nam,'w');
+                fwrite(fid,1);
+                fclose(fid);
+                delete(tmp_nam);
+                isTempDirOk = true;
+            catch
+                % Temp dir is not writable, so use the user-specified folder
+                [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
+                fpath = fileparts(options.name);
+                tmp_nam = fullfile(fpath,[fname fext]);
+                isTempDirOk = false;
+            end
+            if isTempDirOk
+                pdf_nam_tmp = [tempname '.pdf'];
+            else
+                pdf_nam_tmp = fullfile(fpath,[fname '.pdf']);
+            end
+            if options.pdf
+                pdf_nam = [options.name '.pdf'];
+                try copyfile(pdf_nam, pdf_nam_tmp, 'f'); catch, end  % fix for issue #65
+            else
+                pdf_nam = pdf_nam_tmp;
+            end
+            % Generate the options for print
+            p2eArgs = {renderer, sprintf('-r%d', options.resolution)};
+            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';
+            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';
+            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';
+            end
+            try
+                % Generate an eps
+                print2eps(tmp_nam, fig, options, p2eArgs{:});
+                % Remove the background, if desired
+                if options.transparent && ~isequal(get(fig, 'Color'), 'none')
+                    eps_remove_background(tmp_nam, 1 + using_hg2(fig));
+                end
+                % Fix colorspace to CMYK, if requested (workaround for issue #33)
+                if options.colourspace == 1  % CMYK
+                    % Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option
+                    change_rgb_to_cmyk(tmp_nam);
+                end
+                % Add a bookmark to the PDF if desired
+                if options.bookmark
+                    fig_nam = get(fig, 'Name');
+                    if isempty(fig_nam)
+                        warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.');
+                    end
+                    add_bookmark(tmp_nam, fig_nam);
+                end
+                % Generate a pdf
+                eps2pdf(tmp_nam, pdf_nam_tmp, 1, options.append, options.colourspace==2, options.quality, options.gs_options);
+                % Ghostscript croaks on % chars in the output PDF file, so use tempname and then rename the file
+                try movefile(pdf_nam_tmp, pdf_nam, 'f'); catch, end
+            catch ex
+                % Delete the eps
+                delete(tmp_nam);
+                rethrow(ex);
+            end
+            % Delete the eps
+            delete(tmp_nam);
+            if options.eps
+                try
+                    % Generate an eps from the pdf
+                    % since pdftops can't handle relative paths (e.g., '..\'), use a temp file
+                    eps_nam_tmp = strrep(pdf_nam_tmp,'.pdf','.eps');
+                    pdf2eps(pdf_nam, eps_nam_tmp);
+                    movefile(eps_nam_tmp,  [options.name '.eps'], 'f');
+                catch ex
+                    if ~options.pdf
+                        % Delete the pdf
+                        delete(pdf_nam);
+                    end
+                    try delete(eps_nam_tmp); catch, end
+                    rethrow(ex);
+                end
+                if ~options.pdf
+                    % Delete the pdf
+                    delete(pdf_nam);
+                end
+            end
+        end
+
+        % Revert the figure or close it (if requested)
+        if cls || options.closeFig
+            % Close the created figure
+            close(fig);
+        else
+            % Reset the hardcopy mode
+            set(fig, 'InvertHardcopy', old_mode);
+            % Reset the axes limit and tick modes
+            for a = 1:numel(Hlims)
+                try
+                    set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a},... 
+                                  'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a},...
+                                  'XTickLabelMode', Xlabel{a}, 'YTickLabelMode', Ylabel{a}, 'ZTickLabelMode', Zlabel{a}); 
+                catch
+                    % ignore - fix issue #4 (using HG2 on R2014a and earlier)
+                end
+            end
+            % Revert the tex-labels font weights
+            try set(texLabels, 'FontWeight','bold'); catch, end
+            % Revert annotation units
+            for handleIdx = 1 : numel(annotationHandles)
+                try
+                    oldUnits = originalUnits{handleIdx};
+                catch
+                    oldUnits = originalUnits;
+                end
+                try set(annotationHandles(handleIdx),'Units',oldUnits); catch, end
+            end
+            % Revert figure units
+            set(fig,'Units',oldFigUnits);
+        end
+
+        % Output to clipboard (if requested)
+        if options.clipboard
+            % Delete the output file if unchanged from the default name ('export_fig_out.png')
+            if strcmpi(options.name,'export_fig_out')
+                try
+                    fileInfo = dir('export_fig_out.png');
+                    if ~isempty(fileInfo)
+                        timediff = now - fileInfo.datenum;
+                        ONE_SEC = 1/24/60/60;
+                        if timediff < ONE_SEC
+                            delete('export_fig_out.png');
+                        end
+                    end
+                catch
+                    % never mind...
+                end
+            end
+
+            % Save the image in the system clipboard
+            % credit: Jiro Doke's IMCLIPBOARD: http://www.mathworks.com/matlabcentral/fileexchange/28708-imclipboard
+            try
+                error(javachk('awt', 'export_fig -clipboard output'));
+            catch
+                warning('export_fig -clipboard output failed: requires Java to work');
+                return;
+            end
+            try
+                % Import necessary Java classes
+                import java.awt.Toolkit
+                import java.awt.image.BufferedImage
+                import java.awt.datatransfer.DataFlavor
+
+                % Get System Clipboard object (java.awt.Toolkit)
+                cb = Toolkit.getDefaultToolkit.getSystemClipboard();
+
+                % Add java class (ImageSelection) to the path
+                if ~exist('ImageSelection', 'class')
+                    javaaddpath(fileparts(which(mfilename)), '-end');
+                end
+
+                % Get image size
+                ht = size(imageData, 1);
+                wd = size(imageData, 2);
+
+                % Convert to Blue-Green-Red format
+                try
+                    imageData2 = imageData(:, :, [3 2 1]);
+                catch
+                    % Probably gray-scaled image (2D, without the 3rd [RGB] dimension)
+                    imageData2 = imageData(:, :, [1 1 1]);
+                end
+
+                % Convert to 3xWxH format
+                imageData2 = permute(imageData2, [3, 2, 1]);
+
+                % Append Alpha data (unused - transparency is not supported in clipboard copy)
+                alphaData2 = uint8(permute(255*alpha,[3,2,1])); %=255*ones(1,wd,ht,'uint8')
+                imageData2 = cat(1, imageData2, alphaData2);
+
+                % Create image buffer
+                imBuffer = BufferedImage(wd, ht, BufferedImage.TYPE_INT_RGB);
+                imBuffer.setRGB(0, 0, wd, ht, typecast(imageData2(:), 'int32'), 0, wd);
+
+                % Create ImageSelection object from the image buffer
+                imSelection = ImageSelection(imBuffer);
+
+                % Set clipboard content to the image
+                cb.setContents(imSelection, []);
+            catch
+                warning('export_fig -clipboard output failed: %s', lasterr); %#ok<LERR>
+            end
+        end
+
+        % Don't output the data to console unless requested
+        if ~nargout
+            clear imageData alpha
+        end
+    catch err
+        % Display possible workarounds before the error message
+        if displaySuggestedWorkarounds && ~strcmpi(err.message,'export_fig error')
+            if ~hadError,  fprintf(2, 'export_fig error. ');  end
+            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');
+            end
+            try
+                if options.eps
+                    fprintf(2, '  and that you have <a href="http://www.foolabs.com/xpdf">pdftops</a> installed\n');
+                end
+            catch
+                % ignore - probably an error in parse_args
+            end
+            fprintf(2, '  and that you do not have <a href="matlab:which export_fig -all">multiple versions</a> of export_fig installed by mistake\n');
+            fprintf(2, '  and that you did not made a mistake in the <a href="matlab:help export_fig">expected input arguments</a>\n');
+            try
+                % Alert per issue #149
+                if ~strncmpi(get(0,'Units'),'pixel',5)
+                    fprintf(2, '  or try to set groot''s Units property back to its default value of ''pixels'' (<a href="matlab:web(''https://github.com/altmany/export_fig/issues/149'',''-browser'');">details</a>)\n');
+                end
+            catch
+                % ignore - maybe an old MAtlab release
+            end
+            fprintf(2, '\nIf the problem persists, then please <a href="https://github.com/altmany/export_fig/issues">report a new issue</a>.\n\n');
+        end
+        rethrow(err)
+    end
 end
-% Hack the font units where necessary (due to a font rendering bug in
-% print?). This may not work perfectly in all cases. Also it can change the
-% figure layout if reverted, so use a copy.
-magnify = options.magnify * options.aa_factor;
-if isbitmap(options) && magnify ~= 1
-    fontu = findobj(fig, 'FontUnits', 'normalized');
-    if ~isempty(fontu)
-        % Some normalized font units found
-        if ~cls
-            fig = copyfig(fig);
-            set(fig, 'Visible', 'off');
-            fontu = findobj(fig, 'FontUnits', 'normalized');
-            cls = true;
-        end
-        set(fontu, 'FontUnits', 'points');
-    end
+
+function options = default_options()
+    % 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, ...
+        'gs_options',   {{}});
 end
-% MATLAB "feature": axes limits and tick marks can change when printing
-Hlims = findall(fig, 'Type', 'axes');
-if ~cls
-    % Record the old axes limit and tick modes
-    Xlims = make_cell(get(Hlims, 'XLimMode'));
-    Ylims = make_cell(get(Hlims, 'YLimMode'));
-    Zlims = make_cell(get(Hlims, 'ZLimMode'));
-    Xtick = make_cell(get(Hlims, 'XTickMode'));
-    Ytick = make_cell(get(Hlims, 'YTickMode'));
-    Ztick = make_cell(get(Hlims, 'ZTickMode'));
+
+function [fig, options] = parse_args(nout, fig, varargin)
+    % Parse the input arguments
+
+    % Set the defaults
+    native = false; % Set resolution to native of an image
+    options = default_options();
+    options.im =    (nout == 1);  % user requested imageData output
+    options.alpha = (nout == 2);  % user requested alpha output
+
+    % Go through the other arguments
+    skipNext = false;
+    for a = 1:nargin-2
+        if skipNext
+            skipNext = false;
+            continue;
+        end
+        if all(ishandle(varargin{a}))
+            fig = varargin{a};
+        elseif ischar(varargin{a}) && ~isempty(varargin{a})
+            if varargin{a}(1) == '-'
+                switch lower(varargin{a}(2:end))
+                    case 'nocrop'
+                        options.crop = false;
+                        options.crop_amounts = [0,0,0,0];
+                    case {'trans', 'transparent'}
+                        options.transparent = true;
+                    case 'opengl'
+                        options.renderer = 1;
+                    case 'zbuffer'
+                        options.renderer = 2;
+                    case 'painters'
+                        options.renderer = 3;
+                    case 'pdf'
+                        options.pdf = true;
+                    case 'eps'
+                        options.eps = true;
+                    case 'png'
+                        options.png = true;
+                    case {'tif', 'tiff'}
+                        options.tif = true;
+                    case {'jpg', 'jpeg'}
+                        options.jpg = true;
+                    case 'bmp'
+                        options.bmp = true;
+                    case 'rgb'
+                        options.colourspace = 0;
+                    case 'cmyk'
+                        options.colourspace = 1;
+                    case {'gray', 'grey'}
+                        options.colourspace = 2;
+                    case {'a1', 'a2', 'a3', 'a4'}
+                        options.aa_factor = str2double(varargin{a}(3));
+                    case 'append'
+                        options.append = true;
+                    case 'bookmark'
+                        options.bookmark = true;
+                    case 'native'
+                        native = true;
+                    case 'clipboard'
+                        options.clipboard = true;
+                        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
+                        try
+                            zipFileName = 'https://github.com/altmany/export_fig/archive/master.zip';
+                            folderName = fileparts(which(mfilename('fullpath')));
+                            targetFileName = fullfile(folderName, datestr(now,'yyyy-mm-dd.zip'));
+                            urlwrite(zipFileName,targetFileName);
+                        catch
+                            error('Could not download %s into %s\n',zipFileName,targetFileName);
+                        end
+
+                        % Unzip the downloaded zip file in the export_fig folder
+                        try
+                            unzip(targetFileName,folderName);
+                        catch
+                            error('Could not unzip %s\n',targetFileName);
+                        end
+                    case 'nofontswap'
+                        options.fontswap = false;
+                    otherwise
+                        try
+                            wasError = false;
+                            if strcmpi(varargin{a}(1:2),'-d')
+                                varargin{a}(2) = 'd';  % ensure lowercase 'd'
+                                options.gs_options{end+1} = varargin{a};
+                            elseif strcmpi(varargin{a}(1:2),'-c')
+                                if numel(varargin{a})==2
+                                    skipNext = true;
+                                    vals = str2num(varargin{a+1}); %#ok<ST2NM>
+                                else
+                                    vals = str2num(varargin{a}(3:end)); %#ok<ST2NM>
+                                end
+                                if numel(vals)~=4
+                                    wasError = true;
+                                    error('option -c cannot be parsed: must be a 4-element numeric vector');
+                                end
+                                options.crop_amounts = vals;
+                                options.crop = true;
+                            else  % scalar parameter value
+                                val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match'));
+                                if isempty(val) || isnan(val)
+                                    % Issue #51: improved processing of input args (accept space between param name & value)
+                                    val = str2double(varargin{a+1});
+                                    if isscalar(val) && ~isnan(val)
+                                        skipNext = true;
+                                    end
+                                end
+                                if ~isscalar(val) || isnan(val)
+                                    wasError = true;
+                                    error('option %s is not recognised or cannot be parsed', varargin{a});
+                                end
+                                switch lower(varargin{a}(2))
+                                    case 'm'
+                                        % Magnification may never be negative
+                                        if val <= 0
+                                            wasError = true;
+                                            error('Bad magnification value: %g (must be positive)', val);
+                                        end
+                                        options.magnify = val;
+                                    case 'r'
+                                        options.resolution = val;
+                                    case 'q'
+                                        options.quality = max(val, 0);
+                                    case 'p'
+                                        options.bb_padding = val;
+                                end
+                            end
+                        catch err
+                            % We might have reached here by raising an intentional error
+                            if wasError  % intentional raise
+                                rethrow(err)
+                            else  % unintentional
+                                error(['Unrecognized export_fig input option: ''' varargin{a} '''']);
+                            end
+                        end
+                end
+            else
+                [p, options.name, ext] = fileparts(varargin{a});
+                if ~isempty(p)
+                    options.name = [p filesep options.name];
+                end
+                switch lower(ext)
+                    case {'.tif', '.tiff'}
+                        options.tif = true;
+                    case {'.jpg', '.jpeg'}
+                        options.jpg = true;
+                    case '.png'
+                        options.png = true;
+                    case '.bmp'
+                        options.bmp = true;
+                    case '.eps'
+                        options.eps = true;
+                    case '.pdf'
+                        options.pdf = true;
+                    case '.fig'
+                        % If no open figure, then load the specified .fig file and continue
+                        if isempty(fig)
+                            fig = openfig(varargin{a},'invisible');
+                            varargin{a} = fig;
+                            options.closeFig = true;
+                        else
+                            % save the current figure as the specified .fig file and exit
+                            saveas(fig(1),varargin{a});
+                            fig = -1;
+                            return
+                        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>
+                    otherwise
+                        options.name = varargin{a};
+                end
+            end
+        end
+    end
+
+    % Quick bail-out if no figure found
+    if isempty(fig),  return;  end
+
+    % Do border padding with repsect to a cropped image
+    if options.bb_padding
+        options.crop = true;
+    end
+
+    % Set default anti-aliasing now we know the renderer
+    if options.aa_factor == 0
+        try isAA = strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on'); catch, isAA = false; end
+        options.aa_factor = 1 + 2 * (~(using_hg2(fig) && isAA) | (options.renderer == 3));
+    end
+
+    % Convert user dir '~' to full path
+    if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\')
+        options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end));
+    end
+
+    % Compute the magnification and resolution
+    if isempty(options.magnify)
+        if isempty(options.resolution)
+            options.magnify = 1;
+            options.resolution = 864;
+        else
+            options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch');
+        end
+    elseif isempty(options.resolution)
+        options.resolution = 864;
+    end
+
+    % Set the default format
+    if ~isvector(options) && ~isbitmap(options)
+        options.png = true;
+    end
+
+    % Check whether transparent background is wanted (old way)
+    if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none')
+        options.transparent = true;
+    end
+
+    % If requested, set the resolution to the native vertical resolution of the
+    % first suitable image found
+    if native && isbitmap(options)
+        % Find a suitable image
+        list = 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)
+                    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
+    end
 end
-% Set all axes limit and tick modes to manual, so the limits and ticks can't change
-set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual');
-set_tick_mode(Hlims, 'X');
-set_tick_mode(Hlims, 'Y');
-set_tick_mode(Hlims, 'Z');
-% Set to print exactly what is there
-set(fig, 'InvertHardcopy', 'off');
-% Set the renderer
-switch options.renderer
-    case 1
-        renderer = '-opengl';
-    case 2
-        renderer = '-zbuffer';
-    case 3
-        renderer = '-painters';
-    otherwise
-        renderer = '-opengl'; % Default for bitmaps
+
+function A = downsize(A, factor)
+    % Downsample an image
+    if factor == 1
+        % Nothing to do
+        return
+    end
+    try
+        % Faster, but requires image processing toolbox
+        A = imresize(A, 1/factor, 'bilinear');
+    catch
+        % No image processing toolbox - resize manually
+        % Lowpass filter - use Gaussian as is separable, so faster
+        % Compute the 1d Gaussian filter
+        filt = (-factor-1:factor+1) / (factor * 0.6);
+        filt = exp(-filt .* filt);
+        % Normalize the filter
+        filt = single(filt / sum(filt));
+        % Filter the image
+        padding = floor(numel(filt) / 2);
+        for a = 1:size(A, 3)
+            A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid');
+        end
+        % Subsample
+        A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);
+    end
 end
-% Do the bitmap formats first
-if isbitmap(options)
-    % Get the background colour
-    if options.transparent && (options.png || options.alpha)
-        % Get out an alpha channel
-        % MATLAB "feature": black colorbar axes can change to white and vice versa!
-        hCB = findobj(fig, 'Type', 'axes', 'Tag', 'Colorbar');
-        if isempty(hCB)
-            yCol = [];
-            xCol = [];
-        else
-            yCol = get(hCB, 'YColor');
-            xCol = get(hCB, 'XColor');
-            if iscell(yCol)
-                yCol = cell2mat(yCol);
-                xCol = cell2mat(xCol);
-            end
-            yCol = sum(yCol, 2);
-            xCol = sum(xCol, 2);
-        end
-        % MATLAB "feature": apparently figure size can change when changing
-        % colour in -nodisplay mode
-        pos = get(fig, 'Position');
-        % Set the background colour to black, and set size in case it was
-        % changed internally
-        tcol = get(fig, 'Color');
-        set(fig, 'Color', 'k', 'Position', pos);
-        % Correct the colorbar axes colours
-        set(hCB(yCol==0), 'YColor', [0 0 0]);
-        set(hCB(xCol==0), 'XColor', [0 0 0]);
-        % Print large version to array
-        B = print2array(fig, magnify, renderer);
-        % Downscale the image
-        B = downsize(single(B), options.aa_factor);
-        % Set background to white (and set size)
-        set(fig, 'Color', 'w', 'Position', pos);
-        % Correct the colorbar axes colours
-        set(hCB(yCol==3), 'YColor', [1 1 1]);
-        set(hCB(xCol==3), 'XColor', [1 1 1]);
-        % Print large version to array
-        A = print2array(fig, magnify, renderer);
-        % Downscale the image
-        A = downsize(single(A), options.aa_factor);
-        % Set the background colour (and size) back to normal
-        set(fig, 'Color', tcol, 'Position', pos);
-        % Compute the alpha map
-        alpha = round(sum(B - A, 3)) / (255 * 3) + 1;
-        A = alpha;
-        A(A==0) = 1;
-        A = B ./ A(:,:,[1 1 1]);
-        clear B
-        % Convert to greyscale
-        if options.colourspace == 2
-            A = rgb2grey(A);
-        end
-        A = uint8(A);
-        % Crop the background
-        if options.crop
-            [alpha, v] = crop_borders(alpha, 0, 1);
-            A = A(v(1):v(2),v(3):v(4),:);
-        end
-        if options.png
-            % Compute the resolution
-            res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
-            % Save the png
-            imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
-            % Clear the png bit
-            options.png = false;
-        end
-        % Return only one channel for greyscale
-        if isbitmap(options)
-            A = check_greyscale(A);
-        end
-        if options.alpha
-            % Store the image
-            im = A;
-            % Clear the alpha bit
-            options.alpha = false;
-        end
-        % Get the non-alpha image
-        if isbitmap(options)
-            alph = alpha(:,:,ones(1, size(A, 3)));
-            A = uint8(single(A) .* alph + 255 * (1 - alph));
-            clear alph
-        end
-        if options.im
-            % Store the new image
-            im = A;
-        end
-    else
-        % Print large version to array
-        if options.transparent
-            % MATLAB "feature": apparently figure size can change when changing
-            % colour in -nodisplay mode
-            pos = get(fig, 'Position');
-            tcol = get(fig, 'Color');
-            set(fig, 'Color', 'w', 'Position', pos);
-            A = print2array(fig, magnify, renderer);
-            set(fig, 'Color', tcol, 'Position', pos);
-            tcol = 255;
-        else
-            [A, tcol] = print2array(fig, magnify, renderer);
-        end
-        % Crop the background
-        if options.crop
-            A = crop_borders(A, tcol, 1);
-        end
-        % Downscale the image
-        A = downsize(A, options.aa_factor);
-        if options.colourspace == 2
-            % Convert to greyscale
-            A = rgb2grey(A);
-        else
-            % Return only one channel for greyscale
-            A = check_greyscale(A);
-        end
-        % Outputs
-        if options.im
-            im = A;
-        end
-        if options.alpha
-            im = A;
-            alpha = zeros(size(A, 1), size(A, 2), 'single');
-        end
-    end
-    % Save the images
-    if options.png
-        res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
-        imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
-    end
-    if options.bmp
-        imwrite(A, [options.name '.bmp']);
-    end
-    % Save jpeg with given quality
-    if options.jpg
-        quality = options.quality;
-        if isempty(quality)
-            quality = 95;
-        end
-        if quality > 100
-            imwrite(A, [options.name '.jpg'], 'Mode', 'lossless');
-        else
-            imwrite(A, [options.name '.jpg'], 'Quality', quality);
-        end
-    end
-    % Save tif images in cmyk if wanted (and possible)
-    if options.tif
-        if options.colourspace == 1 && size(A, 3) == 3
-            A = double(255 - A);
-            K = min(A, [], 3);
-            K_ = 255 ./ max(255 - K, 1);
-            C = (A(:,:,1) - K) .* K_;
-            M = (A(:,:,2) - K) .* K_;
-            Y = (A(:,:,3) - K) .* K_;
-            A = uint8(cat(3, C, M, Y, K));
-            clear C M Y K K_
-        end
-        append_mode = {'overwrite', 'append'};
-        imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1});
-    end
+
+function A = rgb2grey(A)
+    A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A)); %#ok<ZEROLIKE>
 end
-% Now do the vector formats
-if isvector(options)
-    % Set the default renderer to painters
-    if ~options.renderer
-        renderer = '-painters';
-    end
-    % Generate some filenames
-    tmp_nam = [tempname '.eps'];
-    if options.pdf
-        pdf_nam = [options.name '.pdf'];
-    else
-        pdf_nam = [tempname '.pdf'];
-    end
-    % Generate the options for print
-    p2eArgs = {renderer, sprintf('-r%d', options.resolution)};
-    if options.colourspace == 1
-        p2eArgs = [p2eArgs {'-cmyk'}];
-    end
-    if ~options.crop
-        p2eArgs = [p2eArgs {'-loose'}];
-    end
-    try
-        % Generate an eps
-        print2eps(tmp_nam, fig, options.bb_padding, p2eArgs{:});
-        % Remove the background, if desired
-        if options.transparent && ~isequal(get(fig, 'Color'), 'none')
-            eps_remove_background(tmp_nam, 1 + using_hg2(fig));
-        end
-        % Add a bookmark to the PDF if desired
-        if options.bookmark
-            fig_nam = get(fig, 'Name');
-            if isempty(fig_nam)
-                warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.');
-            end
-            add_bookmark(tmp_nam, fig_nam);
-        end
-        % Generate a pdf
-        eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);
-    catch ex
-        % Delete the eps
-        delete(tmp_nam);
-        rethrow(ex);
-    end
-    % Delete the eps
-    delete(tmp_nam);
-    if options.eps
-        try
-            % Generate an eps from the pdf
-            pdf2eps(pdf_nam, [options.name '.eps']);
-        catch ex
-            if ~options.pdf
-                % Delete the pdf
-                delete(pdf_nam);
-            end
-            rethrow(ex);
-        end
-        if ~options.pdf
-            % Delete the pdf
-            delete(pdf_nam);
-        end
+
+function A = check_greyscale(A)
+    % Check if the image is greyscale
+    if size(A, 3) == 3 && ...
+            all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ...
+            all(reshape(A(:,:,2) == A(:,:,3), [], 1))
+        A = A(:,:,1); % Save only one channel for 8-bit output
     end
 end
-if cls
-    % Close the created figure
-    close(fig);
-else
-    % Reset the hardcopy mode
-    set(fig, 'InvertHardcopy', old_mode);
-    % Reset the axes limit and tick modes
-    for a = 1:numel(Hlims)
-        set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a}, 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a});
-    end
+
+function eps_remove_background(fname, count)
+    % Remove the background of an eps file
+    % Open the file
+    fh = fopen(fname, 'r+');
+    if fh == -1
+        error('Not able to open file %s.', fname);
+    end
+    % Read the file line by line
+    while count
+        % Get the next line
+        l = fgets(fh);
+        if isequal(l, -1)
+            break; % Quit, no rectangle found
+        end
+        % Check if the line contains the background rectangle
+        if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1)
+            % Set the line to whitespace and quit
+            l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' ';
+            fseek(fh, -numel(l), 0);
+            fprintf(fh, l);
+            % Reduce the count
+            count = count - 1;
+        end
+    end
+    % Close the file
+    fclose(fh);
 end
+
+function b = isvector(options)
+    b = options.pdf || options.eps;
 end
 
-function [fig, options] = parse_args(nout, varargin)
-% Parse the input arguments
-% Set the defaults
-fig = get(0, 'CurrentFigure');
-options = struct('name', 'export_fig_out', ...
-                 'crop', true, ...
-                 'transparent', false, ...
-                 'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters
-                 'pdf', false, ...
-                 'eps', false, ...
-                 'png', false, ...
-                 'tif', false, ...
-                 'jpg', false, ...
-                 'bmp', false, ...
-                 'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray
-                 'append', false, ...
-                 'im', nout == 1, ...
-                 'alpha', nout == 2, ...
-                 'aa_factor', 0, ...
-                 'bb_padding', 0, ...
-                 'magnify', [], ...
-                 'resolution', [], ...
-                 'bookmark', false, ...
-                 'quality', []);
-native = false; % Set resolution to native of an image
-
-% Go through the other arguments
-for a = 1:nargin-1
-    if all(ishandle(varargin{a}))
-        fig = varargin{a};
-    elseif ischar(varargin{a}) && ~isempty(varargin{a})
-        if varargin{a}(1) == '-'
-            switch lower(varargin{a}(2:end))
-                case 'nocrop'
-                    options.crop = false;
-                case {'trans', 'transparent'}
-                    options.transparent = true;
-                case 'opengl'
-                    options.renderer = 1;
-                case 'zbuffer'
-                    options.renderer = 2;
-                case 'painters'
-                    options.renderer = 3;
-                case 'pdf'
-                    options.pdf = true;
-                case 'eps'
-                    options.eps = true;
-                case 'png'
-                    options.png = true;
-                case {'tif', 'tiff'}
-                    options.tif = true;
-                case {'jpg', 'jpeg'}
-                    options.jpg = true;
-                case 'bmp'
-                    options.bmp = true;
-                case 'rgb'
-                    options.colourspace = 0;
-                case 'cmyk'
-                    options.colourspace = 1;
-                case {'gray', 'grey'}
-                    options.colourspace = 2;
-                case {'a1', 'a2', 'a3', 'a4'}
-                    options.aa_factor = str2double(varargin{a}(3));
-                case 'append'
-                    options.append = true;
-                case 'bookmark'
-                    options.bookmark = true;
-                case 'native'
-                    native = true;
-                otherwise
-                    val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match'));
-                    if ~isscalar(val)
-                        error('option %s not recognised', varargin{a});
-                    end
-                    switch lower(varargin{a}(2))
-                        case 'm'
-                            options.magnify = val;
-                        case 'r'
-                            options.resolution = val;
-                        case 'q'
-                            options.quality = max(val, 0);
-                        case 'p'
-                            options.bb_padding = val;
-                    end
-            end
-        else
-            [p, options.name, ext] = fileparts(varargin{a});
-            if ~isempty(p)
-                options.name = [p filesep options.name];
-            end
-            switch lower(ext)
-                case {'.tif', '.tiff'}
-                    options.tif = true;
-                case {'.jpg', '.jpeg'}
-                    options.jpg = true;
-                case '.png'
-                    options.png = true;
-                case '.bmp'
-                    options.bmp = true;
-                case '.eps'
-                    options.eps = true;
-                case '.pdf'
-                    options.pdf = true;
-                otherwise
-                    options.name = varargin{a};
-            end
-        end
-    end
-end
-
-% Set default anti-aliasing now we know the renderer
-if options.aa_factor == 0
-    options.aa_factor = 1 + 2 * (~(using_hg2(fig) && strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on')) | (options.renderer == 3));
-end
-
-% Convert user dir '~' to full path
-if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\')
-    options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end));
-end
-
-% Compute the magnification and resolution
-if isempty(options.magnify)
-    if isempty(options.resolution)
-        options.magnify = 1;
-        options.resolution = 864;
-    else
-        options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch');
-    end
-elseif isempty(options.resolution)
-    options.resolution = 864;
-end  
-
-% Check we have a figure handle
-if isempty(fig)
-    error('No figure found');
-end
-
-% Set the default format
-if ~isvector(options) && ~isbitmap(options)
-    options.png = true;
-end
-
-% Check whether transparent background is wanted (old way)
-if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none')
-    options.transparent = true;
-end
-
-% If requested, set the resolution to the native vertical resolution of the
-% first suitable image found
-if native && isbitmap(options)
-    % Find a suitable image
-    list = findobj(fig, 'Type', 'image', 'Tag', 'export_fig_native');
-    if isempty(list)
-        list = findobj(fig, 'Type', 'image', 'Visible', 'on');
-    end
-    for hIm = list(:)'
-        % Check height is >= 2
-        height = size(get(hIm, 'CData'), 1);
-        if height < 2
-            continue
-        end
-        % Account for the image filling only part of the axes, or vice
-        % versa
-        yl = get(hIm, 'YData');
-        if isscalar(yl)
-            yl = [yl(1)-0.5 yl(1)+height+0.5];
-        else
-            if ~diff(yl)
-                continue
-            end
-            yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1));
-        end
-        hAx = get(hIm, 'Parent');
-        yl2 = get(hAx, 'YLim');
-        % Find the pixel height of the axes
-        oldUnits = get(hAx, 'Units');
-        set(hAx, 'Units', 'pixels');
-        pos = get(hAx, 'Position');
-        set(hAx, 'Units', oldUnits);
-        if ~pos(4)
-            continue
-        end
-        % Found a suitable image
-        % Account for stretch-to-fill being disabled
-        pbar = get(hAx, 'PlotBoxAspectRatio');
-        pos = min(pos(4), pbar(2)*pos(3)/pbar(1));
-        % Set the magnification to give native resolution
-        options.magnify = (height * diff(yl2)) / (pos * diff(yl));
-        break
-    end
-end
-end
-
-function A = downsize(A, factor)
-% Downsample an image
-if factor == 1
-    % Nothing to do
-    return
-end
-try
-    % Faster, but requires image processing toolbox
-    A = imresize(A, 1/factor, 'bilinear');
-catch
-    % No image processing toolbox - resize manually
-    % Lowpass filter - use Gaussian as is separable, so faster
-    % Compute the 1d Gaussian filter
-    filt = (-factor-1:factor+1) / (factor * 0.6);
-    filt = exp(-filt .* filt);
-    % Normalize the filter
-    filt = single(filt / sum(filt));
-    % Filter the image
-    padding = floor(numel(filt) / 2);
-    for a = 1:size(A, 3)
-        A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid');
-    end
-    % Subsample
-    A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);
-end
-end
-
-function A = rgb2grey(A)
-A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A));
-end
-
-function A = check_greyscale(A)
-% Check if the image is greyscale
-if size(A, 3) == 3 && ...
-        all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ...
-        all(reshape(A(:,:,2) == A(:,:,3), [], 1))
-    A = A(:,:,1); % Save only one channel for 8-bit output
-end
-end
-
-function eps_remove_background(fname, count)
-% Remove the background of an eps file
-% Open the file
-fh = fopen(fname, 'r+');
-if fh == -1
-    error('Not able to open file %s.', fname);
-end
-% Read the file line by line
-while count
-    % Get the next line
-    l = fgets(fh);
-    if isequal(l, -1)
-        break; % Quit, no rectangle found
-    end
-    % Check if the line contains the background rectangle
-    if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1)
-        % Set the line to whitespace and quit
-        l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' ';
-        fseek(fh, -numel(l), 0);
-        fprintf(fh, l);
-        % Reduce the count
-        count = count - 1;
-    end
-end
-% Close the file
-fclose(fh);
-end
-
-function b = isvector(options)
-b = options.pdf || options.eps;
-end
-
 function b = isbitmap(options)
-b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
+    b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
 end
 
 % Helper function
 function A = make_cell(A)
-if ~iscell(A)
-    A = {A};
+    if ~iscell(A)
+        A = {A};
+    end
 end
+
+function add_bookmark(fname, bookmark_text)
+    % Adds a bookmark to the temporary EPS file after %%EndPageSetup
+    % Read in the file
+    fh = fopen(fname, 'r');
+    if fh == -1
+        error('File %s not found.', fname);
+    end
+    try
+        fstrm = fread(fh, '*char')';
+    catch ex
+        fclose(fh);
+        rethrow(ex);
+    end
+    fclose(fh);
+
+    % Include standard pdfmark prolog to maximize compatibility
+    fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse'));
+    % Add page bookmark
+    fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text));
+
+    % Write out the updated file
+    fh = fopen(fname, 'w');
+    if fh == -1
+        error('Unable to open %s for writing.', fname);
+    end
+    try
+        fwrite(fh, fstrm, 'char*1');
+    catch ex
+        fclose(fh);
+        rethrow(ex);
+    end
+    fclose(fh);
 end
 
-function add_bookmark(fname, bookmark_text)
-% Adds a bookmark to the temporary EPS file after %%EndPageSetup
-% Read in the file
-fh = fopen(fname, 'r');
-if fh == -1
-    error('File %s not found.', fname);
+function set_tick_mode(Hlims, ax)
+    % Set the tick mode of linear axes to manual
+    % Leave log axes alone as these are tricky
+    M = get(Hlims, [ax 'Scale']);
+    if ~iscell(M)
+        M = {M};
+    end
+    M = cellfun(@(c) strcmp(c, 'linear'), M);
+    set(Hlims(M), [ax 'TickMode'], 'manual');
+    %set(Hlims(M), [ax 'TickLabelMode'], 'manual');  % this hides exponent label in HG2!
 end
-try
-    fstrm = fread(fh, '*char')';
-catch ex
-    fclose(fh);
-    rethrow(ex);
+
+function change_rgb_to_cmyk(fname)  % convert RGB => CMYK within an EPS file
+    % Do post-processing on the eps file
+    try
+        % Read the EPS file into memory
+        fstrm = read_write_entire_textfile(fname);
+
+        % Replace all gray-scale colors
+        fstrm = regexprep(fstrm, '\n([\d.]+) +GC\n', '\n0 0 0 ${num2str(1-str2num($1))} CC\n');
+        
+        % Replace all RGB colors
+        fstrm = regexprep(fstrm, '\n[0.]+ +[0.]+ +[0.]+ +RC\n', '\n0 0 0 1 CC\n');  % pure black
+        fstrm = regexprep(fstrm, '\n([\d.]+) +([\d.]+) +([\d.]+) +RC\n', '\n${sprintf(''%.4g '',[1-[str2num($1),str2num($2),str2num($3)]/max([str2num($1),str2num($2),str2num($3)]),1-max([str2num($1),str2num($2),str2num($3)])])} CC\n');
+
+        % Overwrite the file with the modified contents
+        read_write_entire_textfile(fname, fstrm);
+    catch
+        % never mind - leave as is...
+    end
 end
-fclose(fh);
-
-% Include standard pdfmark prolog to maximize compatibility
-fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse'));
-% Add page bookmark
-fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text));
-
-% Write out the updated file
-fh = fopen(fname, 'w');
-if fh == -1
-    error('Unable to open %s for writing.', fname);
-end
-try
-    fwrite(fh, fstrm, 'char*1');
-catch ex
-    fclose(fh);
-    rethrow(ex);
-end
-fclose(fh);
-end
-
-function set_tick_mode(Hlims, ax)
-% Set the tick mode of linear axes to manual
-% Leave log axes alone as these are tricky
-M = get(Hlims, [ax 'Scale']);
-if ~iscell(M)
-    M = {M};
-end
-M = cellfun(@(c) strcmp(c, 'linear'), M);
-set(Hlims(M), [ax 'TickMode'], 'manual');
-end
Index: issm/trunk/externalpackages/export_fig/fix_lines.m
===================================================================
--- issm/trunk/externalpackages/export_fig/fix_lines.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/fix_lines.m	(revision 21341)
@@ -38,6 +38,14 @@
 % opened.
 
+% 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+)
+% 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39
+
 function fstrm = fix_lines(fstrm, fname2)
 
+% Issue #20: warn users if using this function in HG2 (R2014b+)
+if using_hg2
+    warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.');
+end
+    
 if nargout == 0 || nargin > 1
     if nargin < 2
@@ -114,9 +122,4 @@
 end
 
-% Isolate line style definition section
-first_sec = strfind(fstrm, '% line types:');
-[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
-[remaining, remaining] = strtok(remaining, '%');
-
 % Define the new styles, including the new GR format
 % Dot and dash lengths have two parts: a constant amount plus a line width
@@ -135,5 +138,10 @@
 
 % Construct the output
-fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
+% This is the original (memory-intensive) code:
+%first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section
+%[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
+%[remaining, remaining] = strtok(remaining, '%');
+%fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
+fstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\r',new_style{:}),'%']);
 
 % Write the output file
Index: issm/trunk/externalpackages/export_fig/ghostscript.m
===================================================================
--- issm/trunk/externalpackages/export_fig/ghostscript.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/ghostscript.m	(revision 21341)
@@ -1,2 +1,3 @@
+function varargout = ghostscript(cmd)
 %GHOSTSCRIPT  Calls a local GhostScript executable with the input command
 %
@@ -20,139 +21,176 @@
 %   result - Output from ghostscript.
 
-% Copyright: Oliver Woodford, 2009-2013
+% Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015-
+%{
+% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
+% Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems.
+% 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and
+%            Shaun Kline for pointing out the issue
+% 04/05/11 - Thanks to David Chorlian for pointing out an alternative
+%            location for gs on linux.
+% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
+%            Punnoose for highlighting the issue.
+% 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
+%            Steinbring for proposing the fix.
+% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes 
+%            for the fix.
+% 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen
+%            Vermeer for raising the issue.
+% 27/02/15 - If Ghostscript croaks, display suggested workarounds
+% 30/03/15 - Improved performance by caching status of GS path check, if ok
+% 14/05/15 - Clarified warning message in case GS path could not be saved
+% 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74)
+% 10/11/15 - Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX
+%}
 
-% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
-% Mac OS.
-% Thanks to Nathan Childress for the fix to the default location on 64-bit
-% Windows systems.
-% 27/4/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and
-% Shaun Kline for pointing out the issue
-% 4/5/11 - Thanks to David Chorlian for pointing out an alternative
-% location for gs on linux.
-% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
-% Punnoose for highlighting the issue.
-% 28/6/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
-% Steinbring for proposing the fix.
-% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes
-% for the fix.
-% 23/01/2014 - Add full path to ghostscript.txt in warning. Thanks to Koen
-% Vermeer for raising the issue.
-
-function varargout = ghostscript(cmd)
-% Initialize any required system calls before calling ghostscript
-shell_cmd = '';
-if isunix
-    shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
-end
-if ismac
-    shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';  % Avoids an error on Mac with GS 9.07
-end
-% Call ghostscript
-[varargout{1:nargout}] = system(sprintf('%s"%s" %s', shell_cmd, gs_path, cmd));
+    try
+        % Call ghostscript
+        [varargout{1:nargout}] = system([gs_command(gs_path()) cmd]);
+    catch err
+        % Display possible workarounds for Ghostscript croaks
+        url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998';  % issue #12
+        url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270';  % issue #20
+        hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end
+        fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\n * <a href="%s">%s</a> ',hg2_str,url1,url1);
+        if using_hg2
+            fprintf(2, '(GS 9.10)\n * <a href="%s">%s</a> (R2014a)',url2,url2);
+        end
+        fprintf('\n\n');
+        if ismac || isunix
+            url3 = 'https://github.com/altmany/export_fig/issues/27';  % issue #27
+            fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\n * <a href="%s">%s</a>\n\n',url3,url3);
+            % issue #20
+            fpath = which(mfilename);
+            if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end
+            fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export..." to "setenv ..."\nat the bottom of <a href="matlab:opentoline(''%s'',174)">%s</a>\n\n',fpath,fpath);
+        end
+        rethrow(err);
+    end
 end
 
 function path_ = gs_path
-% Return a valid path
-% Start with the currently set path
-path_ = user_string('ghostscript');
-% Check the path works
-if check_gs_path(path_)
-    return
-end
-% Check whether the binary is on the path
-if ispc
-    bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};
-else
-    bin = {'gs'};
-end
-for a = 1:numel(bin)
-    path_ = bin{a};
-    if check_store_gs_path(path_)
+    % Return a valid path
+    % Start with the currently set path
+    path_ = user_string('ghostscript');
+    % Check the path works
+    if check_gs_path(path_)
         return
     end
-end
-% Search the obvious places
-if ispc
-    default_location = 'C:\Program Files\gs\';
-    dir_list = dir(default_location);
-    if isempty(dir_list)
-        default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems 
+    % Check whether the binary is on the path
+    if ispc
+        bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};
+    else
+        bin = {'gs'};
+    end
+    for a = 1:numel(bin)
+        path_ = bin{a};
+        if check_store_gs_path(path_)
+            return
+        end
+    end
+    % Search the obvious places
+    if ispc
+        default_location = 'C:\Program Files\gs\';
         dir_list = dir(default_location);
+        if isempty(dir_list)
+            default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems
+            dir_list = dir(default_location);
+        end
+        executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'};
+        ver_num = 0;
+        % If there are multiple versions, use the newest
+        for a = 1:numel(dir_list)
+            ver_num2 = sscanf(dir_list(a).name, 'gs%g');
+            if ~isempty(ver_num2) && ver_num2 > ver_num
+                for b = 1:numel(executable)
+                    path2 = [default_location dir_list(a).name executable{b}];
+                    if exist(path2, 'file') == 2
+                        path_ = path2;
+                        ver_num = ver_num2;
+                    end
+                end
+            end
+        end
+        if check_store_gs_path(path_)
+            return
+        end
+    else
+        executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
+        for a = 1:numel(executable)
+            path_ = executable{a};
+            if check_store_gs_path(path_)
+                return
+            end
+        end
     end
-    executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'};
-    ver_num = 0;
-    % If there are multiple versions, use the newest
-    for a = 1:numel(dir_list)
-        ver_num2 = sscanf(dir_list(a).name, 'gs%g');
-        if ~isempty(ver_num2) && ver_num2 > ver_num
-            for b = 1:numel(executable)
-                path2 = [default_location dir_list(a).name executable{b}];
-                if exist(path2, 'file') == 2
-                    path_ = path2;
-                    ver_num = ver_num2;
+    % Ask the user to enter the path
+    while true
+        if strncmp(computer, 'MAC', 3) % Is a Mac
+            % Give separate warning as the uigetdir dialogue box doesn't have a
+            % title
+            uiwait(warndlg('Ghostscript not found. Please locate the program.'))
+        end
+        base = uigetdir('/', 'Ghostcript not found. Please locate the program.');
+        if isequal(base, 0)
+            % User hit cancel or closed window
+            break;
+        end
+        base = [base filesep]; %#ok<AGROW>
+        bin_dir = {'', ['bin' filesep], ['lib' filesep]};
+        for a = 1:numel(bin_dir)
+            for b = 1:numel(bin)
+                path_ = [base bin_dir{a} bin{b}];
+                if exist(path_, 'file') == 2
+                    if check_store_gs_path(path_)
+                        return
+                    end
                 end
             end
         end
     end
-    if check_store_gs_path(path_)
-        return
+    if ismac
+        error('Ghostscript not found. Have you installed it (http://pages.uoregon.edu/koch)?');
+    else
+        error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
     end
-else
-    executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
-    for a = 1:numel(executable)
-        path_ = executable{a};
-        if check_store_gs_path(path_)
-            return
-        end
-    end
-end
-% Ask the user to enter the path
-while 1
-    if strncmp(computer, 'MAC', 3) % Is a Mac
-        % Give separate warning as the uigetdir dialogue box doesn't have a
-        % title
-        uiwait(warndlg('Ghostscript not found. Please locate the program.'))
-    end
-    base = uigetdir('/', 'Ghostcript not found. Please locate the program.');
-    if isequal(base, 0)
-        % User hit cancel or closed window
-        break;
-    end
-    base = [base filesep];
-    bin_dir = {'', ['bin' filesep], ['lib' filesep]};
-    for a = 1:numel(bin_dir)
-        for b = 1:numel(bin)
-            path_ = [base bin_dir{a} bin{b}];
-            if exist(path_, 'file') == 2
-                if check_store_gs_path(path_)
-                    return
-                end
-            end
-        end
-    end
-end
-error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
 end
 
 function good = check_store_gs_path(path_)
-% Check the path is valid
-good = check_gs_path(path_);
-if ~good
-    return
-end
-% Update the current default path to the path found
-if ~user_string('ghostscript', path_)
-    warning('Path to ghostscript installation could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt'));
-    return
-end
+    % Check the path is valid
+    good = check_gs_path(path_);
+    if ~good
+        return
+    end
+    % Update the current default path to the path found
+    if ~user_string('ghostscript', path_)
+        filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt');
+        warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_);
+        return
+    end
 end
 
 function good = check_gs_path(path_)
-% Check the path is valid
-shell_cmd = '';
-if ismac
-    shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';  % Avoids an error on Mac with GS 9.07
+    persistent isOk
+    if isempty(path_)
+        isOk = false;
+    elseif ~isequal(isOk,true)
+        % Check whether the path is valid
+        [status, message] = system([gs_command(path_) '-h']); %#ok<ASGLU>
+        isOk = status == 0;
+    end
+    good = isOk;
 end
-[good, message] = system(sprintf('%s"%s" -h', shell_cmd, path_));
-good = good == 0;
+
+function cmd = gs_command(path_)
+    % Initialize any required system calls before calling ghostscript
+    % TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh)
+    shell_cmd = '';
+    if isunix
+        shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
+    end
+    if ismac
+        shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';  % Avoids an error on Mac with GS 9.07
+    end
+    % Construct the command string
+    cmd = sprintf('%s"%s" ', shell_cmd, path_);
 end
Index: issm/trunk/externalpackages/export_fig/isolate_axes.m
===================================================================
--- issm/trunk/externalpackages/export_fig/isolate_axes.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/isolate_axes.m	(revision 21341)
@@ -1,2 +1,3 @@
+function fh = isolate_axes(ah, vis)
 %ISOLATE_AXES Isolate the specified axes in a figure on their own
 %
@@ -22,98 +23,108 @@
 
 % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
-% 16/3/2012 Moved copyfig to its own function. Thanks to Bob Fratantonio
-% for pointing out that the function is also used in export_fig.m.
-% 12/12/12 - Add support for isolating uipanels. Thanks to michael for
-% suggesting it.
-% 08/10/13 - Bug fix to allchildren suggested by Will Grant (many thanks!).
-% 05/12/13 - Bug fix to axes having different units. Thanks to Remington
-% Reid for reporting the issue.
+% 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio
+%           for pointing out that the function is also used in export_fig.m
+% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it
+% 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!)
+% 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting
+% 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro
+%           on FEX page as a comment on 24-Apr-2014); standardized indentation & help section
+% 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2
 
-function fh = isolate_axes(ah, vis)
-% Make sure we have an array of handles
-if ~all(ishandle(ah))
-    error('ah must be an array of handles');
-end
-% Check that the handles are all for axes or uipanels, and are all in the same figure
-fh = ancestor(ah(1), 'figure');
-nAx = numel(ah);
-for a = 1:nAx
-    if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})
-        error('All handles must be axes or uipanel handles.');
+    % Make sure we have an array of handles
+    if ~all(ishandle(ah))
+        error('ah must be an array of handles');
     end
-    if ~isequal(ancestor(ah(a), 'figure'), fh)
-        error('Axes must all come from the same figure.');
+    % Check that the handles are all for axes or uipanels, and are all in the same figure
+    fh = ancestor(ah(1), 'figure');
+    nAx = numel(ah);
+    for a = 1:nAx
+        if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})
+            error('All handles must be axes or uipanel handles.');
+        end
+        if ~isequal(ancestor(ah(a), 'figure'), fh)
+            error('Axes must all come from the same figure.');
+        end
     end
-end
-% Tag the objects so we can find them in the copy
-old_tag = get(ah, 'Tag');
-if nAx == 1
-    old_tag = {old_tag};
-end
-set(ah, 'Tag', 'ObjectToCopy');
-% Create a new figure exactly the same as the old one
-fh = copyfig(fh); %copyobj(fh, 0);
-if nargin < 2 || ~vis
-    set(fh, 'Visible', 'off');
-end
-% Reset the object tags
-for a = 1:nAx
-    set(ah(a), 'Tag', old_tag{a});
-end
-% Find the objects to save
-ah = findall(fh, 'Tag', 'ObjectToCopy');
-if numel(ah) ~= nAx
-    close(fh);
-    error('Incorrect number of objects found.');
-end
-% Set the axes tags to what they should be
-for a = 1:nAx
-    set(ah(a), 'Tag', old_tag{a});
-end
-% Keep any legends and colorbars which overlap the subplots
-lh = findall(fh, 'Type', 'axes', '-and', {'Tag', 'legend', '-or', 'Tag', 'Colorbar'});
-nLeg = numel(lh);
-if nLeg > 0
-    set([ah(:); lh(:)], 'Units', 'normalized');
-    ax_pos = get(ah, 'OuterPosition');
-    if nAx > 1
-        ax_pos = cell2mat(ax_pos(:));
+    % Tag the objects so we can find them in the copy
+    old_tag = get(ah, 'Tag');
+    if nAx == 1
+        old_tag = {old_tag};
     end
-    ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);
-    leg_pos = get(lh, 'OuterPosition');
-    if nLeg > 1;
-        leg_pos = cell2mat(leg_pos);
+    set(ah, 'Tag', 'ObjectToCopy');
+    % Create a new figure exactly the same as the old one
+    fh = copyfig(fh); %copyobj(fh, 0);
+    if nargin < 2 || ~vis
+        set(fh, 'Visible', 'off');
     end
-    leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
-    ax_pos = shiftdim(ax_pos, -1);
-    % Overlap test
-    M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
-        bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
-        bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
-        bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
-    ah = [ah; lh(any(M, 2))];
-end
-% Get all the objects in the figure
-axs = findall(fh);
-% Delete everything except for the input objects and associated items
-delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
+    % Reset the object tags
+    for a = 1:nAx
+        set(ah(a), 'Tag', old_tag{a});
+    end
+    % Find the objects to save
+    ah = findall(fh, 'Tag', 'ObjectToCopy');
+    if numel(ah) ~= nAx
+        close(fh);
+        error('Incorrect number of objects found.');
+    end
+    % Set the axes tags to what they should be
+    for a = 1:nAx
+        set(ah(a), 'Tag', old_tag{a});
+    end
+    % Keep any legends and colorbars which overlap the subplots
+    % Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we
+    %       don't test for the type, only the tag (hopefully nobody but Matlab uses them!)
+    lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar');
+    nLeg = numel(lh);
+    if nLeg > 0
+        set([ah(:); lh(:)], 'Units', 'normalized');
+        try
+            ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property
+        catch
+            ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition
+        end
+        if nAx > 1
+            ax_pos = cell2mat(ax_pos(:));
+        end
+        ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);
+        try
+            leg_pos = get(lh, 'OuterPosition');
+        catch
+            leg_pos = get(lh, 'Position');  % No OuterPosition in HG2, only in HG1
+        end
+        if nLeg > 1;
+            leg_pos = cell2mat(leg_pos);
+        end
+        leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
+        ax_pos = shiftdim(ax_pos, -1);
+        % Overlap test
+        M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
+            bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
+            bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
+            bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
+        ah = [ah; lh(any(M, 2))];
+    end
+    % Get all the objects in the figure
+    axs = findall(fh);
+    % Delete everything except for the input objects and associated items
+    delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
 end
 
 function ah = allchildren(ah)
-ah = findall(ah);
-if iscell(ah)
-    ah = cell2mat(ah);
-end
-ah = ah(:);
+    ah = findall(ah);
+    if iscell(ah)
+        ah = cell2mat(ah);
+    end
+    ah = ah(:);
 end
 
 function ph = allancestors(ah)
-ph = [];
-for a = 1:numel(ah)
-    h = get(ah(a), 'parent');
-    while h ~= 0
-        ph = [ph; h];
-        h = get(h, 'parent');
+    ph = [];
+    for a = 1:numel(ah)
+        h = get(ah(a), 'parent');
+        while h ~= 0
+            ph = [ph; h];
+            h = get(h, 'parent');
+        end
     end
 end
-end
Index: issm/trunk/externalpackages/export_fig/pdftops.m
===================================================================
--- issm/trunk/externalpackages/export_fig/pdftops.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/pdftops.m	(revision 21341)
@@ -16,5 +16,5 @@
 %
 % IN:
-%   cmd - Command string to be passed into pdftops.
+%   cmd - Command string to be passed into pdftops (e.g. '-help').
 %
 % OUT:
@@ -24,86 +24,127 @@
 % Copyright: Oliver Woodford, 2009-2010
 
-% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
-% Mac OS.
-% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path
-% under linux.
+% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
+% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path under linux.
 % 23/01/2014 - Add full path to pdftops.txt in warning.
+% 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation
+% 02/05/2016 - Added possible error explanation suggested by Michael Pacer (issue #137)
+% 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)
 
-% Call pdftops
-[varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
+    % Call pdftops
+    [varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
 end
 
 function path_ = xpdf_path
-% Return a valid path
-% Start with the currently set path
-path_ = user_string('pdftops');
-% Check the path works
-if check_xpdf_path(path_)
-    return
-end
-% Check whether the binary is on the path
-if ispc
-    bin = 'pdftops.exe';
-else
-    bin = 'pdftops';
-end
-if check_store_xpdf_path(bin)
-    path_ = bin;
-    return
-end
-% Search the obvious places
-if ispc
-    path_ = 'C:\Program Files\xpdf\pdftops.exe';
-else
-    path_ = '/usr/local/bin/pdftops';
-end
-if check_store_xpdf_path(path_)
-    return
-end
-% Ask the user to enter the path
-while 1
-    if strncmp(computer,'MAC',3) % Is a Mac
-        % Give separate warning as the uigetdir dialogue box doesn't have a
-        % title
-        uiwait(warndlg('Pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/.'))
+    % Return a valid path
+    % Start with the currently set path
+    path_ = user_string('pdftops');
+    % Check the path works
+    if check_xpdf_path(path_)
+        return
     end
-    base = uigetdir('/', 'Pdftops not found. Please locate the program.');
-    if isequal(base, 0)
-        % User hit cancel or closed window
-        break;
+    % Check whether the binary is on the path
+    if ispc
+        bin = 'pdftops.exe';
+    else
+        bin = 'pdftops';
     end
-    base = [base filesep];
-    bin_dir = {'', ['bin' filesep], ['lib' filesep]};
-    for a = 1:numel(bin_dir)
-        path_ = [base bin_dir{a} bin];
-        if exist(path_, 'file') == 2
-            break;
+    if check_store_xpdf_path(bin)
+        path_ = bin;
+        return
+    end
+    % Search the obvious places
+    if ispc
+        paths = {'C:\Program Files\xpdf\pdftops.exe', 'C:\Program Files (x86)\xpdf\pdftops.exe'};
+    else
+        paths = {'/usr/bin/pdftops', '/usr/local/bin/pdftops'};
+    end
+    for a = 1:numel(paths)
+        path_ = paths{a};
+        if check_store_xpdf_path(path_)
+            return
         end
     end
-    if check_store_xpdf_path(path_)
+
+    % 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';
+    fprintf(2, '%s\n', [errMsg1 '<a href="matlab:web(''-browser'',''' url1 ''');">' url1 '</a>']);
+    errMsg1 = [errMsg1 url1];
+    %if strncmp(computer,'MAC',3) % Is a Mac
+    %    % Give separate warning as the MacOS uigetdir dialogue box doesn't have a title
+    %    uiwait(warndlg(errMsg1))
+    %end
+
+    % Provide an alternative possible explanation as per issue #137
+    errMsg2 = 'If you have pdftops installed, perhaps Matlab is shaddowing it as described in ';
+    url2 = 'https://github.com/altmany/export_fig/issues/137';
+    fprintf(2, '%s\n', [errMsg2 '<a href="matlab:web(''-browser'',''' url2 ''');">issue #137</a>']);
+    errMsg2 = [errMsg2 url1];
+
+    state = 0;
+    while 1
+        if state
+            option1 = 'Install pdftops';
+        else
+            option1 = 'Issue #137';
+        end
+        answer = questdlg({errMsg1,'',errMsg2},'Pdftops error',option1,'Locate pdftops','Cancel','Cancel');
+        drawnow;  % prevent a Matlab hang: http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem
+        switch answer
+            case 'Install pdftops'
+                web('-browser',url1);
+            case 'Issue #137'
+                web('-browser',url2);
+                state = 1;
+            case 'Locate pdftops'
+                base = uigetdir('/', errMsg1);
+                if isequal(base, 0)
+                    % User hit cancel or closed window
+                    break
+                end
+                base = [base filesep]; %#ok<AGROW>
+                bin_dir = {'', ['bin' filesep], ['lib' filesep]};
+                for a = 1:numel(bin_dir)
+                    path_ = [base bin_dir{a} bin];
+                    if exist(path_, 'file') == 2
+                        break
+                    end
+                end
+                if check_store_xpdf_path(path_)
+                    return
+                end
+
+            otherwise  % User hit Cancel or closed window
+                break
+        end
+    end
+    error('pdftops executable not found.');
+end
+
+function good = check_store_xpdf_path(path_)
+    % Check the path is valid
+    good = check_xpdf_path(path_);
+    if ~good
+        return
+    end
+    % Update the current default path to the path found
+    if ~user_string('pdftops', path_)
+        warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
         return
     end
 end
-error('pdftops executable not found.');
-end
-
-function good = check_store_xpdf_path(path_)
-% Check the path is valid
-good = check_xpdf_path(path_);
-if ~good
-    return
-end
-% Update the current default path to the path found
-if ~user_string('pdftops', path_)
-    warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
-    return
-end
-end
 
 function good = check_xpdf_path(path_)
-% Check the path is valid
-[good, message] = system(sprintf('"%s" -h', path_));
-% system returns good = 1 even when the command runs
-% Look for something distinct in the help text
-good = ~isempty(strfind(message, 'PostScript'));
+    % Check the path is valid
+    [good, message] = system(sprintf('"%s" -h', path_)); %#ok<ASGLU>
+    % system returns good = 1 even when the command runs
+    % Look for something distinct in the help text
+    good = ~isempty(strfind(message, 'PostScript'));
+
+    % 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
+        fprintf('Error running %s:\n', path_);
+        fprintf(2,'%s\n\n',message);
+    end
 end
Index: issm/trunk/externalpackages/export_fig/print2array.m
===================================================================
--- issm/trunk/externalpackages/export_fig/print2array.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/print2array.m	(revision 21341)
@@ -1,2 +1,3 @@
+function [A, bcol] = print2array(fig, res, renderer, gs_options)
 %PRINT2ARRAY  Exports a figure to an image array
 %
@@ -6,4 +7,5 @@
 %   A = print2array(figure_handle, resolution)
 %   A = print2array(figure_handle, resolution, renderer)
+%   A = print2array(figure_handle, resolution, renderer, gs_options)
 %   [A bcol] = print2array(...)
 %
@@ -20,4 +22,6 @@
 %   renderer - string containing the renderer paramater to be passed to
 %              print. Default: '-opengl'.
+%   gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
+%                multiple options are needed, enclose in call array: {'-a','-b'}
 %
 % OUT:
@@ -25,174 +29,216 @@
 %   bcol - 1x3 uint8 vector of the background color
 
-% Copyright (C) Oliver Woodford 2008-2012
-
+% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
+%{
 % 05/09/11: Set EraseModes to normal when using opengl or zbuffer
-%           renderers. Thanks to Pawel Kocieniewski for reporting the
-%           issue.
-% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting
-%           the issue.
-% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure
-%           size and erasemode settings. Makes it a bit slower, but more
-%           reliable. Thanks to Phil Trinh and Meelis Lootus for reporting
-%           the issues.
+%           renderers. Thanks to Pawel Kocieniewski for reporting the issue.
+% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it.
+% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size
+%           and erasemode settings. Makes it a bit slower, but more reliable.
+%           Thanks to Phil Trinh and Meelis Lootus for reporting the issues.
 % 09/12/11: Pass font path to ghostscript.
 % 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
 %           Ken Campbell for reporting it.
-% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting
-%           it.
+% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it.
 % 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
 %           reporting the issue.
+% 26/02/15: If temp dir is not writable, use the current folder for temp
+%           EPS/TIF files (Javier Paredes)
+% 27/02/15: Display suggested workarounds to internal print() error (issue #16)
+% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
+% 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation
+% 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func)
+% 07/07/15: Fixed issue #83: use numeric handles in HG1
+%}
 
-function [A, bcol] = print2array(fig, res, renderer)
-% Generate default input arguments, if needed
-if nargin < 2
-    res = 1;
-    if nargin < 1
-        fig = gcf;
-    end
-end
-% Warn if output is large
-old_mode = get(fig, 'Units');
-set(fig, 'Units', 'pixels');
-px = get(fig, 'Position');
-set(fig, 'Units', old_mode);
-npx = prod(px(3:4)*res)/1e6;
-if npx > 30
-    % 30M pixels or larger!
-    warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
-end
-% Retrieve the background colour
-bcol = get(fig, 'Color');
-% Set the resolution parameter
-res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
-% Generate temporary file name
-tmp_nam = [tempname '.tif'];
-if nargin > 2 && strcmp(renderer, '-painters')
-    % Print to eps file
-    tmp_eps = [tempname '.eps'];
-    print2eps(tmp_eps, fig, 0, renderer, '-loose');
+    % Generate default input arguments, if needed
+    if nargin < 2
+        res = 1;
+        if nargin < 1
+            fig = gcf;
+        end
+    end
+    % Warn if output is large
+    old_mode = get(fig, 'Units');
+    set(fig, 'Units', 'pixels');
+    px = get(fig, 'Position');
+    set(fig, 'Units', old_mode);
+    npx = prod(px(3:4)*res)/1e6;
+    if npx > 30
+        % 30M pixels or larger!
+        warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
+    end
+    % Retrieve the background colour
+    bcol = get(fig, 'Color');
+    % Set the resolution parameter
+    res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
+    % Generate temporary file name
+    tmp_nam = [tempname '.tif'];
     try
-        % Initialize the command to export to tiff using ghostscript
-        cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
-        % Set the font path
-        fp = font_path();
-        if ~isempty(fp)
-            cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
-        end
-        % Add the filenames
-        cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"'];
-        % Execute the ghostscript command
-        ghostscript(cmd_str);
-    catch me
+        % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
+        fid = fopen(tmp_nam,'w');
+        fwrite(fid,1);
+        fclose(fid);
+        delete(tmp_nam);  % cleanup
+        isTempDirOk = true;
+    catch
+        % Temp dir is not writable, so use the current folder
+        [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
+        fpath = pwd;
+        tmp_nam = fullfile(fpath,[fname fext]);
+        isTempDirOk = false;
+    end
+    % Enable users to specify optional ghostscript options (issue #36)
+    if nargin > 3 && ~isempty(gs_options)
+        if iscell(gs_options)
+            gs_options = sprintf(' %s',gs_options{:});
+        elseif ~ischar(gs_options)
+            error('gs_options input argument must be a string or cell-array of strings');
+        else
+            gs_options = [' ' gs_options];
+        end
+    else
+        gs_options = '';
+    end
+    if nargin > 2 && strcmp(renderer, '-painters')
+        % Print to eps file
+        if isTempDirOk
+            tmp_eps = [tempname '.eps'];
+        else
+            tmp_eps = fullfile(fpath,[fname '.eps']);
+        end
+        print2eps(tmp_eps, fig, 0, renderer, '-loose');
+        try
+            % Initialize the command to export to tiff using ghostscript
+            cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
+            % Set the font path
+            fp = font_path();
+            if ~isempty(fp)
+                cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
+            end
+            % Add the filenames
+            cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options];
+            % Execute the ghostscript command
+            ghostscript(cmd_str);
+        catch me
+            % Delete the intermediate file
+            delete(tmp_eps);
+            rethrow(me);
+        end
         % Delete the intermediate file
         delete(tmp_eps);
-        rethrow(me);
-    end
-    % Delete the intermediate file
-    delete(tmp_eps);
-    % Read in the generated bitmap
-    A = imread(tmp_nam);
-    % Delete the temporary bitmap file
-    delete(tmp_nam);
-    % Set border pixels to the correct colour
-    if isequal(bcol, 'none')
-        bcol = [];
-    elseif isequal(bcol, [1 1 1])
-        bcol = uint8([255 255 255]);
+        % Read in the generated bitmap
+        A = imread(tmp_nam);
+        % Delete the temporary bitmap file
+        delete(tmp_nam);
+        % Set border pixels to the correct colour
+        if isequal(bcol, 'none')
+            bcol = [];
+        elseif isequal(bcol, [1 1 1])
+            bcol = uint8([255 255 255]);
+        else
+            for l = 1:size(A, 2)
+                if ~all(reshape(A(:,l,:) == 255, [], 1))
+                    break;
+                end
+            end
+            for r = size(A, 2):-1:l
+                if ~all(reshape(A(:,r,:) == 255, [], 1))
+                    break;
+                end
+            end
+            for t = 1:size(A, 1)
+                if ~all(reshape(A(t,:,:) == 255, [], 1))
+                    break;
+                end
+            end
+            for b = size(A, 1):-1:t
+                if ~all(reshape(A(b,:,:) == 255, [], 1))
+                    break;
+                end
+            end
+            bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
+            for c = 1:size(A, 3)
+                A(:,[1:l-1, r+1:end],c) = bcol(c);
+                A([1:t-1, b+1:end],:,c) = bcol(c);
+            end
+        end
     else
-        for l = 1:size(A, 2)
-            if ~all(reshape(A(:,l,:) == 255, [], 1))
-                break;
-            end
-        end
-        for r = size(A, 2):-1:l
-            if ~all(reshape(A(:,r,:) == 255, [], 1))
-                break;
-            end
-        end
-        for t = 1:size(A, 1)
-            if ~all(reshape(A(t,:,:) == 255, [], 1))
-                break;
-            end
-        end
-        for b = size(A, 1):-1:t
-            if ~all(reshape(A(b,:,:) == 255, [], 1))
-                break;
-            end
-        end
-        bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
-        for c = 1:size(A, 3)
-            A(:,[1:l-1, r+1:end],c) = bcol(c);
-            A([1:t-1, b+1:end],:,c) = bcol(c);
-        end
-    end
-else
-    if nargin < 3
-        renderer = '-opengl';
-    end
-    err = false;
-    % Set paper size
-    old_pos_mode = get(fig, 'PaperPositionMode');
-    old_orientation = get(fig, 'PaperOrientation');
-    set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
-    try
-        % Print to tiff file
-        print(fig, renderer, res_str, '-dtiff', tmp_nam);
-        % Read in the printed file
-        A = imread(tmp_nam);
-        % Delete the temporary file
-        delete(tmp_nam);
-    catch ex
-        err = true;
-    end
-    % Reset paper size
-    set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
-    % Throw any error that occurred
-    if err
-        rethrow(ex);
-    end
-    % Set the background color
-    if isequal(bcol, 'none')
-        bcol = [];
-    else
-        bcol = bcol * 255;
-        if isequal(bcol, round(bcol))
-            bcol = uint8(bcol);
-        else
-            bcol = squeeze(A(1,1,:));
-        end
-    end
-end
-% Check the output size is correct
-if isequal(res, round(res))
-    px = [px([4 3])*res 3];
-    if ~isequal(size(A), px)
-        % Correct the output size
-        A = A(1:min(end,px(1)),1:min(end,px(2)),:);
-    end
-end
+        if nargin < 3
+            renderer = '-opengl';
+        end
+        err = false;
+        % Set paper size
+        old_pos_mode = get(fig, 'PaperPositionMode');
+        old_orientation = get(fig, 'PaperOrientation');
+        set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
+        try
+            % Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function)
+            fp = [];  % in case we get an error below
+            fp = findall(fig, 'Type','patch', 'LineWidth',0.75);
+            set(fp, 'LineWidth',0.5);
+            % Fix issue #83: use numeric handles in HG1
+            if ~using_hg2(fig),  fig = double(fig);  end
+            % Print to tiff file
+            print(fig, renderer, res_str, '-dtiff', tmp_nam);
+            % Read in the printed file
+            A = imread(tmp_nam);
+            % Delete the temporary file
+            delete(tmp_nam);
+        catch ex
+            err = true;
+        end
+        set(fp, 'LineWidth',0.75);  % restore original figure appearance
+        % Reset paper size
+        set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
+        % Throw any error that occurred
+        if err
+            % Display suggested workarounds to internal print() error (issue #16)
+            fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n');
+            rethrow(ex);
+        end
+        % Set the background color
+        if isequal(bcol, 'none')
+            bcol = [];
+        else
+            bcol = bcol * 255;
+            if isequal(bcol, round(bcol))
+                bcol = uint8(bcol);
+            else
+                bcol = squeeze(A(1,1,:));
+            end
+        end
+    end
+    % Check the output size is correct
+    if isequal(res, round(res))
+        px = round([px([4 3])*res 3]);  % round() to avoid an indexing warning below
+        if ~isequal(size(A), px)
+            % Correct the output size
+            A = A(1:min(end,px(1)),1:min(end,px(2)),:);
+        end
+    end
 end
 
 % Function to return (and create, where necessary) the font path
 function fp = font_path()
-fp = user_string('gs_font_path');
-if ~isempty(fp)
-    return
+    fp = user_string('gs_font_path');
+    if ~isempty(fp)
+        return
+    end
+    % Create the path
+    % Start with the default path
+    fp = getenv('GS_FONTPATH');
+    % Add on the typical directories for a given OS
+    if ispc
+        if ~isempty(fp)
+            fp = [fp ';'];
+        end
+        fp = [fp getenv('WINDIR') filesep 'Fonts'];
+    else
+        if ~isempty(fp)
+            fp = [fp ':'];
+        end
+        fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
+    end
+    user_string('gs_font_path', fp);
 end
-% Create the path
-% Start with the default path
-fp = getenv('GS_FONTPATH');
-% Add on the typical directories for a given OS
-if ispc
-    if ~isempty(fp)
-        fp = [fp ';'];
-    end
-    fp = [fp getenv('WINDIR') filesep 'Fonts'];
-else
-    if ~isempty(fp)
-        fp = [fp ':'];
-    end
-    fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
-end
-user_string('gs_font_path', fp);
-end
Index: issm/trunk/externalpackages/export_fig/print2eps.m
===================================================================
--- issm/trunk/externalpackages/export_fig/print2eps.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/print2eps.m	(revision 21341)
@@ -1,2 +1,3 @@
+function print2eps(name, fig, export_options, varargin)
 %PRINT2EPS  Prints figures to eps with improved line styles
 %
@@ -4,13 +5,12 @@
 %   print2eps filename
 %   print2eps(filename, fig_handle)
-%   print2eps(filename, fig_handle, bb_padding)
-%   print2eps(filename, fig_handle, bb_padding, options)
+%   print2eps(filename, fig_handle, export_options)
+%   print2eps(filename, fig_handle, export_options, print_options)
 %
 % This function saves a figure as an eps file, with two improvements over
 % MATLAB's print command. First, it improves the line style, making dashed
-% lines more like those on screen and giving grid lines their own dotted
-% style. Secondly, it substitutes original font names back into the eps
-% file, where these have been changed by MATLAB, for up to 11 different
-% fonts.
+% lines more like those on screen and giving grid lines a dotted line style.
+% Secondly, it substitutes original font names back into the eps file,
+% where these have been changed by MATLAB, for up to 11 different fonts.
 %
 %IN:
@@ -20,10 +20,17 @@
 %              not specified, the figure is saved in the current directory.
 %   fig_handle - The handle of the figure to be saved. Default: gcf().
-%   bb_padding - Scalar value of amount of padding to add to border around
-%                the figure, in points. Can be negative as well as
-%                positive. Default: 0.
-%   options - Additional parameter strings to be passed to print.
-
-% Copyright (C) Oliver Woodford 2008-2014
+%   export_options - array or struct of optional scalar values:
+%       bb_padding - Scalar value of amount of padding to add to border around
+%                    the cropped image, in points (if >1) or percent (if <1).
+%                    Can be negative as well as positive; Default: 0
+%       crop       - Cropping flag. Deafult: 0
+%       fontswap   - Whether to swap non-default fonts in figure. Default: true
+%       renderer   - Renderer used to generate bounding-box. Default: 'opengl'
+%       crop_amounts - 4-element vector of crop amounts: [top,right,bottom,left]
+%                    (available only via the struct alternative)
+%   print_options - Additional parameter strings to be passed to the print command
+
+%{
+% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
 
 % The idea of editing the EPS file to change line styles comes from Jiro
@@ -31,8 +38,9 @@
 % The idea of changing dash length with line width came from comments on
 % fex id: 5743, but the implementation is mine :)
-
-% 14/11/2011: Fix a MATLAB bug rendering black or white text incorrectly.
-%             Thanks to Mathieu Morlighem for reporting the issue and
-%             obtaining a fix from TMW.
+%}
+%{
+% 14/11/11: Fix a MATLAB bug rendering black or white text incorrectly.
+%           Thanks to Mathieu Morlighem for reporting the issue and
+%           obtaining a fix from TMW.
 % 08/12/11: Added ability to correct fonts. Several people have requested
 %           this at one time or another, and also pointed me to printeps
@@ -57,157 +65,465 @@
 %           issue.
 % 13/08/13: Fix MATLAB feature of not exporting white lines correctly.
-%           Thanks to Sebastian Heßlinger for reporting it.
-
-function print2eps(name, fig, bb_padding, varargin)
-options = {'-depsc2'};
-if nargin > 3
-    options = [options varargin];
-elseif nargin < 3
-    bb_padding = 0;
-    if nargin < 2
-        fig = gcf();
-    end
+%           Thanks to Sebastian Hesslinger for reporting it.
+% 24/02/15: Fix for Matlab R2014b bug (issue #31): LineWidths<0.75 are not
+%           set in the EPS (default line width is used)
+% 25/02/15: Fixed issue #32: BoundingBox problem caused uncropped EPS/PDF files
+% 05/03/15: Fixed issue #43: Inability to perform EPS file post-processing
+% 06/03/15: Improved image padding & cropping thanks to Oscar Hartogensis
+% 21/03/15: Fixed edge-case of missing handles having a 'FontName' property
+% 26/03/15: Attempt to fix issue #45: white lines in subplots do not print correctly
+% 27/03/15: Attempt to fix issue #44: white artifact lines appearing in patch exports
+% 30/03/15: Fixed issue #52: improved performance on HG2 (R2014b+)
+% 09/04/15: Comment blocks consolidation and minor code cleanup (no real code change)
+% 12/04/15: Fixed issue #56: bad cropping
+% 14/04/15: Workaround for issue #45: lines in image subplots are exported in invalid color
+% 07/07/15: Added option to avoid font-swapping in EPS/PDF
+% 07/07/15: Fixed issue #83: use numeric handles in HG1
+% 22/07/15: Fixed issue #91 (thanks to Carlos Moffat)
+% 28/09/15: Fixed issue #108 (thanks to JacobD10)
+% 01/11/15: Fixed issue #112: optional renderer for bounding-box computation (thanks to Jesús Pestana Puerta)
+% 21/02/16: Enabled specifying non-automated crop amounts
+% 22/02/16: Better support + backward compatibility for transparency (issue #108)
+% 10/06/16: Fixed issue #159: text handles get cleared by Matlab in the print() command
+% 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
+%}
+
+    options = {'-loose'};
+    if nargin > 3
+        options = [options varargin];
+    elseif nargin < 3
+        export_options = 0;
+        if nargin < 2
+            fig = gcf();
+        end
+    end
+
+    % Retrieve padding, crop & font-swap values
+    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
+        if renderer(1)~='-',  renderer = ['-' renderer];  end
+    else
+        if numel(export_options) > 2  % font-swapping
+            fontswap = export_options(3);
+        else
+            fontswap = true;
+        end
+        if numel(export_options) > 1  % cropping
+            bb_crop = export_options(2);
+        else
+            bb_crop = 0;  % scalar value, so use default bb_crop value of 0
+        end
+        if numel(export_options) > 0  % padding
+            bb_padding = export_options(1);
+        else
+            bb_padding = 0;
+        end
+        renderer = '-opengl';
+    end
+
+    % Construct the filename
+    if numel(name) < 5 || ~strcmpi(name(end-3:end), '.eps')
+        name = [name '.eps']; % Add the missing extension
+    end
+
+    % Set paper size
+    old_pos_mode = get(fig, 'PaperPositionMode');
+    old_orientation = get(fig, 'PaperOrientation');
+    set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
+
+    % Find all the used fonts in the figure
+    font_handles = findall(fig, '-property', 'FontName');
+    fonts = get(font_handles, 'FontName');
+    if isempty(fonts)
+        fonts = {};
+    elseif ~iscell(fonts)
+        fonts = {fonts};
+    end
+
+    % Map supported font aliases onto the correct name
+    fontsl = lower(fonts);
+    for a = 1:numel(fonts)
+        f = fontsl{a};
+        f(f==' ') = [];
+        switch f
+            case {'times', 'timesnewroman', 'times-roman'}
+                fontsl{a} = 'times-roman';
+            case {'arial', 'helvetica'}
+                fontsl{a} = 'helvetica';
+            case {'newcenturyschoolbook', 'newcenturyschlbk'}
+                fontsl{a} = 'newcenturyschlbk';
+            otherwise
+        end
+    end
+    fontslu = unique(fontsl);
+
+    % Determine the font swap table
+    if fontswap
+        matlab_fonts = {'Helvetica', 'Times-Roman', 'Palatino', 'Bookman', 'Helvetica-Narrow', 'Symbol', ...
+                        'AvantGarde', 'NewCenturySchlbk', 'Courier', 'ZapfChancery', 'ZapfDingbats'};
+        matlab_fontsl = lower(matlab_fonts);
+        require_swap = find(~ismember(fontslu, matlab_fontsl));
+        unused_fonts = find(~ismember(matlab_fontsl, fontslu));
+        font_swap = cell(3, min(numel(require_swap), numel(unused_fonts)));
+        fonts_new = fonts;
+        for a = 1:size(font_swap, 2)
+            font_swap{1,a} = find(strcmp(fontslu{require_swap(a)}, fontsl));
+            font_swap{2,a} = matlab_fonts{unused_fonts(a)};
+            font_swap{3,a} = fonts{font_swap{1,a}(1)};
+            fonts_new(font_swap{1,a}) = font_swap(2,a);
+        end
+    else
+        font_swap = [];
+    end
+
+    % Swap the fonts
+    if ~isempty(font_swap)
+        fonts_size = get(font_handles, 'FontSize');
+        if iscell(fonts_size)
+            fonts_size = cell2mat(fonts_size);
+        end
+        M = false(size(font_handles));
+
+        % Loop because some changes may not stick first time, due to listeners
+        c = 0;
+        update = zeros(1000, 1);
+        for b = 1:10 % Limit number of loops to avoid infinite loop case
+            for a = 1:numel(M)
+                M(a) = ~isequal(get(font_handles(a), 'FontName'), fonts_new{a}) || ~isequal(get(font_handles(a), 'FontSize'), fonts_size(a));
+                if M(a)
+                    set(font_handles(a), 'FontName', fonts_new{a}, 'FontSize', fonts_size(a));
+                    c = c + 1;
+                    update(c) = a;
+                end
+            end
+            if ~any(M)
+                break;
+            end
+        end
+
+        % Compute the order to revert fonts later, without the need of a loop
+        [update, M] = unique(update(1:c));
+        [M, M] = sort(M);
+        update = reshape(update(M), 1, []);
+    end
+
+    % MATLAB bug fix - black and white text can come out inverted sometimes
+    % Find the white and black text
+    black_text_handles = findall(fig, 'Type', 'text', 'Color', [0 0 0]);
+    white_text_handles = findall(fig, 'Type', 'text', 'Color', [1 1 1]);
+    % Set the font colors slightly off their correct values
+    set(black_text_handles, 'Color', [0 0 0] + eps);
+    set(white_text_handles, 'Color', [1 1 1] - eps);
+
+    % MATLAB bug fix - white lines can come out funny sometimes
+    % Find the white lines
+    white_line_handles = findall(fig, 'Type', 'line', 'Color', [1 1 1]);
+    % Set the line color slightly off white
+    set(white_line_handles, 'Color', [1 1 1] - 0.00001);
+
+    % Workaround for issue #45: lines in image subplots are exported in invalid color
+    % In this case the -depsc driver solves the problem, but then all the other workarounds
+    % below (for all the other issues) will fail, so it's better to let the user decide by
+    % just issuing a warning and accepting the '-depsc' input parameter
+    epsLevel2 = ~any(strcmpi(options,'-depsc'));
+    if epsLevel2
+        % Use -depsc2 (EPS color level-2) if -depsc (EPS color level-3) was not specifically requested
+        options{end+1} = '-depsc2';
+        % Issue a warning if multiple images & lines were found in the figure, and HG1 with painters renderer is used
+        isPainters = any(strcmpi(options,'-painters'));
+        if isPainters && ~using_hg2 && numel(findall(fig,'Type','image'))>1 && ~isempty(findall(fig,'Type','line'))
+            warning('YMA:export_fig:issue45', ...
+                    ['Multiple images & lines detected. In such cases, the lines might \n' ...
+                     'appear with an invalid color due to an internal MATLAB bug (fixed in R2014b). \n' ...
+                     'Possible workaround: add a ''-depsc'' or ''-opengl'' parameter to the export_fig command.']);
+        end
+    end
+
+    % Fix issue #83: use numeric handles in HG1
+    if ~using_hg2(fig),  fig = double(fig);  end
+
+    % Workaround for when transparency is lost through conversion fig>EPS>PDF (issue #108)
+    % Replace transparent patch RGB values with an ID value (rare chance that ID color is being used already)
+    if using_hg2
+        origAlphaColors = eps_maintainAlpha(fig);
+    end
+
+    % Print to eps file
+    print(fig, options{:}, name);
+
+    % Do post-processing on the eps file
+    try
+        % Read the EPS file into memory
+        fstrm = read_write_entire_textfile(name);
+    catch
+        fstrm = '';
+    end
+
+    % Restore colors for transparent patches/lines and apply the
+    % setopacityalpha setting in the EPS file (issue #108)
+    if using_hg2
+        [~,fstrm,foundFlags] = eps_maintainAlpha(fig, fstrm, origAlphaColors);
+
+        % If some of the transparencies were not found in the EPS file, then rerun the
+        % export with only the found transparencies modified (backward compatibility)
+        if ~isempty(fstrm) && ~all(foundFlags)
+            foundIdx = find(foundFlags);
+            for objIdx = 1 : sum(foundFlags)
+                colorsIdx = foundIdx(objIdx);
+                colorsData = origAlphaColors{colorsIdx};
+                hObj     = colorsData{1};
+                propName = colorsData{2};
+                newColor = colorsData{4};
+                hObj.(propName).ColorData = newColor;
+            end
+            delete(name);
+            print(fig, options{:}, name);
+            fstrm = read_write_entire_textfile(name);
+            [~,fstrm] = eps_maintainAlpha(fig, fstrm, origAlphaColors(foundFlags));
+        end
+    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)
+            % Convert miter joins to line joins
+            %fstrm = regexprep(fstrm, '\n10.0 ML\n', '\n1 LJ\n');
+            % This is faster (the original regexprep could take many seconds when the axes contains many lines):
+            fstrm = strrep(fstrm, sprintf('\n10.0 ML\n'), sprintf('\n1 LJ\n'));
+
+            % In HG2, grid lines and axes Ruler Axles have a default LineWidth of 0.5 => replace en-bulk (assume that 1.0 LineWidth = 1.333 LW)
+            %   hAxes=gca; hAxes.YGridHandle.LineWidth, hAxes.YRuler.Axle.LineWidth
+            %fstrm = regexprep(fstrm, '(GC\n2 setlinecap\n1 LJ)\nN', '$1\n0.667 LW\nN');
+            % This is faster:
+            fstrm = strrep(fstrm, sprintf('GC\n2 setlinecap\n1 LJ\nN'), sprintf('GC\n2 setlinecap\n1 LJ\n0.667 LW\nN'));
+
+            % This is more accurate but *MUCH* slower (issue #52)
+            %{
+            % Modify all thin lines in the figure to have 10x LineWidths
+            hLines = findall(fig,'Type','line');
+            hThinLines = [];
+            for lineIdx = 1 : numel(hLines)
+                thisLine = hLines(lineIdx);
+                if thisLine.LineWidth < 0.75 && strcmpi(thisLine.Visible,'on')
+                    hThinLines(end+1) = thisLine; %#ok<AGROW>
+                    thisLine.LineWidth = thisLine.LineWidth * 10;
+                end
+            end
+
+            % If any thin lines were found
+            if ~isempty(hThinLines)
+                % Prepare an EPS with large-enough line widths
+                print(fig, options{:}, name);
+                % Restore the original LineWidths in the figure
+                for lineIdx = 1 : numel(hThinLines)
+                    thisLine = handle(hThinLines(lineIdx));
+                    thisLine.LineWidth = thisLine.LineWidth / 10;
+                end
+
+                % Compare the original and the new EPS files and correct the original stream's LineWidths
+                fstrm_new = read_write_entire_textfile(name);
+                idx = 500;  % skip heading with its possibly-different timestamp
+                markerStr = sprintf('10.0 ML\nN');
+                markerLen = length(markerStr);
+                while ~isempty(idx) && idx < length(fstrm)
+                    lastIdx = min(length(fstrm), length(fstrm_new));
+                    delta = fstrm(idx+1:lastIdx) - fstrm_new(idx+1:lastIdx);
+                    idx = idx + find(delta,1);
+                    if ~isempty(idx) && ...
+                            isequal(fstrm(idx-markerLen+1:idx), markerStr) && ...
+                            ~isempty(regexp(fstrm_new(idx-markerLen+1:idx+12),'10.0 ML\n[\d\.]+ LW\nN')) %#ok<RGXP1>
+                        value = str2double(regexprep(fstrm_new(idx:idx+12),' .*',''));
+                        if isnan(value), break; end  % something's wrong... - bail out
+                        newStr = sprintf('%0.3f LW\n',value/10);
+                        fstrm = [fstrm(1:idx-1) newStr fstrm(idx:end)];
+                        idx = idx + 12;
+                    else
+                        break;
+                    end
+                end
+            end
+            %}
+
+            % This is much faster although less accurate: fix all non-gray lines to have a LineWidth of 0.75 (=1 LW)
+            % Note: This will give incorrect LineWidth of 075 for lines having LineWidth<0.75, as well as for non-gray grid-lines (if present)
+            %       However, in practice these edge-cases are very rare indeed, and the difference in LineWidth should not be noticeable
+            %fstrm = regexprep(fstrm, '([CR]C\n2 setlinecap\n1 LJ)\nN', '$1\n1 LW\nN');
+            % This is faster (the original regexprep could take many seconds when the axes contains many lines):
+            fstrm = strrep(fstrm, sprintf('\n2 setlinecap\n1 LJ\nN'), sprintf('\n2 setlinecap\n1 LJ\n1 LW\nN'));
+        end
+    catch err
+        fprintf(2, 'Error fixing LineWidths in EPS file: %s\n at %s:%d\n', err.message, err.stack(1).file, err.stack(1).line);
+    end
+
+    % Reset the font and line colors
+    try
+        set(black_text_handles, 'Color', [0 0 0]);
+        set(white_text_handles, 'Color', [1 1 1]);
+    catch
+        % Fix issue #159: redo findall() '*text_handles'
+        black_text_handles = findall(fig, 'Type', 'text', 'Color', [0 0 0]+eps);
+        white_text_handles = findall(fig, 'Type', 'text', 'Color', [1 1 1]-eps);
+        set(black_text_handles, 'Color', [0 0 0]);
+        set(white_text_handles, 'Color', [1 1 1]);
+    end
+    set(white_line_handles, 'Color', [1 1 1]);
+
+    % Reset paper size
+    set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
+
+    % Reset the font names in the figure
+    if ~isempty(font_swap)
+        for a = update
+            set(font_handles(a), 'FontName', fonts{a}, 'FontSize', fonts_size(a));
+        end
+    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})));
+        end
+    end
+
+    % Move the bounding box to the top of the file (HG2 only), or fix the line styles (HG1 only)
+    if using_hg2(fig)
+        % Move the bounding box to the top of the file (HG2 only)
+        [s, e] = regexp(fstrm, '%%BoundingBox: [^%]*%%');
+        if numel(s) == 2
+            fstrm = fstrm([1:s(1)-1 s(2):e(2)-2 e(1)-1:s(2)-1 e(2)-1:end]);
+        end
+    else
+        % Fix the line styles (HG1 only)
+        fstrm = fix_lines(fstrm);
+    end
+
+    % Apply the bounding box padding & cropping, replacing Matlab's print()'s bounding box
+    if bb_crop
+        % Calculate a new bounding box based on a bitmap print using crop_border.m
+        % 1. Determine the Matlab BoundingBox and PageBoundingBox
+        [s,e] = regexp(fstrm, '%%BoundingBox: [^%]*%%'); % location BB in eps file
+        if numel(s)==2, s=s(2); e=e(2); end
+        aa = fstrm(s+15:e-3); % dimensions bb - STEP1
+        bb_matlab = cell2mat(textscan(aa,'%f32%f32%f32%f32'));  % dimensions bb - STEP2
+
+        [s,e] = regexp(fstrm, '%%PageBoundingBox: [^%]*%%'); % location bb in eps file
+        if numel(s)==2, s=s(2); e=e(2); end
+        aa = fstrm(s+19:e-3); % dimensions bb - STEP1
+        pagebb_matlab = cell2mat(textscan(aa,'%f32%f32%f32%f32'));  % dimensions bb - STEP2
+
+        % 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);
+
+        % 3. Calculate the new Bounding Box
+        pagew = pagebb_matlab(3)-pagebb_matlab(1);
+        pageh = pagebb_matlab(4)-pagebb_matlab(2);
+        %bb_new = [pagebb_matlab(1)+pagew*bb_rel(1) pagebb_matlab(2)+pageh*bb_rel(2) ...
+        %          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
+
+        % Apply the bounding box padding
+        if bb_padding
+            if abs(bb_padding)<1
+                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);
+        else
+            add_padding = @(n1, n2, n3, n4) sprintf(' %d', str2double({n1, n2, n3, n4}) + bb_offset); % fix small but noticeable bounding box shift
+        end
+        fstrm = regexprep(fstrm, '%%BoundingBox:[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)', '%%BoundingBox:${add_padding($1, $2, $3, $4)}');
+    end
+
+    % Fix issue #44: white artifact lines appearing in patch exports
+    % Note: the problem is due to the fact that Matlab's print() function exports patches
+    %       as a combination of filled triangles, and a white line appears where the triangles touch
+    % In the workaround below, we will modify such dual-triangles into a filled rectangle.
+    % We are careful to only modify regexps that exactly match specific patterns - it's better to not
+    % correct some white-line artifacts than to change the geometry of a patch, or to corrupt the EPS.
+    %   e.g.: '0 -450 937 0 0 450 3 MP PP 937 0 0 -450 0 450 3 MP PP' => '0 -450 937 0 0 450 0 0 4 MP'
+    fstrm = regexprep(fstrm, '\n([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) 3 MP\nPP\n\2 \1 \3 3 MP\nPP\n','\n$1 $2 $3 0 0 4 MP\nPP\n');
+    fstrm = regexprep(fstrm, '\n([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) 3 MP\nPP\n\2 \3 \1 3 MP\nPP\n','\n$1 $2 $3 0 0 4 MP\nPP\n');
+    fstrm = regexprep(fstrm, '\n([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) 3 MP\nPP\n\3 \1 \2 3 MP\nPP\n','\n$1 $2 $3 0 0 4 MP\nPP\n');
+    fstrm = regexprep(fstrm, '\n([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) 3 MP\nPP\n\3 \2 \1 3 MP\nPP\n','\n$1 $2 $3 0 0 4 MP\nPP\n');
+
+    % Write out the fixed eps file
+    read_write_entire_textfile(name, fstrm);
 end
-% Construct the filename
-if numel(name) < 5 || ~strcmpi(name(end-3:end), '.eps')
-    name = [name '.eps']; % Add the missing extension
+
+function [StoredColors, fstrm, foundFlags] = eps_maintainAlpha(fig, fstrm, StoredColors)
+    if nargin == 1  % in: convert transparency in Matlab figure into unique RGB colors
+        hObjs = findall(fig); %findobj(fig,'Type','Area');
+        StoredColors = {};
+        propNames = {'Face','Edge'};
+        for objIdx = 1:length(hObjs)
+            hObj = hObjs(objIdx);
+            for propIdx = 1 : numel(propNames)
+                try
+                    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;
+                    end
+                catch
+                    % Never mind - ignore (either doesn't have the property or cannot change it)
+                end
+            end
+        end
+    else  % restore transparency in Matlab figure by converting back from the unique RGBs
+        %Find the transparent patches
+        wasError = false;
+        nColors = length(StoredColors);
+        foundFlags = false(1,nColors);
+        for objIdx = 1 : nColors
+            colorsData = StoredColors{objIdx};
+            hObj      = colorsData{1};
+            propName  = colorsData{2};
+            origColor = colorsData{3};
+            newColor  = colorsData{4};
+            try
+                %Restore the EPS files patch color
+                colorID   = num2str(round(double(newColor(1:3)') /255,3),'%.3g %.3g %.3g'); %ID for searching
+                origRGB   = num2str(round(double(origColor(1:3)')/255,3),'%.3g %.3g %.3g'); %Replace with original color
+                origAlpha = num2str(round(double(origColor(end)) /255,3),'%.3g'); %Convert alpha value for EPS
+
+                %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']);
+                else  %'Edge'
+                    oldStr = sprintf(['\n' colorID ' RC\n1 LJ\n']);
+                    newStr = sprintf(['\n' origRGB ' RC\n' origAlpha ' .setopacityalpha true\n']);
+                end
+                foundFlags(objIdx) = ~isempty(strfind(fstrm, oldStr));
+                fstrm = strrep(fstrm, oldStr, newStr);
+
+                %Restore the figure object's original color
+                hObj.(propName).ColorData = origColor;
+            catch err
+                % something is wrong - cannot restore transparent color...
+                if ~wasError
+                    fprintf(2, 'Error maintaining transparency in EPS file: %s\n at %s:%d\n', err.message, err.stack(1).file, err.stack(1).line);
+                    wasError = true;
+                end
+            end
+        end
+    end
 end
-% Set paper size
-old_pos_mode = get(fig, 'PaperPositionMode');
-old_orientation = get(fig, 'PaperOrientation');
-set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
-% Find all the used fonts in the figure
-font_handles = findall(fig, '-property', 'FontName');
-fonts = get(font_handles, 'FontName');
-if ~iscell(fonts)
-    fonts = {fonts};
-end
-% Map supported font aliases onto the correct name
-fontsl = lower(fonts);
-for a = 1:numel(fonts)
-    f = fontsl{a};
-    f(f==' ') = [];
-    switch f
-        case {'times', 'timesnewroman', 'times-roman'}
-            fontsl{a} = 'times-roman';
-        case {'arial', 'helvetica'}
-            fontsl{a} = 'helvetica';
-        case {'newcenturyschoolbook', 'newcenturyschlbk'}
-            fontsl{a} = 'newcenturyschlbk';
-        otherwise
-    end
-end
-fontslu = unique(fontsl);
-% Determine the font swap table
-matlab_fonts = {'Helvetica', 'Times-Roman', 'Palatino', 'Bookman', 'Helvetica-Narrow', 'Symbol', ...
-                'AvantGarde', 'NewCenturySchlbk', 'Courier', 'ZapfChancery', 'ZapfDingbats'};
-matlab_fontsl = lower(matlab_fonts);
-require_swap = find(~ismember(fontslu, matlab_fontsl));
-unused_fonts = find(~ismember(matlab_fontsl, fontslu));
-font_swap = cell(3, min(numel(require_swap), numel(unused_fonts)));
-fonts_new = fonts;
-for a = 1:size(font_swap, 2)
-    font_swap{1,a} = find(strcmp(fontslu{require_swap(a)}, fontsl));
-    font_swap{2,a} = matlab_fonts{unused_fonts(a)};
-    font_swap{3,a} = fonts{font_swap{1,a}(1)};
-    fonts_new(font_swap{1,a}) = {font_swap{2,a}};
-end
-% Swap the fonts
-if ~isempty(font_swap)
-    fonts_size = get(font_handles, 'FontSize');
-    if iscell(fonts_size)
-        fonts_size = cell2mat(fonts_size);
-    end
-    M = false(size(font_handles));
-    % Loop because some changes may not stick first time, due to listeners
-    c = 0;
-    update = zeros(1000, 1);
-    for b = 1:10 % Limit number of loops to avoid infinite loop case
-        for a = 1:numel(M)
-            M(a) = ~isequal(get(font_handles(a), 'FontName'), fonts_new{a}) || ~isequal(get(font_handles(a), 'FontSize'), fonts_size(a));
-            if M(a)
-                set(font_handles(a), 'FontName', fonts_new{a}, 'FontSize', fonts_size(a));
-                c = c + 1;
-                update(c) = a;
-            end
-        end
-        if ~any(M)
-            break;
-        end
-    end
-    % Compute the order to revert fonts later, without the need of a loop
-    [update, M] = unique(update(1:c));
-    [M, M] = sort(M);
-    update = reshape(update(M), 1, []);
-end
-% MATLAB bug fix - black and white text can come out inverted sometimes
-% Find the white and black text
-white_text_handles = findobj(fig, 'Type', 'text');
-M = get(white_text_handles, 'Color');
-if iscell(M)
-    M = cell2mat(M);
-end
-M = sum(M, 2);
-black_text_handles = white_text_handles(M == 0);
-white_text_handles = white_text_handles(M == 3);
-% Set the font colors slightly off their correct values
-set(black_text_handles, 'Color', [0 0 0] + eps);
-set(white_text_handles, 'Color', [1 1 1] - eps);
-% MATLAB bug fix - white lines can come out funny sometimes
-% Find the white lines
-white_line_handles = findobj(fig, 'Type', 'line');
-M = get(white_line_handles, 'Color');
-if iscell(M)
-    M = cell2mat(M);
-end
-white_line_handles = white_line_handles(sum(M, 2) == 3);
-% Set the line color slightly off white
-set(white_line_handles, 'Color', [1 1 1] - 0.00001);
-% Print to eps file
-print(fig, options{:}, name);
-% Reset the font and line colors
-set(black_text_handles, 'Color', [0 0 0]);
-set(white_text_handles, 'Color', [1 1 1]);
-set(white_line_handles, 'Color', [1 1 1]);
-% Reset paper size
-set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
-% Reset the font names in the figure
-if ~isempty(font_swap)
-    for a = update
-        set(font_handles(a), 'FontName', fonts{a}, 'FontSize', fonts_size(a));
-    end
-end
-% Do post-processing on the eps file
-try
-    fstrm = read_write_entire_textfile(name);
-catch
-    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})));
-    end
-end
-if using_hg2(fig)
-    % Convert miter joins to line joins
-    fstrm = regexprep(fstrm, '10.0 ML\n', '1 LJ\n');
-    % Move the bounding box to the top of the file
-    [s, e] = regexp(fstrm, '%%BoundingBox: [\w\s()]*%%');
-    if numel(s) == 2
-        fstrm = fstrm([1:s(1)-1 s(2):e(2)-2 e(1)-1:s(2)-1 e(2)-1:end]);
-    end
-else
-    % Fix the line styles
-    fstrm = fix_lines(fstrm);
-end
-% Apply the bounding box padding
-if bb_padding
-    add_padding = @(n1, n2, n3, n4) sprintf(' %d', str2double({n1, n2, n3, n4}) + [-bb_padding -bb_padding bb_padding bb_padding]);
-    fstrm = regexprep(fstrm, '%%BoundingBox:[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)', '%%BoundingBox:${add_padding($1, $2, $3, $4)}');
-end
-% Write out the fixed eps file
-read_write_entire_textfile(name, fstrm);
-end
Index: issm/trunk/externalpackages/export_fig/user_string.m
===================================================================
--- issm/trunk/externalpackages/export_fig/user_string.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/user_string.m	(revision 21341)
@@ -1,23 +1,26 @@
+function string = user_string(string_name, string)
 %USER_STRING  Get/set a user specific string
 %
 % Examples:
-%   string = user_string(string_name)
-%   saved = user_string(string_name, new_string)
+%   string  = user_string(string_name)
+%   isSaved = user_string(string_name, new_string)
 %
 % Function to get and set a string in a system or user specific file. This
 % enables, for example, system specific paths to binaries to be saved.
 %
+% The specified string will be saved in a file named <string_name>.txt,
+% either in a subfolder named .ignore under this file's folder, or in the
+% user's prefdir folder (in case this file's folder is non-writable).
+%
 % IN:
-%   string_name - String containing the name of the string required. The
-%                 string is extracted from a file called (string_name).txt,
-%                 stored in the same directory as user_string.m.
-%   new_string - The new string to be saved under the name given by
-%                string_name.
+%   string_name - String containing the name of the string required, which
+%                 sets the filename storing the string: <string_name>.txt
+%   new_string  - The new string to be saved in the <string_name>.txt file
 %
 % OUT:
-%   string - The currently saved string. Default: ''.
-%   saved - Boolean indicating whether the save was succesful
+%   string  - The currently saved string. Default: ''
+%   isSaved - Boolean indicating whether the save was succesful
 
-% Copyright (C) Oliver Woodford 2011-2013
+% Copyright (C) Oliver Woodford 2011-2014, Yair Altman 2015-
 
 % This method of saving paths avoids changing .m files which might be in a
@@ -28,60 +31,75 @@
 
 % 10/01/2013 - Access files in text, not binary mode, as latter can cause
-% errors. Thanks to Christian for pointing this out.
+%              errors. Thanks to Christian for pointing this out.
+% 29/05/2015 - Save file in prefdir if current folder is non-writable (issue #74)
 
-function string = user_string(string_name, string)
-if ~ischar(string_name)
-    error('string_name must be a string.');
-end
-% Create the full filename
-string_name = fullfile(fileparts(mfilename('fullpath')), '.ignore', [string_name '.txt']);
-if nargin > 1
-    % Set string
-    if ~ischar(string)
-        error('new_string must be a string.');
+    if ~ischar(string_name)
+        error('string_name must be a string.');
     end
-    % Make sure the save directory exists
-    dname = fileparts(string_name);
-    if ~exist(dname, 'dir')
-        % Create the directory
-        try
-            if ~mkdir(dname)                
+    % Create the full filename
+    fname = [string_name '.txt'];
+    dname = fullfile(fileparts(mfilename('fullpath')), '.ignore');
+    file_name = fullfile(dname, fname);
+    if nargin > 1
+        % Set string
+        if ~ischar(string)
+            error('new_string must be a string.');
+        end
+        % Make sure the save directory exists
+        %dname = fileparts(file_name);
+        if ~exist(dname, 'dir')
+            % Create the directory
+            try
+                if ~mkdir(dname)
+                    string = false;
+                    return
+                end
+            catch
                 string = false;
                 return
             end
+            % Make it hidden
+            try
+                fileattrib(dname, '+h');
+            catch
+            end
+        end
+        % Write the file
+        fid = fopen(file_name, 'wt');
+        if fid == -1
+            % file cannot be created/updated - use prefdir if file does not already exist
+            % (if file exists but is simply not writable, don't create a duplicate in prefdir)
+            if ~exist(file_name,'file')
+                file_name = fullfile(prefdir, fname);
+                fid = fopen(file_name, 'wt');
+            end
+            if fid == -1
+                string = false;
+                return;
+            end
+        end
+        try
+            fprintf(fid, '%s', string);
         catch
+            fclose(fid);
             string = false;
             return
         end
-        % Make it hidden
-        try
-            fileattrib(dname, '+h');
-        catch
+        fclose(fid);
+        string = true;
+    else
+        % Get string
+        fid = fopen(file_name, 'rt');
+        if fid == -1
+            % file cannot be read, try to read the file in prefdir
+            file_name = fullfile(prefdir, fname);
+            fid = fopen(file_name, 'rt');
+            if fid == -1
+                string = '';
+                return
+            end
         end
+        string = fgetl(fid);
+        fclose(fid);
     end
-    % Write the file
-    fid = fopen(string_name, 'wt');
-    if fid == -1
-        string = false;
-        return
-    end
-    try
-        fprintf(fid, '%s', string);
-    catch
-        fclose(fid);
-        string = false;
-        return
-    end
-    fclose(fid);
-    string = true;
-else
-    % Get string
-    fid = fopen(string_name, 'rt');
-    if fid == -1
-        string = '';
-        return
-    end
-    string = fgetl(fid);
-    fclose(fid);
 end
-end
Index: issm/trunk/externalpackages/export_fig/using_hg2.m
===================================================================
--- issm/trunk/externalpackages/export_fig/using_hg2.m	(revision 19105)
+++ issm/trunk/externalpackages/export_fig/using_hg2.m	(revision 21341)
@@ -1,3 +1,3 @@
-%USING_HG2 Determine if the HG2 graphics pipeline is used
+%USING_HG2 Determine if the HG2 graphics engine is used
 %
 %   tf = using_hg2(fig)
@@ -7,12 +7,30 @@
 %
 %OUT:
-%   tf - boolean indicating whether the HG2 graphics pipeline is being used
+%   tf - boolean indicating whether the HG2 graphics engine is being used
 %        (true) or not (false).
 
+% 19/06/2015 - Suppress warning in R2015b; cache result for improved performance
+% 06/06/2016 - Fixed issue #156 (bad return value in R2016b)
+
 function tf = using_hg2(fig)
-try
-    tf = ~graphicsversion(fig, 'handlegraphics');
-catch
-    tf = false;
+    persistent tf_cached
+    if isempty(tf_cached)
+        try
+            if nargin < 1,  fig = figure('visible','off');  end
+            oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval');
+            try
+                % This generates a [supressed] warning in R2015b:
+                tf = ~graphicsversion(fig, 'handlegraphics');
+            catch
+                tf = ~verLessThan('matlab','8.4');  % =R2014b
+            end
+            warning(oldWarn);
+        catch
+            tf = false;
+        end
+        if nargin < 1,  delete(fig);  end
+        tf_cached = tf;
+    else
+        tf = tf_cached;
+    end
 end
-end
