function strprint(txt, varargin)
%STRPRINT Wrap and print string
%
%   STRPRINT(STR) wraps the input string STR at 80 characters and prints
%   each wrapped string. The input string is separated on space breaks.
%   STR is a char vector.
%
%   STRPRINT(STR, maxLengthOfLine) separates the string into a maximum
%   length of maxLengthOfLine characters. maxLengthOfLine  is a nonnegative
%   integer scalar specifying the maximum length of each printed string.
%
%   Example
%       str = 'Each line''s length is less than or equal to 20.'
%       strprint(str,20)
%
%   See also STRJOIN, STRSPLIT, TEXTWRAP

% Author: Kelly Luetkemeyer

if isempty(varargin)
    maxLengthOfLine = 80;
else
    maxLengthOfLine = varargin{1};
end

splitData = strsplit(txt,' ');
lengthOfString = cellfun(@length, splitData) + 1;
while ~isempty(splitData)
    elementsToPrint = cumsum(lengthOfString) <= maxLengthOfLine;
    if ~any(elementsToPrint)
       elementsToPrint(1) = true;
    end
    lineout = strjoin(splitData(elementsToPrint),' ');
    fprintf('%s\n', strtrim(char(lineout)));
    splitData = splitData(~elementsToPrint);
    lengthOfString = lengthOfString(~elementsToPrint);
end
