function [sig, sf, bits]=wavread(wavefile, siz)

% WAVREAD  Load Microsoft Windows .WAV format sound files.
%
%  [sig, sf, bits] = wavread(wavfile [, siz])
%   
%        sig : signal
%         sf : sampling freq.
%       bits : the number of bits per sample (8, 16, 24, 32bits)
%    wavfile : file name 
%              (The ".wav" extension is appended if no extension is given.)
%        siz : 'size' returns the size of the audio data
%            : [N1 N2] returns only samples N1 through N2

if nargin < 1
  help wavread;
  return;
end

fmt = 1; % fmt=0: digion format, fmt=1: 2^23 format
if fmt
  cnst = 1;
else
  cnst = 2;
end

if findstr(OCTAVE_VERSION, '2.0')
  uint16 = 'ushort';
  uint32 = 'ulong';
  int16 = 'short';
else
  uint16 = 'uint16';
  uint32 = 'uint32';
  int16 = 'int16';
end

if isempty(findstr(wavefile,'.'))
  wavefile=[wavefile,'.wav'];
end

if is_develop
  fid=fopen(wavefile,'rb','ieee-le');
else
  fid=fopen(wavefile,'r','ieee-le');
end
if fid == -1
  fprintf(2, 'Can''t open %s file for input!', wavefile);
  return;
end

% read riff chunk
RIFF_str=fread(fid,4,'uchar');
header=fread(fid,1,uint32);
WAVE_str=fread(fid,4,'uchar');

% read format sub-chunk
fmt_str=fread(fid,4,'uchar');
fslen=fread(fid,1,uint32);
format(1)=fread(fid,1,uint16);                % Format 
ch=fread(fid,1,uint16);                % Channel
sf=fread(fid,1,uint32);                 % Samples per second
header=fread(fid,1,uint32);             % sound data in byte 
block=fread(fid,1,uint16);
bits=fread(fid,1,uint16);                % Bits per sample
if fslen-16 > 0
  dum = fread(fid, fslen-16, 'uchar');
end

% read data sub-chunck
data_str=fread(fid,4,'uchar');
nbyteforsamples=fread(fid,1,uint32);

nsamples=nbyteforsamples/block;
if(nargin < 2)
  siz = [1 nsamples];
end

if(strcmp(siz, 'size'))
  sig = [nsamples, ch];
  fclose(fid);
  return;
end

st = siz(1);
et = siz(2);

if bits == 8
  fseek(fid, (st-1)*ch, 0);
  [sig, cnt] = fread(fid, [ch, et-st+1],'uchar');
  sig = (sig-128)/128;
end

if bits == 16
  fseek(fid, (st-1)*2*ch, 0);
  [sig, cnt] = fread(fid, [ch, et-st+1], int16);
  sig = sig/32768;     % MATLAB compatible
%  sig = (sig+32768)/32767.5-1;
end

if bits == 24
  fseek(fid, (st-1)*3*ch, 0);
  len = et-st+1;
  tmpsig = fread(fid, [1, (et-st+1)*3*ch], 'uchar');
  for k=1:ch
    idx = (0:len-1)*3*ch+(k-1)*3+1;
    signm = tmpsig(idx+2) > 127;
    sig(k,:) = -signm.*((255-tmpsig(idx+2))*2^16+cnst+(255-tmpsig(idx))+(255-tmpsig(idx+1))*2^8)+(1-signm).*(tmpsig(idx+2)*2^16+tmpsig(idx)+tmpsig(idx+1)*2^8);
  end
  if fmt
    sig = sig/2^23;
  else
    sig = (sig+2^23)/(2^23-0.5)-1;
  end
end

if bits == 32
  fseek(fid, (st-1)*4*ch, 0);
  [sig, cnt] = fread(fid, [ch, et-st+1], 'int32');
  sig = sig/2^31;
end

fclose(fid);

sig = sig';

