function writeString(filename, str, wordsPerLine)
%This function outputs string to a text file. Words are delimited by the
%space character. Only a specified number of words are outputted per line.
%
% INPUTS:
%   filename - a string containing the output filename (with extension).
%   str - the string that will be outputted to the text file.
%   wordsPerLine - the number of words (any number of characters followed
%                  by a single space) that will be written on each line of
%                  the output text file.

%Default number of words per line is 15
if nargin < 3 || wordsPerLine < 1
    wordsPerLine = 15;
end

fid = fopen(filename, 'at');
expression = sprintf('([\\w'']+\\s*){1,%d}', wordsPerLine);
[startIndex, endIndex] = regexp(str, expression);
for ii = 1:length(startIndex)
    fprintf(fid, '%s\n', str(startIndex(ii):endIndex(ii)));
end

fprintf(fid, '\n\n');

fclose(fid);

end

