function stat = fts2ascii(fname, dates, data, colheads, desc, exttext)
%FTS2ASCII writes elements of time series data into a text (ASCII) file.
%
%   STAT = FTS2ASCII(FNAME, TSOBJ, EXTTEXT) writes the financial time
%   series object TSOBJ into an ASCII file named FNAME. The data in the
%   file will be tab-delimited. Please be sure to include an extension.
%
%   For example:
%
%      %% Create the FINTS object %%
%      dates = ['01-Jan-2001';'01-Jan-2001'; '02-Jan-2001'; ...
%              '02-Jan-2001'; '03-Jan-2001';'03-Jan-2001'];
%      times = ['11:00';'12:00';'11:00';'12:00';'11:00';'12:00'];
%      dates_times = cellstr([dates, repmat(' ',size(dates,1),1), times]);
%      myFts = fints(dates_times,(1:6)',{'Data1'},1,'My first FINTS')
%      %% Create the FINTS object %%
%
%      stat = fts2ascii('myfts_file.txt', myFts, 'My first text file saved')
%
%   STAT = FTS2ASCII(FNAME, DATES/TIMES, DATA) writes into an ASCII file
%   named FNAME the dates (and/or times) and data contained in the column
%   vector (or matrix) DATES/TIMES and column-oriented matrix DATA (each
%   column is a series).  DATES will be the first column (TIMES the second,
%   if time information exists) and the columns of DATA will be the subsequent
%   columns.
%
%   Please note that if times are to be written to the ASCII file, the 
%   DATE/TIMES input must be a matrix where the first column contains the
%   serial dates and the second column contains the serial times.
%
%   STAT = FTS2ASCII(FNAME, DATES/TIMES, DATA, COLHEADS, DESC, EXTTEXT) does
%   as described previously with the added feature of including some
%   header information such as description, column headers, and extra
%   description.  COLHEADS is a cell array of column headers (names); 
%   if supplied, first cell MUST always be the one for the DATES column.
%   COLHEADS will be written to the file just before the data themselves.
%   DESC is the description string which will be the first line in the
%   file.  EXTTEXT is an extra string which, if included, will be
%   written after the description line (i.e. line 2 in the file).
%
%   STAT indicates whether it's successful (1) or not (0).
%
%   The data in the file will be TAB-delimited.
%
%   For example:
%
%      dates = ['01-Jan-2001';'01-Jan-2001'; '02-Jan-2001'; ...
%              '02-Jan-2001'; '03-Jan-2001';'03-Jan-2001'];
%      times = ['11:00';'12:00';'11:00';'12:00';'11:00';'12:00'];
%      serial_dates_times = [datenum(dates), datenum(times)];
%      data = round(10*rand(6,2));
%
%      stat = fts2ascii('myfts_file2.txt',serial_dates_times,data, ...
%             {'dates';'times';'Data1';'Data2'},'My second text file saved')
%
%   See also @FINTS/FTS2ASCII.

%   Copyright 1995-2018 The MathWorks, Inc.

warning(message('finance:ftseries:fints_fints:FunctionToBeRemoved'))
wState  = warning;                           % Save warning state
cleanUp = onCleanup(@() warning(wState));    % Restore warning state
warning('off','finance:ftseries:fints_fints:FunctionToBeRemoved')

if nargin > 0
    fname = convertStringsToChars(fname);
end

if nargin > 3
    if isstring(colheads)
        colheads = cellstr(colheads);
    end
end

if nargin > 4
    desc = convertStringsToChars(desc);
end

if nargin > 5
    exttext = convertStringsToChars(exttext);
end

stat = 0;
timeData = 0;
monoWarnFlag = 0;

% Check input arguments.
switch nargin
case 1
    error(message('finance:ftseries:fints_fts2ascii:MinNumOfArgs'));
case 2
    % 2 inputs require that the 2nd input be a tsobj 
    if ~isa(dates,'fints')
        error(message('finance:ftseries:fints_fts2ascii:TsobjMustBe2ndInput'));
    end
case 3
    colheads = {''}; desc = ''; exttext = ''; stat = 1;
case 4
    % Check colheads
    if isempty(colheads)
        % Do nothing
    elseif ~iscell(colheads)
        error(message('finance:ftseries:fints_fts2ascii:ColHeadInvalid'));
    end
    
    desc = ''; exttext = ''; stat = 1;
case 5
    % Check colheads
    if isempty(colheads)
        % Do nothing
    elseif ~iscell(colheads)
        error(message('finance:ftseries:fints_fts2ascii:ColHeadInvalid'));
    end
    
    exttext = ''; stat = 1;
case 6
    % Check colheads
    if isempty(colheads)
        % Do nothing
    elseif ~iscell(colheads)
        error(message('finance:ftseries:fints_fts2ascii:ColHeadInvalid'));
    end
    
    stat = 1;
otherwise
    error(message('finance:ftseries:fints_fts2ascii:InvalidNumArgs'));
end

% Dates must be in the from of serial dates 
if ischar(dates) | iscell(dates)
    error(message('finance:ftseries:fints_fts2ascii:SerialDatesRequired'));
end

% Sizes must be correct
if size(dates, 1) ~= size(data, 1)
    error(message('finance:ftseries:fints_fts2ascii:InvalidSize'));
end 

% Check to see if dates include time info.
% If there is time info, separate the two
if size(dates,2) > 2
    error(message('finance:ftseries:fints_fts2ascii:TooManyColOrDatesNotAColVec'));
elseif size(dates,2) == 2
    timeData = 1;
    times = dates(:,2);
    dates = dates(:,1);
elseif ~isempty(find(double(floor(dates) == dates) == 0))
    % If dates and times are one serial number (floats)
    error(message('finance:ftseries:fints_fts2ascii:SeparateDatesAndTimes'));
elseif size(dates,2) == 1
    % If dates is a column of serial numbers without times (integers)
    timeData = 0;
else
    error(message('finance:ftseries:fints_fts2ascii:IncorrectDatesAndTimes'));
end

% Check the column hearder for correct order
if isempty(colheads)
    colheads = {''};
end
if ~isempty(colheads{1})
    if timeData == 1 % There is time data
        % Make sure 'dates' is first and then 'times' in colheads
        whereDates = strcmp(colheads,'dates');
        first = find(whereDates == 1);
        if isempty(first)
            error(message('finance:ftseries:fints_fts2ascii:ColHeaderDatesMustBe1st'));
        elseif first ~= 1
            error(message('finance:ftseries:fints_fts2ascii:DatesStrNotPresent'));
        end
        whereTimes = strcmp(colheads,'times');
        second = find(whereTimes == 1);
        if isempty(second)
            error(message('finance:ftseries:fints_fts2ascii:ColHeaderTimesMustBe2nd'));
        elseif second ~= 2
            error(message('finance:ftseries:fints_fts2ascii:TimesStrNotPresent'));
        end
        
        % Check to see that the # of column headings for the data is correct
        if (length(colheads)-2) ~= size(data, 2)
            error(message('finance:ftseries:fints_fts2ascii:Dates1stThenTimes2nd'));
        end
    else % No time data
        % Make sure 'dates' is first and no 'times' in colheads
        whereDates = strcmp(colheads,'dates');
        first = find(whereDates == 1);
        if isempty(first)
            error(message('finance:ftseries:fints_fts2ascii:ColHeaderDatesMustBe1st'));
        elseif first ~= 1
            error(message('finance:ftseries:fints_fts2ascii:DatesStrNotPresent'));
        end
        whereTimes = strcmp(colheads,'times');
        second = find(whereTimes == 1);
        if ~isempty(second)
            error(message('finance:ftseries:fints_fts2ascii:NoTimePresent'));
        end
        
        % Check to see that the # of column headings for the data is correct
        if (length(colheads)-1) ~= size(data, 2)
            error(message('finance:ftseries:fints_fts2ascii:DatesMustCome1st'));
        end
        
    end
    colheads = colheads(:);
end % end of 'if ~isempty(colheads{1})'

% Check to see if dates and times are monotonically increasing
if timeData == 0
    % No time data
    theSame = prod(double((dates == sort(dates))));
else
    % There is time data
    theSame = prod(prod((double((dates+times) == sort(dates+times)))));
end

% Turn off backtrace
wb = warning('off','backtrace');

% Warn of non-monotonically increasing dates
if theSame ~= 1
    warning(message('finance:ftseries:fints_fts2ascii:NonMonotonicDatesAndTimes'));
end

% Warn of duplicate dates
% Note: Keep this warning as the last warning displayed.
if timeData == 0
    % No time information
    if ftsuniq(dates) == 0
        warning(message('finance:ftseries:fints_fts2ascii:DuplicateDates'));
    end
else
    % Contains time information
    if ftsuniq(dates+times) == 0
        warning(message('finance:ftseries:fints_fts2ascii:DuplicateDatesAndTimes'));
    end
end

% Restore old backtrace state 
warning(wb)

% Open a text (ASCII) file for writing.
fid = fopen(fname, 'wt');

% Write description and extra text, if supplied.
if ~isempty(desc)
    cnt = fprintf(fid, '%s\n', desc);
end
if ~isempty(exttext)
    cnt = fprintf(fid, '%s\n', exttext);
end

% Write column headers, if supplied.
if ~isempty(colheads{1})
    strfmt = ['%s \t', repmat('%s \t', 1, length(colheads)-2), '%s\n'];
    cnt = fprintf(fid, strfmt, colheads{:});
end

% Write the data into the file.
if timeData == 0
    % No time data
    for idx = 1:size(data, 1)
        strfmt = ['%s \t', repmat('%f \t', 1, size(data, 2)-1), '%f\n'];
        cnt = fprintf(fid, strfmt, datestr(dates(idx)), data(idx, :));
    end
else
    % There is time data
    for idx = 1:size(data, 1)
        strfmt = ['%s \t','%s \t',repmat('%f \t', 1, size(data, 2)-1), '%f\n'];
        cnt = fprintf(fid, strfmt, datestr(dates(idx)),datestr(times(idx),15), data(idx, :));
    end
end

% Close the file.
fclose(fid);

% [EOF]
