function s = cslist(c,varargin)
% cslist  Convert cellstr to comma-separated list.
%
% Syntax
% =======
%
%     S = strfun.cslist(C)
%     S = strfun.cslist(C,...)
%
% Input arguments
% ================
%    
% * `C` [ cellstr ] - Cell array of strings that will be converted to a
% comma-separated list.
%
% Output arguments
% =================
%
% * `S` [ char ] - Text string with comma-separated list.
%
% Options
% ========
%
% * `'lead='` [ char ] - Leading string at the beginning of each line.
%
% * |'spaced' [ *`true`* | `false` ] - Insert a space after comma.
%
% * `'trail='` [ char | *empty* ] - Trailing string at the end of each
% line.
%
% * `'quote='` [ *`'none'`* | `'single'` | `'double'` ] - Enclose the list
% items in quotes.
%
% * `'wrap='` [ numeric | *`Inf`* ] - Insert line break after the word
% reaching this column.
%
% Description
% ============
%
% Example
% ========
%

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

% Parse input arguments.
P = inputParser();
P.addRequired('list',@iscellstr);
P.parse(c);

% Parse options.
options = passvalopt('strfun.cslist',varargin{:});

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

% Set up the formatting string.
switch options.quote
   case 'single'
      format = '''%s'',';
   case 'double'
      format = '"%s",';
   otherwise
      format = '%s,';
end
if options.spaced 
   format = [format,' '];
end

% The length of the formatting string needs to be added to the length of
% each list item.
nformat = length(format) - 2;
len = cellfun(@length,c) + nformat;

nlead = length(options.lead);
ntrail = length(options.trail);

c = c(:).';
s = '';
firstRow = true;
while ~isempty(c)
   n = find(nlead + cumsum(len) + ntrail >= options.wrap,1);
   if isempty(n)
      n = length(c);
   end
   s1 = [options.lead,sprintf(format,c{1:n}),options.trail];
   if ~firstRow
      s = [s,sprintf('\n')];
   end
   s = [s,s1];
   firstRow = false;
   c(1:n) = [];
   len(1:n) = [];
end

end
