function [success bets crumbs] = gambler(goal, initial, p, trials)
% Performs independent trials for a gambling simulation.
% USAGE: [success round crumbs] = gambler(goal, initial, p, trials)
%   A gambler begins with a bankroll designated as initial
%   and repeatedly bets $1 with a winning percentage of p
%   continuing until either meeting the goal or going broke.
%
%   success will be the fraction of times in which goal was reached
%   bets will be the average number of bets placed before the outcome
%   crumbs will be a vector designating the number of timesteps started
%   at a given bankroll.
%
%   If not otherwise specified, 
%       initial = goal/2
%       p = 0.5
%       trials = 1
%
%   If trials is 1, will animate the simulation.

    if nargin < 4
        trials = 1;
        if nargin < 3
            p = 0.5;
            if nargin < 2
                initial = goal/2;
            end
        end
    end
    animate = (trials == 1);
    doCrumbs = animate || (nargout == 3);

    bets = 0;
    success = 0;
    if doCrumbs
        crumbs = zeros(1,goal-1);    % presumably never start at zero or goal
    end
    
    if animate
        expSteps = (goal/2)^2;
        sleepTime = 60/expSteps;
        cap = 10/goal;
    end
    
    for t = 1:trials
        bankroll = initial;
        while bankroll > 0 && bankroll < goal
            if doCrumbs
                if animate
                    bar( crumbs ./ sum(crumbs) );  % display percentages
                    hold on;
                    bar(bankroll, cap, 'r');
                    axis([0.5 goal-0.5 0 cap]);
                    xlabel('bankroll');
                    ylabel('Percentage of time spent with given bankroll');
                    pause(sleepTime);
                    hold off;
                end
                crumbs(bankroll) = crumbs(bankroll) + 1;
            end
            bets = bets + 1;
            if rand(1) <= p
                bankroll = bankroll + 1;   % a win
            else
                bankroll = bankroll - 1;   % a loss
            end
        end
        if bankroll >= goal
            success = success + 1;
        end
    end
    bets = bets / trials;          % average number of bets
    success = success / trials;    % chance of success
    if doCrumbs
        crumbs = crumbs ./ trials;
    end
