Index: /issm/trunk-jpl/externalpackages/export_fig/LICENSE
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/LICENSE	(revision 18904)
+++ /issm/trunk-jpl/externalpackages/export_fig/LICENSE	(revision 18904)
@@ -0,0 +1,27 @@
+Copyright (c) 2014, Oliver J. Woodford
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+  list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+  this list of conditions and the following disclaimer in the documentation
+  and/or other materials provided with the distribution.
+
+* Neither the name of the {organization} nor the names of its
+  contributors may be used to endorse or promote products derived from
+  this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Index: /issm/trunk-jpl/externalpackages/export_fig/README.md
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/README.md	(revision 18904)
+++ /issm/trunk-jpl/externalpackages/export_fig/README.md	(revision 18904)
@@ -0,0 +1,259 @@
+export_fig
+==========
+
+A toolbox for exporting figures from MATLAB to standard image and document formats nicely.
+
+### Overview
+Exporting a figure from MATLAB the way you want it (hopefully the way it looks on screen), can be a real headache for the unitiated, thanks to all the settings that are required, and also due to some eccentricities (a.k.a. features and bugs) of functions such as `print`. The first goal of export_fig is to make transferring a plot from screen to document, just the way you expect (again, assuming that's as it appears on screen), a doddle.
+  
+The second goal is to make the output media suitable for publication, allowing you to publish your results in the full glory that you originally intended. This includes embedding fonts, setting image compression levels (including lossless), anti-aliasing, cropping, setting the colourspace, alpha-blending and getting the right resolution.
+
+Perhaps the best way to demonstrate what export_fig can do is with some examples.
+  
+### Examples
+**Visual accuracy** - MATLAB's exporting functions, namely `saveas` and `print`, change many visual properties of a figure, such as size, axes limits and ticks, and background colour, in unexpected and unintended ways. Export_fig aims to faithfully reproduce the figure as it appears on screen. For example:  
+```Matlab
+plot(cos(linspace(0, 7, 1000)));
+set(gcf, 'Position', [100 100 150 150]);
+saveas(gcf, 'test.png');
+export_fig test2.png
+```
+generates the following:
+
+| Figure: | test.png: | test2.png: |
+|:-------:|:---------:|:----------:|
+|![](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:
+```Matlab
+set(gcf, 'Color', 'w');
+```
+  
+Notice also that export_fig crops and anti-aliases (smooths, for bitmaps only) the output by default. However, these options can be disabled; see the Tips section below for details.
+  
+**Resolution** - by default, export_fig exports bitmaps at screen resolution. However, you may wish to save them at a different resolution. You can do this using either of two options: `-m<val>`, where <val> is a positive real number, magnifies the figure by the factor <val> for export, e.g. `-m2` produces an image double the size (in pixels) of the on screen figure; `-r<val>`, again where <val> is a positive real number, specifies the output bitmap to have <val> pixels per inch, the dimensions of the figure (in inches) being those of the on screen figure. For example, using:  
+```Matlab
+export_fig test.png -m2.5
+```
+on the figure from the example above generates:
+
+![](https://farm4.staticflickr.com/3937/15591910915_dc7040c477_o_d.png)
+
+Sometimes you might have a figure with an image in. For example:
+```Matlab
+imshow(imread('cameraman.tif'))
+hold on
+plot(0:255, sin(linspace(0, 10, 256))*127+128);
+set(gcf, 'Position', [100 100 150 150]);
+```
+generates this figure:
+
+![](https://farm4.staticflickr.com/3942/15589249581_ff87a56a3f_o_d.png)
+  
+Here the image is displayed in the figure at resolution lower than its native resolution. However, you might want to export the figure at a resolution such that the image is output at its native (i.e. original) size (in pixels). Ordinarily this would require some non-trivial computation to work out what that resolution should be, but export_fig has an option to do this for you. Using:
+```Matlab
+export_fig test.png -native
+```
+produces:
+
+![](https://farm6.staticflickr.com/5604/15589249591_da2b2652e4_o_d.png)
+
+with the image being the size (in pixels) of the original image. Note that if you want an image to be a particular size, in pixels, in the output (other than its original size) then you can resize it to this size and use the `-native` option to achieve this.
+
+All resolution options (`-m<val>`, `-q<val>` and `-native`) correctly set the resolution information in PNG and TIFF files, as if the image were the dimensions of the on screen figure.
+
+**Shrinking dots & dashes** - when exporting figures with dashed or dotted lines using either the ZBuffer or OpenGL (default for bitmaps) renderers, the dots and dashes can appear much shorter, even non-existent, in the output file, especially if the lines are thick and/or the resolution is high. For example:  
+```Matlab
+plot(sin(linspace(0, 10, 1000)), 'b:', 'LineWidth', 4);
+hold on
+plot(cos(linspace(0, 7, 1000)), 'r--', 'LineWidth', 3);
+grid on
+export_fig test.png
+```
+generates:
+
+![](https://farm4.staticflickr.com/3956/15592747732_f943d4aa0a_o_d.png)
+
+This problem can be overcome by using the painters renderer. For example:
+```Matlab
+export_fig test.png -painters
+```
+used on the same figure generates:
+
+![](https://farm4.staticflickr.com/3945/14971168504_77692f11f5_o_d.png)
+
+Note that not only are the plot lines correct, but the grid lines are too.
+
+**Transparency** - sometimes you might want a figure and axes' backgrounds to be transparent, so that you can see through them to a document (for example a presentation slide, with coloured or textured background) that the exported figure is placed in. To achieve this, first (optionally) set the axes' colour to 'none' prior to exporting, using:  
+```Matlab
+set(gca, 'Color', 'none'); % Sets axes background
+```
+    
+then use export_fig's `-transparent` option when exporting:
+```Matlab
+export_fig test.png -transparent
+```
+
+This will make the background transparent in PDF, EPS and PNG outputs. You can additionally save fully alpha-blended semi-transparent patch objects to the PNG format. For example:
+
+```Matlab
+logo;
+alpha(0.5);
+```
+
+generates a figure like this:
+
+![](https://farm4.staticflickr.com/3933/15405290339_b08de33528_o_d.png)
+
+If you then export this to PNG using the `-transparent` option you can then put the resulting image into, for example, a presentation slide with fancy, textured background, like so:
+
+![](https://farm6.staticflickr.com/5599/15406302920_59beaefff1_o_d.png)
+
+and the image blends seamlessly with the background.
+
+**Image quality** - when publishing images of your results, you want them to look as good as possible. By default, when outputting to lossy file formats (PDF, EPS and JPEG), export_fig uses a high quality setting, i.e. low compression, for images, so little information is lost. This is in contrast to MATLAB's print and saveas functions, whose default quality settings are poor. For example:
+```Matlab
+A = im2double(imread('peppers.png'));
+B = randn(ceil(size(A, 1)/6), ceil(size(A, 2)/6), 3) * 0.1;
+B = cat(3, kron(B(:,:,1), ones(6)), kron(B(:,:,2), ones(6)), kron(B(:,:,3), ones(6)));
+B = A + B(1:size(A, 1),1:size(A, 2),:);
+imshow(B);
+print -dpdf test.pdf
+```
+generates a PDF file, a sub-window of which looks (when zoomed in) like this:
+
+![](https://farm6.staticflickr.com/5613/15405290309_881b2774d6_o_d.png)
+
+while the command
+
+```Matlab
+export_fig test.pdf
+```
+on the same figure produces this:
+
+![](https://farm4.staticflickr.com/3947/14971168174_687473133f_o_d.png)
+
+While much better, the image still contains some compression artifacts (see the low level noise around the edge of the pepper). You may prefer to export with no artifacts at all, i.e. lossless compression. Alternatively, you might need a smaller file, and be willing to accept more compression. Either way, export_fig has an option that can suit your needs: `-q<val>`, where <val> is a number from 0-100, will set the level of lossy image compression (again in PDF, EPS and JPEG outputs only; other formats are lossless), from high compression (0) to low compression/high quality (100). If you want lossless compression in any of those formats then specify a <val> greater than 100. For example:
+```Matlab
+export_fig test.pdf -q101
+```
+again on the same figure, produces this:
+
+![](https://farm6.staticflickr.com/5608/15405803908_934512c1fe_o_d.png)
+
+Notice that all the noise has gone.
+
+### Tips
+**Anti-aliasing** - the anti-aliasing which export_fig applies to bitmap outputs by default makes the images look nice, but it can also blur images and increase exporting time and memory requirements, so you might not always want it. You can set the level of anti-aliasing by using the `-a<val>` option, where <val> is 1 (no anti-aliasing), 2, 3 (default) or 4 (maximum anti-aliasing).  
+  
+**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.
+
+**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:
+```Matlab
+export_fig ../subdir/fig.png;
+export_fig('C:/Users/Me/Documents/figures/myfig', '-pdf', '-png');
+```
+
+**Variable file names** - often you might want to save a series of figures in a for loop, each with a different name. For this you can use the functional form of input arguments, i.e. `export_fig(arg1, arg2)`,  and construct the filename string in a variable. Here's an example of this:  
+```Matlab
+for a = 1:5
+    plot(rand(5, 2));
+    export_fig(sprintf('plot%d.png', a));
+end
+```
+When using the functional form like this, be sure to put string variables in quotes:
+```Matlab
+export_fig(sprintf('plot%d', a), '-a1', '-pdf', '-png');
+```
+
+**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');
+```
+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');
+```
+
+**Multiple formats** - save time by exporting to multiple formats simultaneously. E.g.: 
+```Matlab
+export_fig filename -pdf -eps -png -jpg -tiff
+```
+
+**Other file formats** - if you'd like to save your figure to a bitmap format that is not supported by export_fig, e.g. animated GIF, PPM file or a frame in a movie, then you can use export_fig to output the image, and optionally an alpha-matte, to the workspace. E.g.:  
+```Matlab
+frame = export_fig;
+```
+or
+```Matlab
+[frame, alpha] = export_fig;
+```
+These variables can then be saved to other image formats using other functions, such as imwrite.
+
+**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)).  
+  
+**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`.  
+  
+**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:  
+```Matlab
+set(figure_handle, 'Renderer', 'opengl');
+```
+After matching the two renderers, if the artifact appears in the on screen figure then you'll need to fix that before exporting. Alternatively you can try changing the renderer used by export_fig. Finally check that it isn't one of the known issues mentioned in the section below.
+
+**Smoothed/interpolated images in output PDF** - if you produce a PDF using export_fig and images in the PDF look overly smoothed or interpolated, this is because the software you are using to view the PDF is smoothing or interpolating the image data. The image is not smoothed in the PDF file itself. If the software has an option to disable this feature, you should select it. Alternatively, use another PDF viewer that doesn't exhibit this problem.  
+  
+**Locating Ghostscript/pdftops** - You may find a dialogue box appears when using export_fig, asking you to locate either [Ghostscript](http://www.ghostscript.com) or [pdftops](http://www.foolabs.com/xpdf). These are separate applications which export_fig requires to perform certain functions. If such a dialogue appears it is because export_fig can't find the application automatically. This is because you either haven't installed it, or it isn't in the normal place. Make sure you install the applications correctly first. They can be downloaded from the following places:  
+ 1. Ghostscript:     [www.ghostscript.com](http://www.ghostscript.com)
+ 2. pdftops (install the Xpdf package): [www.foolabs.com/xpdf](http://www.foolabs.com/xpdf)
+
+If you choose to install them in a non-default location then point export_fig
+to this location using the dialogue box.
+
+**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'.
+```
+then you are missing one or more of the files that come in the export_fig package. Make sure that you click the "Get from GitHub" button at the top-right of the download [page](http://www.mathworks.co.uk/matlabcentral/fileexchange/23629-exportfig), then extract all the files in the zip file to the same directory. You should then have all the necessary files.
+  
+### 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.  
+
+**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).  
+  
+**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.  
+  
+**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.  
+  
+**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.  
+  
+### Raising issues
+If you think you have found a genuine error or issue with export_fig **that is not listed above**, first ensure that the figure looks correct on screen when rendered using the renderer that export_fig is set to use (e.g. if exporting to PDF or EPS, does the figure look correct on screen using the painters renderer, or if exporting to bitmap, does the figure look correct on screen using the OpenGL renderer?). If it looks wrong then the problem is there, and I cannot help (other than to suggest you try exporting using a different renderer).
+
+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.
+
+### And finally...
+
+![](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.
+
Index: /issm/trunk-jpl/externalpackages/export_fig/append_pdfs.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/append_pdfs.m	(revision 18904)
+++ /issm/trunk-jpl/externalpackages/export_fig/append_pdfs.m	(revision 18904)
@@ -0,0 +1,58 @@
+%APPEND_PDFS Appends/concatenates multiple PDF files
+%
+% Example:
+%   append_pdfs(output, input1, input2, ...)
+%   append_pdfs(output, input_list{:})
+%   append_pdfs test.pdf temp1.pdf temp2.pdf
+%
+% This function appends multiple PDF files to an existing PDF file, or
+% concatenates them into a PDF file if the output file doesn't yet exist.
+%
+% This function requires that you have ghostscript installed on your
+% system. Ghostscript can be downloaded from: http://www.ghostscript.com
+%
+% IN:
+%    output - string of output file name (including the extension, .pdf).
+%             If it exists it is appended to; if not, it is created.
+%    input1 - string of an input file name (including the extension, .pdf).
+%             All input files are appended in order.
+%    input_list - cell array list of input file name strings. All input
+%                 files are appended in order.
+
+% Copyright: Oliver Woodford, 2011
+
+% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in
+% one go is much faster than appending them one at a time.
+
+% Thanks to Michael Teo for reporting the issue of a too long command line.
+% Issue resolved on 5/5/2011, by passing gs a command file.
+
+% Thanks to Martin Wittmann for pointing out the quality issue when
+% appending multiple bitmaps.
+% Issue resolved (to best of my ability) 1/6/2011, using the prepress
+% setting
+
+function append_pdfs(varargin)
+% Are we appending or creating a new file
+append = exist(varargin{1}, 'file') == 2;
+if append
+    output = [tempname '.pdf'];
+else
+    output = varargin{1};
+    varargin = varargin(2:end);
+end
+% Create the command file
+cmdfile = [tempname '.txt'];
+fh = fopen(cmdfile, 'w');
+fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
+fprintf(fh, ' "%s"', varargin{:});
+fclose(fh);
+% Call ghostscript
+ghostscript(['@"' cmdfile '"']);
+% Delete the command file
+delete(cmdfile);
+% Rename the file if needed
+if append
+    movefile(output, varargin{1});
+end
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/copyfig.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/copyfig.m	(revision 18903)
+++ /issm/trunk-jpl/externalpackages/export_fig/copyfig.m	(revision 18904)
@@ -21,5 +21,5 @@
 end
 % Is there a legend?
-if isempty(findobj(fh, 'Type', 'axes', 'Tag', 'legend'))
+if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'))
     % Safe to copy using copyobj
     fh = copyobj(fh, 0);
@@ -31,3 +31,3 @@
     delete(tmp_nam);
 end
-return
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/crop_borders.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/crop_borders.m	(revision 18904)
+++ /issm/trunk-jpl/externalpackages/export_fig/crop_borders.m	(revision 18904)
@@ -0,0 +1,81 @@
+%CROP_BORDERS Crop the borders of an image or stack of images
+%
+%   [B, v] = 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.
+%
+%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),:,:).
+
+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;
+        end
+    end
+    if bail
+        break;
+    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;
+        end
+    end
+    if bail
+        break;
+    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;
+        end
+    end
+    if bail
+        break;
+    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),:,:);
+end
+
+function A = col(A)
+A = A(:);
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/eps2pdf.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/eps2pdf.m	(revision 18903)
+++ /issm/trunk-jpl/externalpackages/export_fig/eps2pdf.m	(revision 18904)
@@ -84,9 +84,9 @@
     try
         % Convert to pdf using ghostscript
-        [status message] = ghostscript(options);
-    catch
+        [status, message] = ghostscript(options);
+    catch me
         % Delete the intermediate file
         delete(tmp_nam);
-        rethrow(lasterror);
+        rethrow(me);
     end
     % Delete the intermediate file
@@ -97,5 +97,5 @@
     options = [options ' -f "' source '"'];
     % Convert to pdf using ghostscript
-    [status message] = ghostscript(options);
+    [status, message] = ghostscript(options);
 end
 % Check for error
@@ -108,5 +108,5 @@
     end
 end
-return
+end
 
 % Function to return (and create, where necessary) the font path
@@ -132,3 +132,3 @@
 end
 user_string('gs_font_path', fp);
-return
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/export_fig.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/export_fig.m	(revision 18903)
+++ /issm/trunk-jpl/externalpackages/export_fig/export_fig.m	(revision 18904)
@@ -13,4 +13,5 @@
 %   export_fig ... -a<val>
 %   export_fig ... -q<val>
+%   export_fig ... -p<val>
 %   export_fig ... -<renderer>
 %   export_fig ... -<colorspace>
@@ -85,11 +86,11 @@
 %                  made transparent (png, pdf and eps output only).
 %   -m<val> - option where val indicates the factor to magnify the
-%             on-screen figure dimensions by when generating bitmap
+%             on-screen figure pixel dimensions by when generating bitmap
 %             outputs. Default: '-m1'.
 %   -r<val> - option val indicates the resolution (in pixels per inch) to
-%             export bitmap outputs at, keeping the dimensions of the
-%             on-screen figure. Default: sprintf('-r%g', get(0,
-%             'ScreenPixelsPerInch')). Note that the -m and -r options
-%             change the same property.
+%             export bitmap and vector outputs at, keeping the dimensions
+%             of the on-screen figure. Default: '-r864' (for vector output
+%             only). Note that the -m option overides the -r option for
+%             bitmap outputs only.
 %   -native - option indicating that the output resolution (when outputting
 %             a bitmap format) should be such that the vertical resolution
@@ -118,4 +119,7 @@
 %             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).
 %   -append - option indicating that if the file (pdfs only) already
 %             exists, the figure is to be appended as a new page, instead
@@ -133,9 +137,9 @@
 %
 %   Some helpful examples and tips can be found at:
-%      http://sites.google.com/site/oliverwoodford/software/export_fig
+%      https://github.com/ojwoodford/export_fig
 %
 %   See also PRINT, SAVEAS.
 
-% Copyright (C) Oliver Woodford 2008-2012
+% Copyright (C) Oliver Woodford 2008-2014
 
 % The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG
@@ -168,4 +172,8 @@
 % 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)
@@ -217,5 +225,8 @@
 end
 % Set all axes limit and tick modes to manual, so the limits and ticks can't change
-set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual', 'XTickMode', 'manual', 'YTickMode', 'manual', 'ZTickMode', 'manual');
+set(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');
@@ -289,5 +300,5 @@
         % Crop the background
         if options.crop
-            [alpha, v] = crop_background(alpha, 0);
+            [alpha, v] = crop_borders(alpha, 0, 1);
             A = A(v(1):v(2),v(3):v(4),:);
         end
@@ -336,5 +347,5 @@
         % Crop the background
         if options.crop
-            A = crop_background(A, tcol);
+            A = crop_borders(A, tcol, 1);
         end
         % Downscale the image
@@ -406,5 +417,5 @@
     end
     % Generate the options for print
-    p2eArgs = {renderer};
+    p2eArgs = {renderer, sprintf('-r%d', options.resolution)};
     if options.colourspace == 1
         p2eArgs = [p2eArgs {'-cmyk'}];
@@ -415,8 +426,8 @@
     try
         % Generate an eps
-        print2eps(tmp_nam, fig, p2eArgs{:});
+        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);
+            eps_remove_background(tmp_nam, 1 + using_hg2(fig));
         end
         % Add a bookmark to the PDF if desired
@@ -465,5 +476,5 @@
     end
 end
-return
+end
 
 function [fig, options] = parse_args(nout, varargin)
@@ -485,6 +496,8 @@
                  'im', nout == 1, ...
                  'alpha', nout == 2, ...
-                 'aa_factor', 3, ...
-                 'magnify', 1, ...
+                 'aa_factor', 0, ...
+                 'bb_padding', 0, ...
+                 'magnify', [], ...
+                 'resolution', [], ...
                  'bookmark', false, ...
                  'quality', []);
@@ -535,5 +548,5 @@
                     native = true;
                 otherwise
-                    val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q))(\d*\.)?\d+(e-?\d+)?', 'match'));
+                    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});
@@ -543,7 +556,9 @@
                             options.magnify = val;
                         case 'r'
-                            options.magnify = val ./ get(0, 'ScreenPixelsPerInch');
+                            options.resolution = val;
                         case 'q'
                             options.quality = max(val, 0);
+                        case 'p'
+                            options.bb_padding = val;
                     end
             end
@@ -573,4 +588,26 @@
 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)
@@ -584,5 +621,5 @@
 
 % Check whether transparent background is wanted (old way)
-if isequal(get(ancestor(fig, 'figure'), 'Color'), 'none')
+if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none')
     options.transparent = true;
 end
@@ -632,5 +669,5 @@
     end
 end
-return
+end
 
 function A = downsize(A, factor)
@@ -659,9 +696,9 @@
     A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);
 end
-return
+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));
-return
+end
 
 function A = check_greyscale(A)
@@ -672,67 +709,7 @@
     A = A(:,:,1); % Save only one channel for 8-bit output
 end
-return
-
-function [A, v] = crop_background(A, bcol)
-% Map the foreground pixels
-[h, w, c] = size(A);
-if isscalar(bcol) && c > 1
-    bcol = bcol(ones(1, c));
-end
-bail = false;
-for l = 1:w
-    for a = 1:c
-        if ~all(A(:,l,a) == bcol(a))
-            bail = true;
-            break;
-        end
-    end
-    if bail
-        break;
-    end
-end
-bail = false;
-for r = w:-1:l
-    for a = 1:c
-        if ~all(A(:,r,a) == bcol(a))
-            bail = true;
-            break;
-        end
-    end
-    if bail
-        break;
-    end
-end
-bail = false;
-for t = 1:h
-    for a = 1:c
-        if ~all(A(t,:,a) == bcol(a))
-            bail = true;
-            break;
-        end
-    end
-    if bail
-        break;
-    end
-end
-bail = false;
-for b = h:-1:t
-    for a = 1:c
-        if ~all(A(b,:,a) == bcol(a))
-            bail = true;
-            break;
-        end
-    end
-    if bail
-        break;
-    end
-end
-% Crop the background, leaving one boundary pixel to avoid bleeding on
-% resize
-v = [max(t-1, 1) min(b+1, h) max(l-1, 1) min(r+1, w)];
-A = A(v(1):v(2),v(3):v(4),:);
-return
-
-function eps_remove_background(fname)
+end
+
+function eps_remove_background(fname, count)
 % Remove the background of an eps file
 % Open the file
@@ -742,5 +719,5 @@
 end
 % Read the file line by line
-while true
+while count
     % Get the next line
     l = fgets(fh);
@@ -749,23 +726,24 @@
     end
     % Check if the line contains the background rectangle
-    if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +rf *[\n\r]+', 'start'), 1)
+    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);
-        break;
+        % Reduce the count
+        count = count - 1;
     end
 end
 % Close the file
 fclose(fh);
-return
+end
 
 function b = isvector(options)
 b = options.pdf || options.eps;
-return
+end
 
 function b = isbitmap(options)
 b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
-return
+end
 
 % Helper function
@@ -774,5 +752,5 @@
     A = {A};
 end
-return
+end
 
 function add_bookmark(fname, bookmark_text)
@@ -808,3 +786,14 @@
 end
 fclose(fh);
-return
+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-jpl/externalpackages/export_fig/fix_lines.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/fix_lines.m	(revision 18903)
+++ /issm/trunk-jpl/externalpackages/export_fig/fix_lines.m	(revision 18904)
@@ -1,3 +1,2 @@
-function fix_lines(fname, fname2)
 %FIX_LINES  Improves the line style of eps files generated by print
 %
@@ -5,4 +4,5 @@
 %   fix_lines fname
 %   fix_lines fname fname2
+%   fstrm_out = fixlines(fstrm_in)
 %
 % This function improves the style of lines in eps files generated by
@@ -16,9 +16,13 @@
 % information.
 %
-% IN:
+%IN:
 %   fname - Name or path of source eps file.
 %   fname2 - Name or path of destination eps file. Default: same as fname.
+%   fstrm_in - File contents of a MATLAB-generated eps file.
+%
+%OUT:
+%   fstrm_out - Contents of the eps file with line styles fixed.
 
-% Copyright: (C) Oliver Woodford, 2008-2010
+% Copyright: (C) Oliver Woodford, 2008-2014
 
 % The idea of editing the EPS file to change line styles comes from Jiro
@@ -34,16 +38,14 @@
 % opened.
 
-% Read in the file
-fh = fopen(fname, 'r');
-if fh == -1
-    error('File %s not found.', fname);
+function fstrm = fix_lines(fstrm, fname2)
+
+if nargout == 0 || nargin > 1
+    if nargin < 2
+        % Overwrite the input file
+        fname2 = fstrm;
+    end
+    % Read in the file
+    fstrm = read_write_entire_textfile(fstrm);
 end
-try
-    fstrm = fread(fh, '*char')';
-catch ex
-    fclose(fh);
-    rethrow(ex);
-end
-fclose(fh);
 
 % Move any embedded fonts after the postscript header
@@ -51,5 +53,5 @@
     % Find the start and end of the header
     ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
-    [ind2 ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
+    [ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
     % Put the header first
     if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
@@ -67,5 +69,5 @@
 ind = sort(ind);
 % Find line width commands
-[ind2 ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
+[ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
 % Go through each line style section and swap with any line width commands
 % near by
@@ -114,6 +116,6 @@
 % Isolate line style definition section
 first_sec = strfind(fstrm, '% line types:');
-[second_sec remaining] = strtok(fstrm(first_sec+1:end), '/');
-[remaining remaining] = strtok(remaining, '%');
+[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
+[remaining, remaining] = strtok(remaining, '%');
 
 % Define the new styles, including the new GR format
@@ -132,23 +134,10 @@
              '/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
 
-if nargin < 2
-    % Overwrite the input file
-    fname2 = fname;
+% Construct the output
+fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
+
+% Write the output file
+if nargout == 0 || nargin > 1
+    read_write_entire_textfile(fname2, fstrm);
 end
-
-% Save the file with the section replaced
-fh = fopen(fname2, 'w');
-if fh == -1
-    error('Unable to open %s for writing.', fname2);
 end
-try
-    fwrite(fh, fstrm(1:first_sec), 'char*1');
-    fwrite(fh, second_sec, 'char*1');
-    fprintf(fh, '%s\r', new_style{:});
-    fwrite(fh, remaining, 'char*1');
-catch ex
-    fclose(fh);
-    rethrow(ex);
-end
-fclose(fh);
-return
Index: /issm/trunk-jpl/externalpackages/export_fig/ghostscript.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/ghostscript.m	(revision 18903)
+++ /issm/trunk-jpl/externalpackages/export_fig/ghostscript.m	(revision 18904)
@@ -20,5 +20,5 @@
 %   result - Output from ghostscript.
 
-% Copyright: Oliver Woodford, 2009-2010
+% Copyright: Oliver Woodford, 2009-2013
 
 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
@@ -32,9 +32,23 @@
 % 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', gs_path, cmd));
-return
+[varargout{1:nargout}] = system(sprintf('%s"%s" %s', shell_cmd, gs_path, cmd));
+end
 
 function path_ = gs_path
@@ -85,7 +99,7 @@
     end
 else
-    bin = {'/usr/bin/gs', '/usr/local/bin/gs'};
-    for a = 1:numel(bin)
-        path_ = bin{a};
+    executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
+    for a = 1:numel(executable)
+        path_ = executable{a};
         if check_store_gs_path(path_)
             return
@@ -119,4 +133,5 @@
 end
 error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
+end
 
 function good = check_store_gs_path(path_)
@@ -128,12 +143,16 @@
 % 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 ghostscript.txt.');
+    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
-return
+end
 
 function good = check_gs_path(path_)
 % Check the path is valid
-[good, message] = system(sprintf('"%s" -h', path_));
+shell_cmd = '';
+if ismac
+    shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';  % Avoids an error on Mac with GS 9.07
+end
+[good, message] = system(sprintf('%s"%s" -h', shell_cmd, path_));
 good = good == 0;
-return
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/im2gif.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/im2gif.m	(revision 18904)
+++ /issm/trunk-jpl/externalpackages/export_fig/im2gif.m	(revision 18904)
@@ -0,0 +1,186 @@
+%IM2GIF Convert a multiframe image to an animated GIF file
+%
+% Examples:
+%   im2gif infile
+%   im2gif infile outfile
+%   im2gif(A, outfile)
+%   im2gif(..., '-nocrop')
+%   im2gif(..., '-nodither')
+%   im2gif(..., '-ncolors', n)
+%   im2gif(..., '-loops', n)
+%   im2gif(..., '-delay', n) 
+%   
+% This function converts a multiframe image to an animated GIF.
+%
+% To create an animation from a series of figures, export to a multiframe
+% TIFF file using export_fig, then convert to a GIF, as follows:
+%
+%    for a = 2 .^ (3:6)
+%       peaks(a);
+%       export_fig test.tif -nocrop -append
+%    end
+%    im2gif('test.tif', '-delay', 0.5);
+%
+%IN:
+%   infile - string containing the name of the input image.
+%   outfile - string containing the name of the output image (must have the
+%             .gif extension). Default: infile, with .gif extension.
+%   A - HxWxCxN array of input images, stacked along fourth dimension, to
+%       be converted to gif.
+%   -nocrop - option indicating that the borders of the output are not to
+%             be cropped.
+%   -nodither - option indicating that dithering is not to be used when
+%               converting the image.
+%   -ncolors - option pair, the value of which indicates the maximum number
+%              of colors the GIF can have. This can also be a quantization
+%              tolerance, between 0 and 1. Default/maximum: 256.
+%   -loops - option pair, the value of which gives the number of times the
+%            animation is to be looped. Default: 65535.
+%   -delay - option pair, the value of which gives the time, in seconds,
+%            between frames. Default: 1/15.
+
+% Copyright (C) Oliver Woodford 2011
+
+function im2gif(A, varargin)
+
+% Parse the input arguments
+[A, options] = parse_args(A, varargin{:});
+
+if options.crop ~= 0
+    % Crop
+    A = crop_borders(A, A(ceil(end/2),1,:,1));
+end
+
+% Convert to indexed image
+[h, w, c, n] = size(A);
+A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
+map = unique(reshape(A, h*w*n, c), 'rows');
+if size(map, 1) > 256
+    dither_str = {'dither', 'nodither'};
+    dither_str = dither_str{1+(options.dither==0)};
+    if options.ncolors <= 1
+        [B, map] = rgb2ind(A, options.ncolors, dither_str);
+        if size(map, 1) > 256
+            [B, map] = rgb2ind(A, 256, dither_str);
+        end
+    else
+        [B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
+    end
+else
+    if max(map(:)) > 1
+        map = double(map) / 255;
+        A = double(A) / 255;
+    end
+    B = rgb2ind(im2double(A), map);
+end
+B = reshape(B, h, w, 1, n);
+
+% Bug fix to rgb2ind
+map(B(1)+1,:) = im2double(A(1,1,:));
+
+% Save as a gif
+imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
+end
+
+%% Parse the input arguments
+function [A, options] = parse_args(A, varargin)
+% Set the defaults
+options = struct('outfile', '', ...
+                 'dither', true, ...
+                 'crop', true, ...
+                 'ncolors', 256, ...
+                 'loops', 65535, ...
+                 'delay', 1/15);
+
+% Go through the arguments
+a = 0;
+n = numel(varargin);
+while a < n
+    a = a + 1;
+    if ischar(varargin{a}) && ~isempty(varargin{a})
+        if varargin{a}(1) == '-'
+            opt = lower(varargin{a}(2:end));
+            switch opt
+                case 'nocrop'
+                    options.crop = false;
+                case 'nodither'
+                    options.dither = false;
+                otherwise
+                    if ~isfield(options, opt)
+                        error('Option %s not recognized', varargin{a});
+                    end
+                    a = a + 1;
+                    if ischar(varargin{a}) && ~ischar(options.(opt))
+                        options.(opt) = str2double(varargin{a});
+                    else
+                        options.(opt) = varargin{a};
+                    end
+            end
+        else
+            options.outfile = varargin{a};
+        end
+    end
+end
+
+if isempty(options.outfile)
+    if ~ischar(A)
+        error('No output filename given.');
+    end
+    % Generate the output filename from the input filename
+    [path, outfile] = fileparts(A);
+    options.outfile = fullfile(path, [outfile '.gif']);
+end
+
+if ischar(A)
+    % Read in the image
+    A = imread_rgb(A);
+end
+end
+
+%% Read image to uint8 rgb array
+function [A, alpha] = imread_rgb(name)
+% Get file info
+info = imfinfo(name);
+% Special case formats
+switch lower(info(1).Format)
+    case 'gif'
+        [A, map] = imread(name, 'frames', 'all');
+        if ~isempty(map)
+            map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
+            A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
+            A = permute(A, [1 2 5 4 3]);
+        end
+    case {'tif', 'tiff'}
+        A = cell(numel(info), 1);
+        for a = 1:numel(A)
+            [A{a}, map] = imread(name, 'Index', a, 'Info', info);
+            if ~isempty(map)
+                map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
+                A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
+            end
+            if size(A{a}, 3) == 4
+                % TIFF in CMYK colourspace - convert to RGB
+                if isfloat(A{a})
+                    A{a} = A{a} * 255;
+                else
+                    A{a} = single(A{a});
+                end
+                A{a} = 255 - A{a};
+                A{a}(:,:,4) = A{a}(:,:,4) / 255;
+                A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
+            end
+        end
+        A = cat(4, A{:});
+    otherwise
+        [A, map, alpha] = imread(name);
+        A = A(:,:,:,1); % Keep only first frame of multi-frame files
+        if ~isempty(map)
+            map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
+            A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
+        elseif size(A, 3) == 4
+            % Assume 4th channel is an alpha matte
+            alpha = A(:,:,4);
+            A = A(:,:,1:3);
+        end
+end
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/isolate_axes.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/isolate_axes.m	(revision 18903)
+++ /issm/trunk-jpl/externalpackages/export_fig/isolate_axes.m	(revision 18904)
@@ -19,5 +19,5 @@
 %    fh - The handle of the created figure.
 
-% Copyright (C) Oliver Woodford 2011-2012
+% Copyright (C) Oliver Woodford 2011-2013
 
 % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
@@ -26,4 +26,7 @@
 % 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.
 
 function fh = isolate_axes(ah, vis)
@@ -72,4 +75,5 @@
 nLeg = numel(lh);
 if nLeg > 0
+    set([ah(:); lh(:)], 'Units', 'normalized');
     ax_pos = get(ah, 'OuterPosition');
     if nAx > 1
@@ -82,9 +86,11 @@
     end
     leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
-    for a = 1:nAx
-            % Overlap test
-            ah = [ah; lh(leg_pos(:,1) < ax_pos(a,3) & leg_pos(:,2) < ax_pos(a,4) &...
-                         leg_pos(:,3) > ax_pos(a,1) & leg_pos(:,4) > ax_pos(a,2))];
-    end
+    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
@@ -92,13 +98,13 @@
 % Delete everything except for the input objects and associated items
 delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
-return
+end
 
 function ah = allchildren(ah)
-ah = allchild(ah);
+ah = findall(ah);
 if iscell(ah)
     ah = cell2mat(ah);
 end
 ah = ah(:);
-return
+end
 
 function ph = allancestors(ah)
@@ -111,3 +117,3 @@
     end
 end
-return
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/pdf2eps.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/pdf2eps.m	(revision 18903)
+++ /issm/trunk-jpl/externalpackages/export_fig/pdf2eps.m	(revision 18904)
@@ -25,5 +25,5 @@
 options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
 % Convert to eps using pdftops
-[status message] = pdftops(options);
+[status, message] = pdftops(options);
 % Check for error
 if status
@@ -48,4 +48,4 @@
 end
 fclose(fid);
-return
+end
 
Index: /issm/trunk-jpl/externalpackages/export_fig/pdftops.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/pdftops.m	(revision 18903)
+++ /issm/trunk-jpl/externalpackages/export_fig/pdftops.m	(revision 18904)
@@ -28,8 +28,9 @@
 % 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.
 
 % Call pdftops
 [varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
-return
+end
 
 function path_ = xpdf_path
@@ -85,4 +86,5 @@
 end
 error('pdftops executable not found.');
+end
 
 function good = check_store_xpdf_path(path_)
@@ -94,14 +96,14 @@
 % Update the current default path to the path found
 if ~user_string('pdftops', path_)
-    warning('Path to pdftops executable could not be saved. Enter it manually in pdftops.txt.');
+    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
-return
+end
 
 function good = check_xpdf_path(path_)
 % Check the path is valid
-[good message] = system(sprintf('"%s" -h', path_));
+[good, message] = system(sprintf('"%s" -h', path_));
 % system returns good = 1 even when the command runs
 % Look for something distinct in the help text
 good = ~isempty(strfind(message, 'PostScript'));
-return
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/print2array.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/print2array.m	(revision 18903)
+++ /issm/trunk-jpl/externalpackages/export_fig/print2array.m	(revision 18904)
@@ -71,5 +71,5 @@
     % Print to eps file
     tmp_eps = [tempname '.eps'];
-    print2eps(tmp_eps, fig, renderer, '-loose');
+    print2eps(tmp_eps, fig, 0, renderer, '-loose');
     try
         % Initialize the command to export to tiff using ghostscript
@@ -172,5 +172,5 @@
     end
 end
-return
+end
 
 % Function to return (and create, where necessary) the font path
@@ -196,3 +196,3 @@
 end
 user_string('gs_font_path', fp);
-return
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/print2eps.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/print2eps.m	(revision 18903)
+++ /issm/trunk-jpl/externalpackages/export_fig/print2eps.m	(revision 18904)
@@ -4,5 +4,6 @@
 %   print2eps filename
 %   print2eps(filename, fig_handle)
-%   print2eps(filename, fig_handle, options)
+%   print2eps(filename, fig_handle, bb_padding)
+%   print2eps(filename, fig_handle, bb_padding, options)
 %
 % This function saves a figure as an eps file, with two improvements over
@@ -18,8 +19,11 @@
 %              ".eps" extension is added if not there already. If a path is
 %              not specified, the figure is saved in the current directory.
-%   fig_handle - The handle of the figure to be saved. Default: gcf.
+%   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-2013
+% Copyright (C) Oliver Woodford 2008-2014
 
 % The idea of editing the EPS file to change line styles comes from Jiro
@@ -50,11 +54,18 @@
 % 22/03/13: Extend font swapping to axes labels. Thanks to Rasmus Ischebeck
 %           for reporting the issue.
-
-function print2eps(name, fig, varargin)
+% 23/07/13: Bug fix to font swapping. Thanks to George for reporting the
+%           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 < 2
-    fig = gcf;
-elseif nargin > 2
+if nargin > 3
     options = [options varargin];
+elseif nargin < 3
+    bb_padding = 0;
+    if nargin < 2
+        fig = gcf();
+    end
 end
 % Construct the filename
@@ -62,4 +73,8 @@
     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');
@@ -95,5 +110,5 @@
     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,end}(1)};
+    font_swap{3,a} = fonts{font_swap{1,a}(1)};
     fonts_new(font_swap{1,a}) = {font_swap{2,a}};
 end
@@ -126,8 +141,4 @@
     update = reshape(update(M), 1, []);
 end
-% Set paper size
-old_pos_mode = get(fig, 'PaperPositionMode');
-old_orientation = get(fig, 'PaperOrientation');
-set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
 % MATLAB bug fix - black and white text can come out inverted sometimes
 % Find the white and black text
@@ -143,64 +154,60 @@
 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 colors
+% 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);
-% Correct the fonts
+% Reset the font names in the figure
 if ~isempty(font_swap)
-    % Reset the font names in the figure
     for a = update
         set(font_handles(a), 'FontName', fonts{a}, 'FontSize', fonts_size(a));
     end
-    % Replace the font names in the eps file
-    font_swap = font_swap(2:3,:);
-    try
-        swap_fonts(name, font_swap{:});
-    catch
-        warning('swap_fonts() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
-        return
-    end
-end
-% Fix the line styles
+end
+% Do post-processing on the eps file
 try
-    fix_lines(name);
+    fstrm = read_write_entire_textfile(name);
 catch
-    warning('fix_lines() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
-end
-return
-
-function swap_fonts(fname, varargin)
-% 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);
-
+    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
-for a = 1:2:numel(varargin)
-    fstrm = regexprep(fstrm, [varargin{a} '-?[a-zA-Z]*\>'], varargin{a+1}(~isspace(varargin{a+1})));
-end
-
-% Write out the updated file
-fh = fopen(fname, 'w');
-if fh == -1
-    error('Unable to open %s for writing.', fname2);
-end
-try
-    fwrite(fh, fstrm, 'char*1');
-catch ex
-    fclose(fh);
-    rethrow(ex);
-end
-fclose(fh);
-return
+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-jpl/externalpackages/export_fig/read_write_entire_textfile.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/read_write_entire_textfile.m	(revision 18904)
+++ /issm/trunk-jpl/externalpackages/export_fig/read_write_entire_textfile.m	(revision 18904)
@@ -0,0 +1,37 @@
+%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory
+%
+% Read or write an entire text file to/from memory, without leaving the
+% file open if an error occurs.
+%
+% Reading:
+%   fstrm = read_write_entire_textfile(fname)
+% Writing:
+%   read_write_entire_textfile(fname, fstrm)
+%
+%IN:
+%   fname - Pathname of text file to be read in.
+%   fstrm - String to be written to the file, including carriage returns.
+%
+%OUT:
+%   fstrm - String read from the file. If an fstrm input is given the
+%           output is the same as that input. 
+
+function fstrm = read_write_entire_textfile(fname, fstrm)
+modes = {'rt', 'wt'};
+writing = nargin > 1;
+fh = fopen(fname, modes{1+writing});
+if fh == -1
+    error('Unable to open file %s.', fname);
+end
+try
+    if writing
+        fwrite(fh, fstrm, 'char*1');
+    else
+        fstrm = fread(fh, '*char')';
+    end
+catch ex
+    fclose(fh);
+    rethrow(ex);
+end
+fclose(fh);
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/user_string.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/user_string.m	(revision 18903)
+++ /issm/trunk-jpl/externalpackages/export_fig/user_string.m	(revision 18904)
@@ -85,3 +85,3 @@
     fclose(fid);
 end
-return
+end
Index: /issm/trunk-jpl/externalpackages/export_fig/using_hg2.m
===================================================================
--- /issm/trunk-jpl/externalpackages/export_fig/using_hg2.m	(revision 18904)
+++ /issm/trunk-jpl/externalpackages/export_fig/using_hg2.m	(revision 18904)
@@ -0,0 +1,18 @@
+%USING_HG2 Determine if the HG2 graphics pipeline is used
+%
+%   tf = using_hg2(fig)
+%
+%IN:
+%   fig - handle to the figure in question.
+%
+%OUT:
+%   tf - boolean indicating whether the HG2 graphics pipeline is being used
+%        (true) or not (false).
+
+function tf = using_hg2(fig)
+try
+    tf = ~graphicsversion(fig, 'handlegraphics');
+catch
+    tf = false;
+end
+end
