function [] = play2( madlib )
% PLAY Run a game of Mad Libs, where the Mad Lib to play is the argument.
% That argument should be a 1-dimensional cell array of strings. This
% function interprets the first of those strings as text to put verbatim
% into the output, the second as a cue for text from the user, the third
% as verbatim text, the fourth as a cue, and so forth. Based on this
% interpretation, the function uses the cues to get text from its user, and
% then to print a complete story made from the verbatim text in the mad lib
% and the text from the user.

% History:
%
%     April 2017 -- Documentation expanded by Doug Baldwin.
%
%     April 2014 -- Created by Doug Baldwin as a prototype solution to a
%       CSci 120 project. Based on an earlier script exploring mad libs in
%       Matlab by Doug Baldwin.
%
%     November 2013 -- Mad lib script created by Doug Baldwin as a
%       prototype for Math 288. Inspired by a simpler madlib program by
%       Kevin Palmowski.


% Build a single string containing the text fragments from the madlib
% interspersed with user responses to the cues. Do this by stepping
% through the Mad Lib concatenating something onto the growing story at
% each step: if the current element of the Mad Lib is verbatim text, it is
% what's concatenated; if the current element is a cue then the cue is
% used as a prompt for user input, and that user input is what's
% concatenated.

isCue = false;              % 1st string in madlib is text, not a cue
story = '';

fprintf( 'Give me a...\n' )

for s = 1 : length( madlib )
    
    if isCue
        current = input( madlib{s}, 's' );
    else
        % Assign element s of the Mad Lib to variable "current."
        current = madlib{s};
    end
    
    story = [ story, current ];
    
    isCue = ~isCue;         % The next string has the opposite cue/non-cue role from the current string
    
end


% Print the story, breaking lines at spaces in order to keep lines from
% being too much more than 80 characters long.

spaces = isspace( story );

lineLength = 0;                     % Length of current output line

fprintf( '\n' )

for i = 1 : length( story )
    
    if spaces(i)                    % Spaces are possible line breaks
        if lineLength > 80          % Use the break if this line is already long
            fprintf( '\n' );
            lineLength = 0;
        else
            fprintf( ' ' );         % Otherwise the space is just a space, and counts in this line's length
            lineLength = lineLength + 1;
        end
    else
        fprintf( '%c', story(i) );  % Always just print and count non-spaces
        lineLength = lineLength + 1;
    end
    
end

fprintf( '\n' );
