function fit_axes( ax )
%FIT_AXES  Fit axes tightly to figure w.r.t. labels.

% (c) 2020-03-29 Martin Matousek
% Last change: $Date$
%              $Revision$

  if nargin < 1, ax = gca; end

  % text width and height
  set( ax, 'units', 'points' )
  f = get( gca, 'fontsize' );
  tx_w = 0.6 * f;
  tx_h = f;

  % minimal border
  left = 2;
  bot = 2;
  top = 2;
  right = 2;

  % update border if there is a title or labels
  if ~isempty( get( get( gca, 'ylabel' ), 'string' ) )
    left = left + 2*tx_h;
  end

  n = max( cellfun( @numel, get( gca, 'YTickLabel') ) );

  if ~isempty( n )
    left = left + ( n + 0.5 ) * tx_w;
  end

  if ~isempty( get( gca, 'XTickLabel') )
    bot = bot + 1.5 * tx_h;
  end

  if ~isempty( get( get( gca, 'xlabel' ), 'string' ) )
    bot = bot + 2*tx_h;
  end

  if ~isempty( get( get( gca, 'title' ), 'string' ) )
    top = top + 2*tx_h;
  end

  % remove suplot behaviour (keep SubplotGridLocation)
  sub = getappdata( ax, 'SubplotGridLocation' );

  fig = get( ax, 'parent' );
  if ~isempty( getappdata( fig, 'SubplotGrid' ) )
    rmappdata( fig, 'SubplotGrid' )
  end

  % maximum axis size
  set( ax, 'units', 'normalized' )
  if ~isempty( sub )
    w = 1 / sub{2};
    h = 1 / sub{1};
    x = rem( sub{3}-1, sub{2} ) * w;
    y = floor( (sub{3}-1) / sub{2} ) * h;
    set( ax, 'position', [ x, y, w, h ] )
  else
    set( ax, 'position', [0, 0, 1, 1] )
  end

  % set borders
  set( ax, 'units', 'points' )
  p = get( ax, 'position' );
  set( ax, 'position', p + [ left, bot, -left-right, -bot-top ] )
  set( ax, 'units', 'normalized' )

  % keep SubplotGridLocation
  if ~isempty( sub )
    setappdata( ax, 'SubplotGridLocation', sub );
  end
end % fcn.
