function outsig = playrecf(insig, sf, bits, dev, info);

%  play and record sound via 16 or 8-bit sound card. (file version)
%   this program only runs on Linux or *BSD with sound driver
%   needs command line playing software `vplay' with akira.patch
%
%    outsig = soundf(insig [, sf] [, bits] [, dev] [, info]);
%       insig : array of sounds (max 2-channels)
%      outsig : array of sounds (max 2-channels)
%         sf  : sampling freq (Hz) (default : 8000)
%        bits : bits/sample        (default : 16)
%         dev : device number 0:/dev/dsp0, 1:/dev/dsp1, and so on
%        info : 0: quiet mode (default)
%               1: show information of D/A conversion
%               2: show information of D/A conversion and command

if(nargin < 1)
  help playrec
end
if(nargin < 2)
  sf = 8000;
end
if(nargin < 3)
  bits = 16;
end
if(nargin < 4)
  dev = 0;
end
if(nargin < 5)
  info = 0;
end

if ~exist('OCTAVE_VERSION')
  error('MATLAB doesn\'t support this command');
  return;
end
outfile = tmpnam();
infile = tmpnam();

if size(insig, 1) > size(insig, 2)
  insig = insig';
end
[ch, len] = size(insig);
if ch > 2
  ch = 2;
end
if(max(insig) > 1 | min(insig) < -1)
  disp('Input: 16-bit short overflow will occur');
end

if(ch == 2)
  if(info > 0)
    cmdline = sprintf('-s%d -f %s -r -b%d -S', sf, infile, bits);
  else
    cmdline = sprintf('-s%d -f %s -r -q -b%d -S', sf, infile, bits);
  end
else
  if(info > 0)
    cmdline = sprintf('-s%d -f %s -r -b%d', sf, infile, bits);
  else
    cmdline = sprintf('-s%d -f %s -r -q -b%d', sf, infile, bits);
  end
end
if dev == 0
  cmdline = sprintf('recplay %s %s', cmdline, outfile);
else
  cmdline = sprintf('recplay -c %d %s %s', dev, cmdline, outfile);
end

if(bits == 8)
  nsig=round((insig+1) * 255/2);
  dattype = 'uchar';
else
  nsig = round((insig+1)*65535/2) - 32768;
  dattype = 'short';
end

ifd = fopen(outfile, 'wb');
fwrite(ifd, nsig, dattype, 0, 'ieee-le');
fflush(ifd);
fclose(ifd);
system([cmdline ' && rm -rf ' outfile]);
ofd = fopen(infile, 'rb');

osig = fread(ofd, [ch, len], dattype, 0, 'ieee-le');

if bits == 8
  outsig = (osig-128)/128;
else
  outsig = osig/32768;
end

outsig = outsig';

fclose(ofd);
system(['rm -rf ' infile]);

if(info > 1)
  disp(cmdline);
end

if(max(outsig) > 1 | min(outsig) < -1)
  disp('Output : 16-bit short overflow will occur');
end
