function [signal,freq,width] = sfread(fname);
% [SIGNAL,FREQ,WIDTH] = SFREAD(FILENAME)
%  Reads NeXT soundfile into a matrix SIGNAL, where the number
%  of rows corresponds to the number of channels in the file
%  (1, 2, or 4).  FREQ returns the sampling rate, and WIDTH - 
%  number of bytes per sample.
%
%  Ilia Bisnovatyi, University of Chicago
%  March 1, 1995 

   if nargin~=1,
      error('SFREAD requires one input argument.');
   end;
   
   [fid,message] = fopen(fname,'r');
   if fid==-1,
      error(message);
   end;

   
   % Determine if the file is of the right format

   magic = fread(fid,4,'char');
   if magic~=('.snd')',
      error('Not a NeXT/SUN format file.')
   end;   
   

   % Read the rest of the header    

   dataLocation = fread(fid,1,'int32');
   dataSize = fread(fid,1,'int32')
   dataFormat = fread(fid,1,'int32');
   freq = fread(fid,1,'int32')
   channellCount = fread(fid,1,'int32')
   
   if dataFormat == 2,              % Linear 8-bit
      width = 1;
      precision = 'int8';
   elseif dataFormat == 3,          % Linear 16-bit
      width = 2;
      precision = 'int16';
   elseif dataFormat == 5,          % Linear 32-bit
      width = 4;
      precision = 'int32';
   else
      error('Only linear 8-, 16- and 32-bit formats are supported right now.');
   end;
   fread(fid,dataLocation-24);      % Skip the info field
   size = dataSize/width;
   signal = fread(fid,size,precision);    % Read in the sound data
   signal = reshape(signal,channellCount,size/channellCount);
   fclose(fid);
  


