function movetosubplot(ax,varargin)
% movetosubplot  Move an existing axes object or legend to specified subplot position.
%
% Syntax
% =======
%
%     AX = movetosubplot(AX,M,N,P)
%
% Input arguments
% ================
%
% * `AX` [ numeric ] - Handle to an existing axes object or legend.
%
% * `M`, `N`, `P` [ numeric ] - Specification of the new position; see help
% on standard `subplot`.
%
% Output arguments
% =================
%
% * `AX` [ numeric ] - Handle to the axes or legend moved to the new
% position.

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

%**************************************************************************

oldpos = get(ax,'position');

if ischar(varargin{1})
    fig = get(ax,'parent');
    set(fig,'units','normalized');
    switch varargin{1}
        case 'bottom'
            bottompos = 0; %0.01;
            newpos = [0.5-oldpos(3)/2,bottompos,oldpos(3:4)];
        case 'top'
            toppos = 1; %0.98;
            newpos = [0.5-oldpos(3)/2,toppos-oldpos(4),oldpos(3:4)];
    end
else
    helperfig = figure('visible','off');
    helperax = subplot(varargin{:},'visible','off');
    newpos = get(helperax,'position');
    close(helperfig);
    if isequal(get(ax,'tag'),'legend')
        newpos(1) = newpos(1) + (newpos(3) - oldpos(3))/2;
        newpos(2) = newpos(2) + (newpos(4) - oldpos(4))/2;
        newpos(3:4) = oldpos(3:4);
    end
end

set(ax,'position',newpos);

end