function WriteTable(varargin)
% Writes an array to an ASCII data file with a specified format
% Row and column headers can also be specified
% Syntax y = WriteTable(Filename,A,Format,Permission,ColumnHeaders,Rowheaders)
% Filename - name of the file data is to written to
% A - the array containing the data to be written
% Format - the format string eg 15.3F (see function FPRINTF) - do not specify the %
% Permission - (w) will write to a new file or overwrite existing data (a) will append to an existing file (a)
% ColumnHeaders - column string array speifying the lables for the column headings (each row of array contains 1 heading)
% RowHeaders - column string array speifying the lables for the row headings (each row of array contains 1 heading)
% Function can have a minimum of 2 arguments WriteTable(Filename,A), other arguments are optional
% Example:
% A = rand(5,5);CHeaders = 'COne CTwo CThree CFour CFive';RHeaders = 'ROne RTwo RThree RFour RFive';
% WriteTable('TableData.dat',A,'13.4E','w',makemat(CHeaders),makemat(RHeaders))
% ** Makemat is not a native MATLAB function but can be downloaded from this site

if (nargin < 2)
    error('Too few input arguments !');
end

FileName = varargin{1};
DataArray = varargin{2};
WriteAppend = 'a'; % Default open mode
DataFormat = '%s';
ColumnHeaders = []; % By default there are no column headers
RowHeaders = []; % By default there are no row headers

if nargin >= 3
    DataFormat = varargin{3};
    DataFormat = ['%' DataFormat];
end
if nargin >= 4
    WriteAppend = varargin{4};  
end
if nargin >= 5
    ColumnHeaders = varargin{5};
end
if nargin >= 6
    RowHeaders = varargin{6};
end

fid1 = fopen(FileName,WriteAppend);

if isnumeric(ColumnHeaders) & ~isempty(ColumnHeaders)
    ColHeaders = [];
    if size(ColumnHeaders,1) > size(DataArray,2)
        error('Length of column headers incompatible with number of columns in table.')
    end
    for i =1:length(ColumnHeaders)
        ColHeaders = strvcat(ColHeaders,num2str(ColumnHeaders(i)));
    end
    ColumnHeaders = ColHeaders;
end        

if isnumeric(RowHeaders) & ~isempty(RowHeaders)
    RHeaders = [];
    if size(RowHeaders,1) > size(DataArray,1)
        error('Length of row headers incompatible with number of rows in table.')
    end
    for i =1:size(RowHeaders,1)
        RHeaders = strvcat(RHeaders,RowHeaders(i,:));
    end
    RowHeaders = RHeaders;
end        

if ~isempty(ColumnHeaders)
    DCW = length(sprintf(DataFormat,DataArray(1,1))); % Data column width
    for i = 1:size(ColumnHeaders,1)
        if i == 1
            fprintf(fid1,['%' num2str(DCW+size(RowHeaders,2)) 's'],ColumnHeaders(i,:));
        else
            fprintf(fid1,['%' num2str(DCW) 's'],ColumnHeaders(i,:));
        end
    end
    fprintf(fid1,'\n');
end

for i = 1:size(DataArray,1)
    if ~isempty(RowHeaders)
        fprintf(fid1,'%s',RowHeaders(i,:));
    end
    fprintf(fid1,DataFormat,DataArray(i,:));
    fprintf(fid1,'\n');
end

fclose(fid1);

