function writeGif(filename, frames, fps, skip)
% write the array of frames to filename. 
% fps is the frames per second.
% skip is the number of frames skipped (in case you don't want to animate
% all frames). Setting fps needs to take into account skip value.

% t = 0:1/fps:length(frames);
if nargin < 4
    skip = 1;
end

for i = 1:skip:length(frames)
      im = frame2im(frames(i));
      [imind,cm] = rgb2ind(im,256);
      if i == 1;
          imwrite(imind,cm,filename,'gif','WriteMode','overwrite','delaytime',1/fps,'Loopcount',inf);
      else
          imwrite(imind,cm,filename,'gif','WriteMode','append','delaytime',1/fps);
      end
end
