function h=mtimes(g,f)
% compose - Constructs composition of two functions
%
% compose :: (A{:}->B{:}), (B{:}->C{:}) -> (A{:}->C{:}).
%
% returns the function h such that h(...) = f(g(...))
% If functions have multiple returns and arguments, outputs
% from g are routed to f.

	n1=nargout(g); if n1<0, n1=inf; end
	n2=nargin(f); if n2<0, n2=inf; end
	n3=nargout(f); if n3<0, n3=inf; end
	nint=min(n1,n2); 
	if ~isfinite(nint), error('Cannot determine number of intermediate values'); end

	fns = { @q00, @q01, @q0n; @q10, @q11, @q1n; @qn0, @qn1, @qnn };
	h=fns{ acount(nint,1)+1, acount(n3,1)+1};

	function q00(varargin), g(varargin{:}); f(); end
	function q10(varargin), f(g(varargin{:})); end
	function qn0(varargin), [y{1:nint}]=g(varargin{:}); f(y{:}); end
	function x=q01(varargin), g(varargin{:}); x=f(); end
	function x=q11(varargin), x=f(g(varargin{:})); end
	function x=qn1(varargin), [y{1:nint}]=g(varargin{:}); x=f(y{:}); end
	function varargout=q0n(varargin), g(varargin{:}); [varargout{1:nargout}]=f(); end
	function varargout=q1n(varargin), [varargout{1:nargout}]=f(g(varargin{:})); end
	function varargout=qnn(varargin), [y{1:nint}]=g(varargin{:}); [varargout{1:nargout}]=f(y{:}); end
end
