function img = leaf_getimage( m )
%img = leaf_getimage( m )
%   Get an image of the current mesh.  It will be forced to be the same
%   size as the size stored in m.globalProps.framesize, unless that is
%   empty, in which case m.globalProps.framesize will be set to the size of
%   the captured image.  This ensures that successive images are all
%   the same size, which is essential when recording a movie.
%
%   See also: leaf_movie.
%
%   Topics: Movies/Images

    img = [];
    OFFLINERENDER = false;  % Offline rendering, i.e. without any graphic
                            % environment present, does not yet work.
    img1 = [];
    if OFFLINERENDER
        print(gcf,'-dpng','-r72','tempframe');
        img.cdata = imread('tempframe.png');
        img.colormap = [];
    elseif ~isempty(m.pictures)
        if length(m.pictures)==1
            h = guidata( m.pictures(1) );
            img = mygetframe(h.pictureBackground);
        else
            % Assume the first two pictures are stereo views.
            h2 = guidata( m.pictures(2) );
            img = mygetframe(h2.pictureBackground);
            h1 = guidata( m.pictures(1) );
            img1 = mygetframe(h1.pictureBackground);
        end
    else
        % No image to record.  Giveup.
        complain( 'Cannot record an image: no graphics present.' );
        return;
    end
    trim = 1;
    framesize = size(img.cdata);
    if all( framesize([1 2]) > trim+trim )
        img.cdata = img.cdata( 1+trim : framesize(1)-trim, ...
                                   1+trim : framesize(2)-trim, ...
                                   : );
        framesize = size(img.cdata);
    end
    if isempty( m.globalProps.framesize )
        m.globalProps.framesize = framesize;
    else
        img.cdata = trimframe( img.cdata, ...
            m.globalProps.framesize, ...
            m.plotdefaults.bgcolor );
    end
    if ~isempty(img1)
        img1.cdata = trimframe( img1.cdata, ...
                                  size(img.cdata), ...
                                  m.plotdefaults.bgcolor );
        width = size(img.cdata,2);
        img.cdata(:,(width+1):(width*2),:) = img1.cdata;
    end
end
