You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
    Metadata details:
    filename: buffer_wait_dat.m
    path of file: ./repos/spm/external/fieldtrip/fileio/private
    
    the code of the file until where you have to start completion: function available = buffer_wait_dat(selection, host, port)

% BUFFER_WAIT_DAT implementation that is also backwards compatibility with ft buffer version 1
%
% Use as
%   available = buffer_wait_dat(selection, host, port)
% where
%   selection(1) = nsamples, 0 indicates not to wait
%   selection(2) = nevents,  0 indicates not to wait
%   selection(3) = timeout in seconds
%
% It returns a structure with the available nsamples and nevents.

% check if backwards compatibilty mode is required
try
  selection(1) = selection(1)-1;
  selection(2) = selection(2)-1;
  selection(3) = selection(3)*1000; % in miliseconds

  % the WAIT_DAT request waits until it has more samples or events
  % the following should work for buffer version 2
  available = buffer('WAIT_DAT', selection, host, port);
  
catch
  % the error means that the buffer is version 1, which does not support the WAIT_DAT request

    
function available = buffer_wait_dat(selection, host, port)

% BUFFER_WAIT_DAT implementation that is also backwards compatibility with ft buffer version 1
%
% Use as
%   available = buffer_wait_dat(selection, host, port)
% where
%   selection(1) = nsamples, 0 indicates not to wait
%   selection(2) = nevents,  0 indicates not to wait
%   selection(3) = timeout in seconds
%
% It returns a structure with the available nsamples and nevents.

% check if backwards compatibilty mode is required
try
  selection(1) = selection(1)-1;
  selection(2) = selection(2)-1;
  selection(3) = selection(3)*1000; % in miliseconds

  % the WAIT_DAT request waits until it has more samples or events
  % the following should work for buffer version 2
  available = buffer('WAIT_DAT', selection, host, port);
  
catch
  % the error means that the buffer is version 1, which does not support the WAIT_DAT request
  % the wait_dat can be implemented by polling the buffer
  
  nsamples  = selection(1);
  nevents   = selection(2);
  timeout   = selection(3); % in seconds
  stopwatch = tic;
  
  % results are retrieved in the order written to the buffer
  orig = buffer('GET_HDR', [], host, port);
  
  if timeout > 0
    % wait maximal timeout seconds until more than nsamples samples or nevents events have been received
    while toc(stopwatch)<timeout
      if nsamples == -1 && nevents == -1,             break, end