% FUNCTION BUFFER = BUFFER_UPDATE(BUFFER, ITER)
%
% See BUFFER_INIT for documentation

function buffer = buffer_update(buffer, iter)

if nargin < 2
  error('buffer_upddate() needs at least 2 parameters.');
end

% Does the buffer need actual update?

if (iter > buffer.end) | (iter < buffer.start)
  
  % Virtual update
  buffer.start = 1 + fix((iter-1) / buffer.blocksize) * buffer.blocksize;
  buffer.end   = min(buffer.n, buffer.start + buffer.blocksize - 1);
  buffer.size  = 1 + buffer.end - buffer.start;
  buffer.index = 1 + iter - buffer.start;

  % Actual update (uses values just updated)
  % This will typically read from/write to a file
  buffer = feval(buffer.update_fun, buffer, buffer.update_args{:});

else

  % Virtual update only
  buffer.index = 1 + iter - buffer.start;

end
