function h_bar = fwaitbar(fid,msg)
%FWAITBAR Displays timer controlled wait bar for working with files.
% Creates and displays a waitbar depending on the file position indicator(FID).
% Due to the fact that the waitbar updates automatically via timer function
% it is not necessary to update it manually in each cycle of the loop.
%
% H = FWAITBAR(FID) initializes the waitbar due to file identifier
% obtained from FOPEN. The length of the bar will compute due to
% file position indicator obtained from FTELL.
% The handle to the waitbar figure is returned in H.
%
% FWAITBAR(FID,'message') initializes the wait bar with a specified
% message.
%
% FWAITBAR is typically used outside a FOR/WHILE loop that performs a
% lengthy operation with readout of files.
%
% Example
% fid=fopen('fopen.m');
% fwaitbar(fid);
% while 1
% tline = fgetl(fid);
% if ~ischar(tline), break, end
% disp(tline)
% pause(0.05)
% end
% fclose(fid);
%
%See also fopen, fread, fscanf, fprintf, fwrite, fseek, ftell, waitbar.
%
% Author: Elmar Tarajan [MCommander@gmx.de]
% Version: v1.0
%
try
if nargin == 1
[fpath fname fext] = fileparts(fopen(fid));
msg = sprintf('[%s%s] in process',fname,fext);
end%
%
tmp = ftell(fid);
fseek(fid,0,1);
fsize = ftell(fid);
fseek(fid,tmp,-1);
catch
error('Invalid file identifier. Use fopen to generate a valid file identifier.')
end% try
%
tic
h_bar = waitbar(0,msg);
T = timer('Period',1,'StartDelay',1, ...
'ObjectVisibility','off', ...
'ExecutionMode','fixedSpacing', ...
'TimerFcn',{@update_bar,h_bar,fid,fsize});
start(T)
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function update_bar(T,cnc,h_bar,fid,fsize)
try
tmp = ftell(fid)/(fsize+1);
waitbar(tmp,h_bar)
set(h_bar,'Name',['Please wait... ' datestr((toc/tmp-toc)*1.157407e-5,13)]);
catch
try ; close(h_bar) ; end;
try ; stop(T);delete(T) ; end;
end% try
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%[I LOVE MATLAB]%%%