function [signal,freq,width] = sfwrite(signal,fname,freq,format);
% SFWRITE(SIGNAL,FILENAME,FREQ,FORMAT)
%  Writes a sound in SIGNAL with a sampling rate FREQ into a NeXT/SUN file 
%  named FILENAME in a format FORMAT.  Currently supported formats are
%        
%              'int16' for 16-bit linear
%              'int8'  for  8-bit linear
%
%  The default frequency is 44100 Hz, the default format is 16-bit linear.
%  SFWRITE deduces the number of channells from the smaller of the dimentions
%  of SIGNAL.  The data in SIGNAL is automatically scaled so that the maximum
%  value is equal to the maximum value under the corresponding resolution.
%
%  Ilia Bisnovatyi, University of Chicago
%  March 1, 1995 

   if nargin<2,
      error('SFREAD requires at least two input arguments.');
   end;
   if nargin<4,
      format = 'int16';
   end;
   if nargin<3,
      freq = 44100;
   end;

   [fid,message] = fopen(fname,'w');
   if fid==-1,
      error(message);
   end;
   
   % Determine if the file is of the right format

   lf = length(format);
   if lf == 4 
         if format == 'int8',
              width = 1;
              dataFormat = 2;
         end;
   elseif lf == 5,
         if format == 'int16',
               width = 2;
               dataFormat = 3;
         end;
   else
      error('Unsupported format.');
   end;


   magic =('.snd')';
   dataLocation = 28;               % Use standard header size;
   sz = size(signal);
   dataSize = sz(1)*sz(2)*width;
   channellCount = min(sz(2),sz(1));        
   
   % Write the header
   fwrite(fid,magic,'char');
   fwrite(fid,dataLocation,'int32');
   fwrite(fid,dataSize,'int32');
   fwrite(fid,dataFormat,'int32');
   fwrite(fid,freq,'int32');
   fwrite(fid,channellCount,'int32');
   fwrite(fid,0,'int32');             % Simply zero the info field

   % Scale the data                   
   maxs = max(abs(signal));
   ratio = (((256^width)/2)-2)/maxs;
   % Now write the data
   count = fwrite(fid,signal(:)*ratio,format);
   fclose(fid);
   if count ~= sz(1)*sz(2),
      error('There was an error writing the data');
   end;



