% audioread_BugCheck.m , Dec.2016
% Reads 4096-sample blocks from wav files.
% The code sometimes fails with the error message :
% "out of memory  error or dimension too large for Octave's index type"
% This also happened already in line 20 with a 570 MB file, although this
% command should just read the wav-file header and 1 sample.
% This code (with minor changes) runs by a factor of 112 faster under MATLAB 6.1
% (R12.1),2001, on an old Laptop from 2002.

more off

maxblock=999999;
info_chunk=100;

[fname,path] = uigetfile('e:\wav\*.wav','Pick a WAV file =>');
wavname = [path '\' fname];

[dummy,name,dummy] = fileparts(fname);

[y,fs,NBits]=wavread(wavname,1);

disp(['SampleRate : ' int2str(fs)])

SIZ = wavread(wavname,'size');
samples = SIZ(1)
channels = SIZ(2);
if (channels<2)
  disp('Less than 2 channels !')
endif;
% --------------------------------------------------------------------

n1 = 1;

lseqh =2048;
lseq=lseqh+lseqh;
lseq1=lseq-1;

t_samples = samples;

ni = fix(t_samples/lseq);
rest=mod(t_samples,lseq);

disp(['Number of full blocks ni = ' int2str(ni) ', rest=' int2str(rest) ' samples'])

n2 = n1+lseq1;

disp(['Scanning file ' fname])
block = 1;

ch = 's';

tic();

while (n1<=t_samples) && (block<=maxblock)

  data = wavread(wavname,[n1,n2]);
  [nr,nc]=size(data);
  if nc<2
    data=data*[1 1]; % expanding to Mono in Stereo for equal processing
  endif
  anz = n2-n1+1;

% Column 1 : Left, Column 2 : Right
  if anz<lseq 
    data  = [data; zeros(lseq-anz,2)]; % fil with zeros to length lseq
  endif;
 
% do some data processing 

  n1 = n2+1;
  n2 = n2+lseq;
  if (n2>t_samples) 
    n2 = t_samples;
  endif;

if (mod(block,info_chunk)==0)
  toc()
  ch=kbhit(1); % does not work as described, waits for further input
  %              instead of returning immediately
  disp(['block : ' int2str(block) ', size(data)=' int2str(size(data))])
  tic();
endif

  block = block+1;

  if ch=='e', break,endif;
endwhile;

toc()

disp('Ready')
