function S = nist_stnr(D,SR)
% S = nist_stnr(D,SR)
%    Calculate NIST STNR
%    Currently works by running external binary & parsing return
% 2010-12-02 Dan Ellis dpwe@ee.columbia.edu

% do we have the binaries?
arch = computer();
% fallback to 32 bit linux if 64 bit linux
if strcmp(arch,'GLNXA64') == 1
  arch = 'GLNX86';
end

sndcat = ['./sndcat.',arch];
stnr = ['./stnr.',arch];

if exist(sndcat) == 0 || exist(stnr) == 0
  disp(['sndcat / stnr binaries not found, using Matlab ' ...
        'approximation']);
  S = nist_stnr_m(D,SR);
else
  % save the extracted region of the noisy file
  noisyfile = 'dn.wav';
  wavwrite(D,SR,noisyfile);
  % convert to sphere
  noisysph = 'dn.sph';
  mysystem(['./sndcat.',arch,' -T NIST ',noisyfile,' -o ',noisysph]);
  % run nist stnr on it
  rs = tokenize(mysystem(['./stnr.',arch,' -c ',noisysph, ...
                      ' | grep SNR']));
  % extract the reported SNR
  S = str2num(rs{14});
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function w = mysystem(cmd)
% Run system command; report error; strip all but last line
[s,w] = system(cmd);
if s ~= 0 
  error(['unable to execute ',cmd,' (',w,')']);
end
% Keep just final non-blank line
if length(w) > 0
  while(w(end)==10); w = w(1:end-1); end
  w = w((1+max([0,findstr(w,10)])):end);
end
% Debug
%disp([cmd,' -> ','*',w,'*']);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function a = tokenize(s,t)
% Break space-separated string into cell array of strings.
% Optional second arg gives alternate separator (default ' ')
% 2004-09-18 dpwe@ee.columbia.edu
if nargin < 2;  t = ' '; end
a = [];
p = 1;
n = 1;
l = length(s);
nss = findstr([s(p:end),t],t);
for ns = nss
  % Skip initial spaces (separators)
  if ns == p
    p = p+1;
  else
    if p <= l
      a{n} = s(p:(ns-1));
      n = n+1;
      p = ns+1;
    end
  end
end
