function tblwrite(data,varnames,casenames,filename)
%TBLWRITE Writes data in tabular form to the file system.
%   TBLWRITE(DATA, VARNAMES, CASENAMES, FILENAME) Writes a tab delimited 
%   file with variable names in the first row, case names in the 
%   first column and data in columns under each variable name. FILENAME is 
%   the complete path to the desired file.
%   VARNAMES is a string matrix containing the variable names. 
%   CASENAMES is a string matrix containing the names of each observation.
%   DATA is a numeric matrix with a value for each variable-observation
%   pair.

%   B.A. Jones 10-4-94
%   Copyright (c) 1993-96 by The MathWorks, Inc.
%   $Revision: 2.3 $  $Date: 1996/02/21 18:34:00 $

delimiter = '   ';

eval('isempty(filename);','filename=[];');
if nargin < 4 | isempty(filename)
   [F,P]=uiputfile('*');
   filename = [P,F];
end

[nobs, nvars] = size(data);

[nvarnames, maxl] = size(varnames);
if nvars ~= nvarnames
   error('Requires the number of variable names to equal the number of data columns.');
end

eval('isempty(casenames);','casenames=[];');
if nargin < 3 | isempty(casenames)
   digits = floor(log10(nobs))+1;
   caseformat = ['%',int2str(digits),'d'];
   casenames = (reshape(sprintf(caseformat,(1:nobs)),digits,nobs))';
end

marker1 = delimiter(ones(nvars,1),:);
varnames = [marker1 varnames]';
varnames = varnames(:)';

if strcmp(computer,'MAC2')
   lf = setstr(13);
else
   lf = setstr(10);
end

varnames = [varnames(:)' lf];

for rows = 1:nobs
    sr = [casenames(rows,:) delimiter];
    for cols = 1:nvars
        s = num2str(data(rows,cols));
      if cols ~= nvars
         s = [s delimiter];
      end      
      sr = [sr s];
    end
   if rows == 1
      maxl = length(sr);
      l = length(sr);
      lines = sr;
   else
      blank = ' ';
      l = length(sr);
       deltal = l - maxl;
      if deltal > 0
           lines = [lines blank(ones(rows-1,1),ones(deltal,1))];
        maxl = l;
      elseif deltal < 0
         sr = [sr blank(1,ones(-deltal,1))];
      end
      lines = [lines;sr];
   end
end
lines = [lines lf(ones(nobs,1),1)];
  
fid = fopen(filename,'w');

if fid == -1
   disp('Unable to open file.');
   return
end

fprintf(fid,'%s',varnames);
fprintf(fid,'%s',lines');
fclose(fid);
