function m = leaf_rectangle( m, varargin )
%m = leaf_rectangle( m, varargin )
%   Create a new rectangular mesh.
%
%   Arguments:
%       M is either empty or an existing mesh.  If it is empty, then an
%       entirely new mesh is created, with the default set of morphogens
%       If M is an existing mesh, then its geometry is replaced by the new
%       mesh.  It retains the same set of morphogens (all set to zero
%       everywhere on the new mesh), interaction function, and all other
%       properties not depending on the specific geometry of the mesh.
%
%   Options:
%       'xwidth'  The width of the rectangle in the X dimension.  Default 2.
%       'ywidth'  The width of the rectangle in the Y dimension.  Default 2.
%       'centre'  Where the centre of the rectangle should be.
%       'xdivs'   The number of finite element cells along the X dimension.
%                 Default 8.
%       'ydivs'   The number of finite element cells along the Y dimension.
%                 Default 8.
%       'base'    The number of divisions along the side with minimum Y
%                 value.  The default is xdivs.
%   Example:
%       m = leaf_rectangle( [], 'xwidth', 2, 'ywidth', 2, 'xdivs', 8,
%                           'ydivs', 8, 'base', 5 )
%   See also: LEAF_CIRCLE, LEAF_CYLINDER, LEAF_LEAF, LEAF_ONECELL,
%   LEAF_SEMICIRCLE.
%
%   Equivalent GUI operation: selecting "Rectangle" in the pulldown menu in
%   the "Mesh editor" panel and clicking the "Generate mesh" button.
%
%   Topics: Mesh creation.

    [s,ok] = safemakestruct( mfilename(), varargin );
    if ~ok, return; end
    setGlobals();
    global gMAX_MGENVERSION
    s = defaultfields( s, 'xwidth', 2, 'ywidth', 2, 'centre', [0 0 0], ...
        'xdivs', 8, 'ydivs', 8, ...
        'base', 0, 'version', gMAX_MGENVERSION );
    ok = checkcommandargs( 'leaf_rectmesh', s, 'only', ...
        'xwidth', 'ywidth', 'centre', 'xdivs', 'ydivs', 'base', 'version' );
    if ~ok, m = []; return; end
    
    newm = makerectmesh( s.xwidth, s.ywidth, s.centre, [s.base s.xdivs], s.ydivs );
    m = setmeshfromnodes( newm, m, s.version );
    m.meshparams = s;
    m.meshparams.randomness = 0;
    m.meshparams.type = regexprep( mfilename(), '^leaf_', '' );
end

