function movie2gif(M,file,varargin)
%MOVIE2GIF Create GIF animation from MATLAB movie.
%   MOVIE2GIF works like the MATLAB function MOVIE2AVI except that a
%   GIF animation is created instead of an AVI movie. This usually
%   saves a lot of space for simpler movies.
%
%   MOVIE2GIF(M,FILE,...) creates a GIF animation from the movie M and
%   writes the result to FILE. The extension '.gif' will be added to
%   FILE if it doesn't already have an extension.
%
%   Property     Value/{Default}     Description
%   -----------------------------------------------------------------------
%   delaytime    Scalar in [0,655]   Specifies the delay in seconds
%                                    before displaying the next image.
% 
%   loopcount    Integer in          Specifies the number of times to repeat
%                [0..65535] | Inf    the animation. If loopcount = 0,
%                                    the animation will be played
%                                    once, if loopcount = 1, the
%                                    animation will be played twice,
%                                    and so on.
%
%   Example:
%     tspan = linspace(0,2*pi,30); tspan(end) = [];
%     x = linspace(-pi,pi);
%     figure, j = 0;
%     M = struct('cdata',{},'colormap',{});;
%     for t = tspan
%       j = j+1;
%       y1 = sin(x+t); y2 = cos(x-t);
%       plot(x,y1,'b',x,y2,'r');
%       M(j) = getframe;
%     end
%
%     movie2gif(M,'test.gif','delaytime',0.05,'loopcount',inf);
%
%   See also MOVIE2AVI, AVIREAD, IMWRITE, PRIVATE/WRITEGIF.

% S. Engblom 2007-05-08

% straightforward once you know how to do it...
sz = size(M(1).cdata);
gif = zeros([sz(1:2) 1 size(M,2)],'uint8');

if ~isempty(M(1).colormap), warning('Colormap of frame ignored.'); end
[gif(:,:,:,1),map] = rgb2ind(M(1).cdata,256);
for j = 2:size(M,2)
  if ~isempty(M(j).colormap), warning('Colormap of frame ignored.'); end
  gif(:,:,:,j) = rgb2ind(M(j).cdata,map);
end

% a single map obtained from the first frame is used for the
% animation: this might not be optimal for all applications but works
% well for moving contours and the like where the number of colors is
% very limited
imwrite(gif,map,file,'gif',varargin{:});