% http://www.mathworks.com/matlabcentral/answers/55332-how-to-create-one-avi-video-from-a-folder-with-i-png-files
refreshSetup
load('Data\Setup.mat','setupSV');

D = dir('Results\Video\*.png');
Num = length(D(not([D.isdir])))

writerObj = VideoWriter('Video.avi');

writerObj.FrameRate = str2num(setupSV{19}) %min 3

numberOfFrames=Num;
% targetDurationInSeconds=20;
% writerObj.FrameRate = numberOfFrames/targetDurationInSeconds;
% format='gif'
format=setupSV{23}
switch format
    case 'avi'        %AVI
        open(writerObj);
        for K = 1 : numberOfFrames
            filename = sprintf('frm%05d.png', K)
            thisimage = imread(['Results\Video\' filename]);%z rootu
            writeVideo(writerObj, thisimage);
        end
        close(writerObj);
    case 'gif'        %GIF
        for K=1:numberOfFrames
            filename = sprintf('frm%05d.png', K)
            thisimage = imread(['Results\Video\' filename]);%z rootu
            outfile = 'Animation.gif';      
            Delay=1/str2num(setupSV{19});
            %Write the first frame to a file named animGif.gif
            [A,map] = rgb2ind(thisimage,256);
            if K == 1
                imwrite(A,map,outfile,'gif','DelayTime',Delay,'loopcount',inf);
            else
                %Loop through and write the rest of the frames
                imwrite(A,map,outfile,'gif','DelayTime',Delay,'writemode','append');
            end
        end
        
        
    otherwise
        %         if K == 1  % On the first loop, create the file. In subsequent loops, append.
        %             imwrite(A,map,outfile,'gif','LoopCount',Inf,'DelayTime',1);
        %         else
        %             imwrite(A,map,outfile,'gif','WriteMode','append','DelayTime',1);
        %         end
        %         %             if K==1
        %         %                 imwrite(imind,cm,outfile,'gif','DelayTime',0,'loopcount',inf);
        %         %             else
        %         %                 imwrite(imind,cm,outfile,'gif','DelayTime',0,'writemode','append');
        %         %             end
end


% %% Movie Test.
%
% %% Set up some function.
% % Sine between -2*pi and 2*pi.
% x = (10*-pi:0.1:10*pi)'; % Note the transpose.
% y = sin(x);
% fid = figure;
% hold on
% % The final plot.
% plot(x,y, '*');
%
% %% Set up the movie.
% writerObj = VideoWriter('out.avi'); % Name it.
% writerObj.FrameRate = 60; % How many frames per second.
% open(writerObj);
%
% for i=1:size(y)
%     % We just use pause but pretend you have some really complicated thing here...
%     pause(0.1);
%     figure(fId); % Makes sure you use your desired frame.
%     plot(x(i),y(i),'or');
%
%     %if mod(i,4)==0, % Uncomment to take 1 out of every 4 frames.
%         frame = getframe(gcf); % 'gcf' can handle if you zoom in to take a movie.
%         writeVideo(writerObj, frame);
%     %end
%
% end
% hold off
% close(writerObj); % Saves the movie.