% FUNCTION WAV2ASCII( WAVFILENAME, [ASCIIFILENAME], [FINAL_SAMPLING_FREQUENCY] )
%
% Default ASCIIFILENAME: '.txt' extension
% Default FINAL_SAMPLING_FREQUENCY: same as in the WAV file

function wav2ascii( wavfilename, asciifilename, final_sampling_frequency )

if nargin < 1
  error( 'wav2ascii needs at least one argument' )
end

if nargin < 2
  [ f_path, f_name ] = fileparts( wavfilename );
  asciifilename = fullfile( f_path, [ f_name '.txt' ] )
end

if isempty( asciifilename )
   [ f_path, f_name ] = fileparts( wavfilename );
  asciifilename = fullfile( f_path, [ f_name '.txt' ] ) 
end

% Read

[y, fs, nbits] = wavread( wavfilename );

% Change sampling frequency

if nargin < 3
  final_sampling_frequency = fs
end

y = resample( y, final_sampling_frequency, fs );
y = round( y * 2 ^ (nbits-1) );

% Write

fid = fopen( asciifilename, 'wt' );

format = sprintf( '%%+0%dd\n', 1 + length( num2str( 2^nbits ) ) )

fprintf( fid, format, y );

fclose( fid );
