function commonlimits(varargin)
%COMMONLIMITS   Set commom axis limits to different figure axes
%   COMMONLIMITS(HAXES) sets the axis limits of axes cotained in vector
%   HAXES to the same limits.
%   COMMONLIMITS(HREF, HAXES) sets the axis limits in HAXES the same as in
%   the reference axis HREF
%   COMMONLIMITS(..., 'x') applies changes only to the x axis.
%   COMMONLIMITS(..., 'xy') applies changes to the x and y axes.
%
% See also: setfig formatfig

% Copyright (c) 2010-2014 Peter Fiala

% search for axis selectors in parameter list
type = 'xyz';
for i = 1 : nargin
    if ischar(varargin{i})
        type = varargin{i};
        varargin = varargin([1:i-1, i+1:end]);
        break
    end
end

switch length(varargin)
    case 0
        ref = findobj('Type', 'figure');
        handles = ref;
    case 1
        ref = varargin{1};
        handles = varargin{1};
    case 2
        ref = varargin{1};
        handles = varargin{2};
    otherwise
        error('commonlimits:nargin', 'too many input arguments');
end

ax = findobj(handles, 'type', 'axes');
ref = findobj(ref, 'type', 'axes');

for c = type
    L = get(ref, [c 'Lim']);
    if iscell(L)
        L = cell2mat(L);
        L = [min(L(:,1)), max(L(:,2))];
    end
    set(ax, [c 'Lim'], L);
end
end