function [X,opt] = read_flac(f,ix,n,ch,opt)

% read_flac - read samples from sound file
% ----------------------------------------
%
% [X,opt] = read_flac(f,ix,n,ch,opt)
%
% Input:
% ------
%  f - file location
%  ix - initial sample
%  n - number of samples
%  ch - channels to select
%  opt - conversion request options
%
% Output:
% -------
%  X - samples from sound file
%  opt - updated conversion options

%--------------------------------
% Author: Harold Figueroa
%--------------------------------
% $Revision: 587 $
% $Date: 2005-02-22 23:28:55 -0500 (Tue, 22 Feb 2005) $
%--------------------------------
	
%---------------------------------------
% SET PERSISTENT VARIABLES
%---------------------------------------

%--
% set location of command-line utility
%--

persistent FLAC FLAC_READ_TEMP;

if (isempty(FLAC))
	
	FLAC = [fileparts(mfilename('fullpath')), filesep, 'flac.exe'];
	
	% NOTE: use a single temporary file to avoid name creation and delete
	
	FLAC_READ_TEMP = [tempdir, 'FLAC_READ_TEMP'];
	
end

%---------------------------------------
% DECODE USING CLI HELPER
%---------------------------------------
	
temp = [FLAC_READ_TEMP, int2str(rand_ab(1,1,10^6)), '.wav'];

%--
% decode flac to temporary file
%--

cmd_str = [ ...
	'"', FLAC, '" --decode --totally-silent', ... % NOTE: make the decoding silent
	' --skip=', int2str(ix), ...
	' --until=+', int2str(n), ...
	' --force --output-name=', temp, ... % NOTE: force the file to be written
	' "', f, '"' ...
];

system(cmd_str);

%--
% load data from temporary sound file
%--
	
X = read_libsndfile(temp,0,n,ch);

%--
% delete temporary file
%--

delete(temp);
