function [fg,aviobj]=gen_timer (sec)
%% Generate timer minutes:seconds
% gen_timer(sec)
% sec - total number of seconds
% Output: timer.gif and timer.avi

filename = 'timer.gif';
aviobj = avifile('timer.avi','compression','none','fps',1);

fg=figure('Name','Timer',...
       'PaperType','a4letter',...
       'PaperSize',[20.98 29.68],...
        'Position',[ 730   640   225    65],...
        'Color',[1 1 1]);
      
txt_box=annotation(gcf,'textbox',[0.02065 0.7287 0.7632 0.5493],...
    'String',{'00:00'},...
    'FontSize',48,...
    'FitBoxToText','off',...
    'LineStyle','none');

minutes=0;
seconds=0;
for n=1:sec
    
seconds=seconds+1;
if mod(seconds,60)==0 && seconds~=0 
    seconds=0;
    minutes=minutes+1;
end

if (n<=sec/5) % when elapsed time is <=20% of total time timer will be red 
clr='r';
else
clr='k';
end
str=datestr( datenum([num2str(minutes) ':' num2str(seconds)],'MM:SS'),'MM:SS' );
set(txt_box,'String',str,'Color',clr);

%Save to gif
frame(n) = getframe(1); %#ok<AGROW>

end %end cycle

%reverse order countdown timer
for k=sec:-1:1
 
% creating gif    
im = frame2im(frame(k));
[imind,cm] = rgb2ind(im,256);
if k == sec;
imwrite(imind,cm,filename,'gif', 'Loopcount',inf,'DelayTime',1); %'Loopcount',inf - infinite loop
else
imwrite(imind,cm,filename,'gif','WriteMode','append','DelayTime',1);
end
% creating avi
aviobj = addframe(aviobj,frame(k));
end

%normal mode
%{
for k=1:sec
% creating gif        
im = frame2im(frame(k));
[imind,cm] = rgb2ind(im,256);
if k == 1;
imwrite(imind,cm,filename,'gif', 'Loopcount',inf,'DelayTime',1); %'Loopcount',inf - infinite loop
else
imwrite(imind,cm,filename,'gif','WriteMode','append','DelayTime',1);
end
% creating avi
aviobj = addframe(aviobj,frame(k));
end
%}
close(fg);
aviobj = close(aviobj);
end