function writetimetable(TT,filename,varargin)
%WRITETIMETABLE Write a timetable to a file.
%
%   WRITETIMETABLE(TT) writes the timetable TT to a comma-delimited text
%   file. The file name is the workspace name of the timetable TT, appended
%   with ".txt".
%
%   If WRITETIMETABLE cannot construct the file name from the timetable input,
%   it writes to the file "timetable.txt".
%
%   WRITETIMETABLE overwrites any existing file by default, but this behavior
%   can be changed to append data or error using the "WriteMode" name-value pair.
%
%   WRITETIMETABLE(TT, FILENAME) writes the timetable TT to the file FILENAME
%   as column-oriented data. WRITETIMETABLE determines the file format from
%   its extension. The extension must be one of those listed below.
%
%   WRITETIMETABLE(TT, FILENAME, "FileType", FILETYPE) specifies the file type,
%   where FILETYPE is one of "text",  "spreadsheet", or "auto".
%
%   The default value for FILETYPE is "auto", which makes WRITETIMETABLE
%   detect the output file type from the file extension supplied in FILENAME.
%
%   WRITETIMETABLE writes data to different file types as follows:
%
%   Delimited text files:
%   ---------------------
%
%   The following extensions are recognized: .txt, .dat, .csv, .log,
%                                            .text, .dlm
%
%   WRITETIMETABLE creates a column-oriented text file, i.e., each
%   column of each variable in TT is written out as a column in the
%   file. TT's variable names are written out as column headings in
%   the first line of the file.
%
%   Use the following optional parameter name/value pairs to control
%   how data are written to a delimited text file:
%
%   "Delimiter"          - The delimiter used in the file. Can be any of " ",
%                          "\t", ",", ";", "|" or their corresponding names
%                          "space", "tab", "comma", "semi", or "bar".
%                          The default value is: ",".
%
%   "WriteVariableNames" - A logical value that specifies whether or not TT's
%                          variable names are written out as column headings.
%                          Default is true.
%
%   "QuoteStrings"       - A logical value that specifies whether to write
%                          text out enclosed in double quotes ("..."). If
%                          "QuoteStrings" is true, any double quote characters
%                          that appear as part of a text variable are replaced
%                          by two double quote characters.
%
%   "DateLocale"         - The locale that writetimetable uses to create month
%                          and day names when writing datetimes to the file.
%                          "DateLocale" must be specified as a character vector
%                          or scalar string in the form xx_YY.
%                          See the documentation for DATETIME for more information.
%
%   "Encoding"           - The encoding to use when creating the file.
%                          Default is "UTF-8".
%
%   "WriteMode"          - Append to an existing file or overwrite an existing
%                          file.
%                          - "overwrite" - Overwrite the file, if it
%                                          exists. This is the default option.
%                          - "append"    - Append to the bottom of the file,
%                                          if it exists.
%
%   .xls, .xlsx, .xlsb, .xlsm, .xltx, .xltm:  Spreadsheet file.
%
%   WRITETIMETABLE creates a column-oriented spreadsheet file, i.e.,
%   each column of each variable in TT is written out as a column in
%   the file. TT's variable names are written out as column headings
%   in the first row of the file.
%
%   Use the following optional parameter name/value pairs to control
%   how data are written to a spreadsheet file:
%
%   "WriteVariableNames" - A logical value that specifies whether or not
%                          TT's variable names are written out as column headings.
%                          Default is true.
%
%   "DateLocale"         - The locale that writetimetable uses to create month
%                          and day names when writing datetimes to the file.
%                          "DateLocale" must be specified as a character vector
%                          or scalar string in the form xx_YY.
%                          Note: The "DateLocale" parameter value is ignored
%                          whenever dates can be written as Excel-formatted dates.
%
%   "Sheet"              - The sheet to write, specified the worksheet name, or a
%                          positive integer indicating the worksheet index.
%
%   "Range"              - A character vector or scalar string that specifies a
%                          rectangular portion of the worksheet to write, using the
%                          Excel A1 reference style.
%
%   "UseExcel"           - A logical value that specifies whether or not to
%                          create the spreadsheet file using Microsoft(R) Excel(R)
%                          for Windows(R). Set "UseExcel" to one of these values:
%                          - false - Does not open an instance of Microsoft Excel
%                                    to write the file. This is the default setting.
%                                    This setting may cause the data to be
%                                    written differently for files with live
%                                    updates (e.g. formula evaluation or plugins).
%                          - true  - Opens an instance of Microsoft Excel to write 
%                                    the file on a Windows system with Excel installed.
%
%   "WriteMode"          - Perform an in-place write, append to an existing
%                          file or sheet, overwrite an existing file or sheet.
%                          - "inplace"        - In-place replacement of the data
%                                               in the sheet. This is the default
%                                               option.
%                          - "overwritesheet" - If sheet exists, overwrite
%                                               contents of sheet.
%                          - "replacefile"    - Create a new file. Prior contents
%                                               of the file and all the sheets are
%                                               removed.
%                          - "append"         - Append to the bottom of the occupied
%                                               range within the sheet.
%   "AutoFitWidth"       - A logical value that specifies whether or not to change
%                          column width to automatically fit the contents. Defaults to true.
%
%   "PreserveFormat"     - A logical value that specifies whether or not to preserve
%                          existing cell formatting. Defaults to true.
%
%   In some cases, WRITETIMETABLE creates a file that does not represent TT
%   exactly, as described below.
%
%   *  WRITETIMETABLE writes out numeric variables using long g format, and
%      categorical or character variables as unquoted text.
%   *  For non-character variables that have more than one column, WRITETIMETABLE
%      writes out multiple delimiter-separated fields on each line, and constructs
%      suitable column headings for the first line of the file.
%   *  WRITETIMETABLE writes out variables that have more than two dimensions as two
%      dimensional variables, with trailing dimensions collapsed.
%   *  For cell-valued variables, WRITETIMETABLE writes out the contents of each cell
%      as a single row, in multiple delimiter-separated fields, when the contents are
%      numeric, logical, character, or categorical, and writes out a single empty
%      field otherwise.
%      
%   See also TIMETABLE, READTIMETABLE, TABLE, READTABLE, WRITETABLE,
%   WRITECELL, WRITEMATRIX

%   Copyright 2012-2020 The MathWorks, Inc.

import matlab.io.internal.utility.suggestWriteFunctionCorrection
import matlab.io.internal.validators.validateWriteFunctionArgumentOrder

if nargin < 2
    timetablename = inputname(1);
    if isempty(timetablename)
        timetablename = 'timetable';
    end
    filename = [timetablename '.txt'];
else
    for i = 1:2:numel(varargin)
        n = strlength(varargin{i});
        % Write should match to WriteVariableNames
        if n > 5 && strncmpi(varargin{i},'WriteRowNames',n) 
            error(message('MATLAB:table:write:WriteRowNamesNotSupported','WRITETIMETABLE'));
        end
    end
end

validateWriteFunctionArgumentOrder(TT, filename, "writetimetable", "timetable", @istimetable);

if ~istimetable(TT)
    suggestWriteFunctionCorrection(TT, "writetimetable");
end

try
    T = timetable2table(TT);
    writetable(T,filename,varargin{:});
catch ME
    throw(ME)
end

end

