function savePlot(filename,saveFig,paperSize)

%
% Description:
%  Attempts to clean up Matlab graphs for presentation and then save
%  them as a PNG and optionally also a FIG file based on "saveFig",
%  based on:-
% 
% http://blogs.mathworks.com/loren/2007/12/11/making-pretty-graphs/
% 
%  The Mathworks article output EPS, using Ghostscript it is possible
%  to convert this to other formats. However, I don't see much
%  difference w.r.t. outputting directly to PNG with a higher
%  resolution.
%
% Usage:
%  savePlot(filename, saveFig)
%
%  filename - the filename of the output (.png)
%  saveFig  - ==1 in addition to saving a PNG also saves a fig file
%

writeEPS = 0;

allAxesInFigure = findall(gcf,'type','axes');

FigLegend = findobj(gcf, 'Type', 'Legend');

for i=1:length(allAxesInFigure)
  currAxes = allAxesInFigure(i);

  set( currAxes                  , ...
      'FontName'   , 'Helvetica' );

  hTitle  = get(currAxes,'title');
  if(isempty(FigLegend) ~= 1)
    hLegend = legend('AutoUpdate','off');
  end
  hXLabel = get(currAxes,'xlabel');
  hYLabel = get(currAxes,'ylabel');
  hZLabel = get(currAxes,'zlabel');

  set([hTitle, hXLabel, hYLabel, hZLabel], ...
      'FontName'   , 'AvantGarde');

  set([currAxes]       , ...
      'FontSize'       , 10);
    
  set([hXLabel, hYLabel, hZLabel]  , ...
      'FontSize'   , 12          );

  set( hTitle                    , ...
      'FontSize'   , 14          , ...
      'FontWeight' , 'bold'      );

  set(currAxes, ...
    'box'         , 'off', ...
    'TickDir'     , 'out'     , ...
    'TickLength'  , [.02 .02] , ...
    'XMinorTick'  , 'on'      , ...
    'YMinorTick'  , 'on'      , ...
    'XGrid'       , 'on'      , ...
    'YGrid'       , 'on'      , ...
    'XColor'      , [.3 .3 .3], ...
    'YColor'      , [.3 .3 .3], ...
    'ZColor'      , [.3 .3 .3], ...
    'LineWidth'   , 1         );

  if(isempty(FigLegend) ~= 1)
    % Still can't get the legend to render correctly on some graphs 
    % ... work in progress
    legend(currAxes,'boxon');
    set([hLegend], ...
        'box', 'on', ...
        'FontSize' ,        10 , ...
        'EdgeColor',    [0 0 0], ...
        'color'    ,    [1 1 1]);
    set(hLegend,'box','on');
  end
end

set(gcf,'PaperPositionMode','auto');

if(saveFig)
  filenameFig = regexprep(filename,'.png','.fig');
  saveas(gcf,filenameFig,'fig');
end
 
if(~writeEPS)
  if(exist('paperSize'))
    set(gcf,'PaperUnits','inches','PaperPosition',paperSize)
  end
  print ('-dpng','-r300',filename);
else
  set(gcf, 'PaperPositionMode', 'auto');
  print -depsc2 tmp1.eps

  fixPSlinestyle('tmp1.eps', 'tmp2.eps');
  system(['"c:\Program Files\gs\gs9.10\bin\gswin64.exe" -dSAFER -dBATCH -dNOPAUSE -r300 -sDEVICE=png256 -dEPSCrop -sOutputFile=',filename,' -f tmp2.eps']); 
end

