function F = save_video_demo(videoname,F)

% call:     F = SAVE_VIDEO_DEMO(VIDEONAME,F)
%
% purpose:  To demomstrate the different options of saving a matlab
%           animation as a video. It can also store the frames in F as a
%           video directly.
%
% input:    videoname (optional)
%               Desired save name of the video. The extension can be either
%               one of the following: .avi, .mpg, .gif
%               If the save name has none of these extensions, the default
%               .avi will be used. If no videoname is given, the default is
%               used.
%               DEFAULT: 'sinusoids.avi';
%           F (optional)
%               Structure of frames. If it is not present, the demo
%               animation is used.
%
% output:   F
%               Structure of frames.
%
% remarks:  1)  For .avi the standard Indeo5 compression is used.
%           2)  For .mpg the 'mpgwrite' tool has to be installed (see The Mathworks).
%           3)  For .gif, a series of .bmp files is created in a tmp
%           directory within the given vidodir (DEFAULT: movies\). You need
%           gif-animation software, like 'Ulead gif Animator LE'
%           (http://download.chip.eu/en/Ulead-GIF-Animator-Lite-1.0_61055.h
%           tml) to convert these files to a single animated gif file.
%
% author:   Jelmer van Ast
% date:     07-March-2008
% revised:  07-March-2008
% place:    Delft Center for Systems and Control, TU Delft

% Some parameters
videodir = 'movies\';
maxt = 20;
savevideo = 1;

makevideo = 1;
if nargin==2
    if ~any(~isfield(F,{'cdata','colormap'}))
        makevideo = 0;
    end
end

if nargin<1
    videoname = 'sinusoids.avi';
end

if length(videoname)>4
    switch lower(videoname(end-3:end))
        case '.avi'
            method = 'avi';
            fps = 29.97;
        case '.mpg'
            method = 'mpg';
            fps = 29.97;
        case '.gif'
            method = 'gif';
            fps = 29.97;
        otherwise
            method = 'avi';
            fps = 29.97;
            videoname = [videoname,'.avi'];
    end
else
    method = 'avi';
    fps = 29.97;
    videoname = [videoname,'.avi'];
end

if makevideo
    % Initialize the figure
    h = figure;
    set(h,'DoubleBuffer','on');

    % Position the figure
    plot(0);
    pos = get(0,'ScreenSize');
    set(gcf,'position',pos/2);

    % Sample function describing the motion of three sinusoids
    t = 0:2;
    y(1,:) = sin(t);
    y(2,:) = sin(2*t);
    y(3,:) = cos(t);

    % Interpolate the results according to fps to get a smooth animation
    ti = min(t):(1/fps):min(maxt,max(t));
    yi = zeros(size(y,1),length(ti));
    for i=1:size(y,1)
        yi(i,:) = spline(t,y(i,:),ti);
    end

    % Pre-allocate the memory space for the frames in F
    %F = struct('cdata',cell(1,length(ti),'colormap',cell(1,length(ti))));

    % Run through the frames and store them in F
    for i=1:length(ti)
        % Plot the current frame
        plot(ti(i),yi(:,i),'o');
        axis([0,ti(end),-1,1]); axis square;

        % Save the plot as a frame if a movie is asked to be made
        F(i) = getframe(gca);

        % Wait some time to see an animation with the proper sampling time
        pause(1/fps);
    end
end

% Save the movie, if requested
if savevideo
    % Waiting before saving prevents strange error messages
    pause(2);
    % Check if movie directory exists, otherwise create it
    if(~isdir(videodir)), mkdir(videodir); end
    % Start saving the movie
    fprintf('saving movie...\n');
    switch method
        case 'avi'
            movie2avi(F,[videodir,videoname],'fps',fps,'compression','Indeo5','quality',100);
        case 'mpg'
            mpgwrite(F,colormap,[videodir,videoname]);
        case 'gif'
            videoname = videoname(1:end-4);
            tmpdir = 'tmp\';
            % Check if tmpdir exists, otherwise create it
            if(~isdir([videodir,tmpdir])), mkdir([videodir,tmpdir]); end
            % Save all individual frames as bmp files
            for i=1:length(F)
                fmt = 'bmp';
                A = frame2im(F(i));
                imwrite(A,[videodir,tmpdir,videoname,'_',num2str(1000+i),'.',fmt],fmt);
                % Show progress
                if((10*(i/length(F))-floor(10*(i/length(F))))<=10/length(F))
                    fprintf('%02d %% completed\n',10*floor(10*(i/length(F))));
                end
                pause(0.2); % Waiting before saving prevents strange error messages
            end
    end
end