function m = leaf_mgen_radial( m, varargin )
%m = leaf_mgen_radial( m, morphogen, amount, ... )
%   Add to the value of a specified morphogen an amount depending on the
%   distance from an origin point.
%   Arguments:
%   1: The name or index of a morphogen.
%   2: The maximum amount of morphogen to add to every node.
%   Options:
%       'x', 'y', 'z'   The X, Y, and Z coordinates of the centre of the
%                       distribution, relative to the centre of the mesh.
%                       Default is (0,0,0).
%   Examples:
%       m = leaf_mgen_radial( m, 'growth', 1, 'x', 0, 'y', 0, 'z', 0 );
%       m = leaf_mgen_radial( m, 'g_anisotropy', 0.8 );
%   See also: leaf_mgen_const.
%
%   Equivalent GUI operation: clicking the "Add radial" button in the
%   "Morphogens" panel.  The amount is specified by the "Amount slider and
%   test item.  x, y, and z are specified in the text boxes of those names.
%
%   Topics: Morphogens.

    if isempty(m), return; end
    [ok1, morphogen, args] = getTypedArg( mfilename(), {'numeric','char'}, varargin );
    if ok1
        [ok2, amount, args] = getTypedArg( mfilename(), 'double', args );
    end
    if ~(ok1 && ok2), return; end
    
    [s,ok] = safemakestruct( mfilename(), args );
    if ~ok, return; end
    s = defaultfields( s, 'x', 0, 'y', 0, 'z', 0, 'power', 1 );
    ok = checkcommandargs( mfilename(), s, 'exact', 'x', 'y', 'z', 'power' );
    if ~ok, return; end

    g = FindMorphogenIndex( m, morphogen, mfilename() );
    for i=1:length(g)
        maxpos = max( m.nodes, [], 1 );
        minpos = min( m.nodes, [], 1 );
        halfrange = (maxpos-minpos)/2;
        meshcentre = sum( m.nodes, 1 )/size(m.nodes,1);
        growthcentre = meshcentre + [ s.x, s.y, s.z ] .* halfrange;
      % growthcentre(3) = minpos(3);
        m = setradialfield( ...
                m, ...
                amount, ...
                g(i), ...
                growthcentre, ...
                s.power, ...
                1 );
    end
end
