function m = leaf_gyrate( m, varargin )
%m = leaf_gyrate( m, ... )
%   Spin and/or tilt the mesh about the Z axis, leaving it at the end in
%   exactly the  same orientation as when it started.  If a movie is currently being
%   recorded, the animation will be appended to the movie.  The current view
%   is assumed to have already been written to the movie.
%
%   Options:
%       'frames':  The number of frames to be added.  Default 32.
%       'spin':    The number of complete rotations about the Z axis.
%                  Default 1.
%       'tilt':    The number of cycles of tilting up, down, and back to
%                  the initial elevation.  Default 1.
%       'tiltangle':    The angle to tilt up and down to, in degrees from
%                       the horizontal.  Default 89.99.
%
%   Topics: Movies/Images, Plotting.

% fprintf( 1, '%s: starting\n', mfilename() );
    if isempty(m), return; end
    [s,ok] = safemakestruct( mfilename(), varargin );
    if ~ok, return; end
    s = defaultfields( s, 'frames', 32, 'spin', 1, 'tilt', 1, 'tiltangle', 89.99 );
    ok = checkcommandargs( mfilename(), s, 'exact', ...
        'frames', 'spin', 'tilt', 'tiltangle' );
    if ~ok, return; end
    
    [az,el] = currentView( m );
    if isempty(az)
        fprintf( 1, '%s: no current picture -- cannot gyrate mesh.\n', mfilename() );
        return;
    end
    
    s.frames = floor(s.frames);
    daz = 360*s.spin/s.frames;
    tiltmax = max( s.tiltangle, el );
    tiltmin = min( -s.tiltangle, el );
    roll = m.plotdefaults.roll;
    for i=1:s.frames
% fprintf( 1, '%s: frame %d of %d\n', mfilename(), i, s.frames );
        cur_el = saw( i/s.frames, s.tilt, tiltmin, tiltmax, el, false );
      % fprintf( 1, 'saw( %.2f, %.2f, %.2f, %.2f, %.2f ) = %.2f\n', ...
      %     i/s.frames, s.tilt, tiltmin, tiltmax, el, cur_el );
        setMeshMultiView( m, normaliseAngle( az + daz*i, -180 ), cur_el, roll );
        drawnow;
        m = recordframe( m );
    end
% fprintf( 1, '%s: ending\n', mfilename() );
end

