% FUNCTION BUFFER = BUFFER_INIT(BLOCKSIZE, N, UPDATE_FUN,
%                               [DISPOSE_FUN], [UPDATE_ARGS])
% 
% RESERVED FIELDS of the BUFFER object: you may read them but not
% change them:
%   buffer.blocksize
%   buffer.dispose_fun
%   buffer.fid
%   buffer.n
%   buffer.update_fun
%   buffer.update_args
%
%   buffer.start
%   buffer.end
%   buffer.size
%   buffer.index
%
% NOTE: instead of passing arguments through UPDATE_ARGS,
%       we advise you to create & use your own fields in 'buffer'.
%
% EXAMPLE: buffer for reading 2 files simultaneously
%          (e.g. energy & zero-crossing rate)
%
% fid.myfid1 = fopen('myfile1', 'r', 'l');
% fid.myfid2 = fopen('myfile2', 'r', 'l');
%
% n = 1234;         % Total number of frames
% blocksize = 100;  % maximum size of buffer in frames
%
% update_fun = @my_update_fun;
% n_channels = 10;
%
% buffer = buffer_init(blocksize, n, update_fun, [], n_channels)
% buffer.fid = fid;
%
% for a = 1:n
%   buffer = buffer_update(buffer, a);
%   
%   disp buffer.data1(:, buffer.index);
%   disp buffer.data2(:, buffer.index);
% end
%
% buffer_dispose(buffer); % To free some memory
%
% fclose(fid.myfid1);
% fclose(fid.myfid2);
%
% %%%
% function buffer = my_update_fun(buffer, my_parameter)
% 
% n_channels = my_parameter;
% buffer.data1 = fread(buffer.fid.myfid1, [n_channels buffer.size], 'float64');
% buffer.data2 = fread(buffer.fid.myfid2, [n_channels buffer.size], 'float64');

function buffer = buffer_init(blocksize, n, update_fun, ...
			      dispose_fun, varargin)

if nargin < 3
  error('buffer_init() needs at least 3 parameters');
end

if nargin < 4
  dispose_fun = [];
end

buffer.blocksize   = blocksize;
buffer.dispose_fun = dispose_fun;
buffer.n           = n;
buffer.update_fun  = update_fun;
buffer.update_args = varargin;

buffer.start = 0;
buffer.end   = 0;
buffer.size  = 0;
buffer.index = 0;