function string = dat2str(dat,varargin) 
% dat2str  Convert IRIS dates to cell array of strings.
%
% Syntax
% =======
%
%     s = dat2str(dat,...)
%
% Input arguments
% ================
%
% * `dat` [ numeric ] - IRIS serial date number(s).
%
% Output arguments
% =================
%
% * `s` [ cellstr ] - Cellstr with strings representing the input dates.
%
% Options
% ========
%
% * `'dateFormat='` [ char | *'YYYYFP'* ] - Date format string.
%
% * `'freqLetters='` [ char | *'YHQBM'* ] - Letters representing the five
% possible frequencies (annual,semi-annual,quarterly,bimontly,monthly).
%
% * `'months='` [ cellstr | *English names of months* ] - Strings
% representing the twelve months.
%
% * `'standinMonth='` [ numeric | 'last' | *1* ] - Which month will
% represent a lower-than-monthly-frequency date if month is part of the
% date format string.
%
% Description
% ============
%
% The date format string can include any combination of the following
% fields:
%
% * `'Y='` - Year.
%
% * `'YYYY='` - Four-digit year.
%
% * `'YY='` - Two-digit year.
%
% * `'P='` - Period within the year (half-year, quarter, bi-month, month).
%
% * `'PP='` - Two-digit period within the year.
%
% * `'R='` - Upper-case roman numeral for the period within the year.
%
% * `'r='` - Lower-case roman numeral for the period within the year.
%
% * `'M='` - Month numeral.
%
% * `'MM='` - Two-digit month numeral.
%
% * `'MMMM='`, `'Mmmm'`, `'mmmm'` - Case-sensitive name of month.
%
% * `'MMM='`, `'Mmm'`, `'mmm'` - Case-sensitive three-letter abbreviation of
% month.
%
% * `'F='` - Upper-case letter representing the date frequency.
%
% * `'f='` - Lower-case letter representing the date frequency.
%
% To get some of the above letters printed literally in the date string,
% use a percent sign as an escape character, i.e. '%Y', etc.
%
% Example
% ========
%

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

if nargin > 1 && isstruct(varargin{1})
    options = varargin{1};
    config = irisget();
else
    % Parse options.
    options = passvalopt('dates.dat2str',varargin{1:end});
    % Run dates/datdefaults to substitute the default (irisget) date format
    % options for 'config'.
    [options,config] = datdefaults(options);
end

%**************************************************************************

if ischar(options.dateformat)
    options.dateformat = {options.dateformat};
end
ndateformat = numel(options.dateformat);

[year,per,freq] = dat2ypf(dat);
string = cell(size(year));
n = numel(year);

for k = 1 : n
    if k <= ndateformat
        dateformat = options.dateformat{k};
    end
    if strncmp(dateformat,'$',1)
        if freq(k) == 0
            string{k} = datestr(per(k),dateformat(2:end));
        else
            utils.error('dates', ...
                'Cannot convert other than daily dates to Matlab date string.');
        end
    else
        string{k} = xxbuildstring(year(k),per(k),freq(k),dateformat, ...
            options.freqletters,options.months,options.standinmonth, ...
            config.highcharcode);
    end
end

end


%**************************************************************************
function s = xxbuildstring(year,per,freq,dateformat, ...
    freqletters,months,standinmonth,offset)

if freq == 0
    varyear = '';
    longyear = '';
    shortyear = '';
else
    varyear = sprintf('%g',year);
    longyear = sprintf('%04g',year);
    if length(longyear) > 2
        shortyear = longyear(end-1:end);
    else
        shortyear = longyear;
    end
end

switch freq
    case 0
        freqletter = '';
        shortarabper = sprintf('%g',per);
        longarabper = sprintf('%02g',per);
        numericmonth = NaN;
        romanper = '';
    case 1
        freqletter = freqletters(1);
        shortarabper = '';
        longarabper = '';
        numericmonth = per2month(per,1,standinmonth);
        romanper = '';
    case 2
        freqletter = freqletters(2);
        shortarabper = sprintf('%g',per);
        longarabper = sprintf('%02g',per);
        numericmonth = per2month(per,2,standinmonth);
        romanper = xxroman(per);
    case 4
        freqletter = freqletters(3);
        shortarabper = sprintf('%g',per);
        longarabper = sprintf('%02g',per);
        numericmonth = per2month(per,4,standinmonth);
        romanper = xxroman(per);
    case 6
        freqletter = freqletters(4);
        shortarabper = sprintf('%g',per);
        longarabper = sprintf('%02g',per);
        numericmonth = per2month(per,6,standinmonth);
        romanper = xxroman(per);
    case 12
        freqletter = freqletters(5);
        shortarabper = sprintf('%02g',per);
        longarabper = sprintf('%02g',per);
        numericmonth = per;
        romanper = xxroman(per);
    otherwise
        freqletter = '?';
        shortarabper = sprintf('%g',per);
        longarabper = sprintf('%02g',per);
        numericmonth = NaN;
        romanper = '';
end

if isempty(numericmonth) || isnan(numericmonth) || ~isnumeric(numericmonth)
    longmonth = '';
    shortmonth = '';
else
    longmonth = months{numericmonth};
    shortmonth = longmonth(1:min([3,end]));
end
romanmonth = xxroman(numericmonth);
varnumericmonth = sprintf('%g',numericmonth);
numericmonth = sprintf('%02g',numericmonth);

subs = { ...
    '%Y','Y'; ...
    '%P','P'; ...
    '%F','F'; ...
    '%f','f'; ...
    '%R','R'; ...
    '%r','r'; ...
    '%Q','Q'; ...
    '%q','q'; ...
    '%M','M'; ...
    '%m','m'; ...
    'YYYY',longyear; ...
    'YY',shortyear; ...
    'Y',varyear; ...
    'PP',longarabper; ...
    'P',shortarabper; ...
    'Q',romanmonth; ...
    'q',lower(romanmonth); ...
    'R',romanper; ...
    'r',lower(romanper); ...
    'F',upper(freqletter); ...
    'f',lower(freqletter); ...
    'Mmmm',longmonth; ...
    'Mmm',shortmonth; ...
    'mmmm',lower(longmonth); ...
    'mmm',lower(shortmonth); ...
    'MMMM',upper(longmonth); ...
    'MMM',upper(shortmonth); ...
    'MM',numericmonth; ...
    'mm',numericmonth; ...
    'M',varnumericmonth; ...
    'm',varnumericmonth; ...
    };

s = dateformat;
for i = 1 : size(subs,1)
    s = strrep(s,subs{i,1},char(offset+i));
end
for i = 1 : size(subs,1)
    s = strrep(s,char(offset+i),subs{i,2});
end

end
% buildstring().

%**************************************************************************
function x = xxroman(x)
romans = { ...
    'I','II','III','IV','V','VI', ...
    'VII','VIII','IX','X','XI','XII', ...
    };
try
    x = romans{x};
catch %#ok<CTCH>
    x = '';
end
end
% xxroman().
