function [success bets] = gambler(goal, initial, p, trials)
% Performs independent trials for a gambling simulation.
% USAGE: [success round] = 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
%
%   If not otherwise specified, 
%       initial = goal/2
%       p = 0.5
%       trials = 1

    if nargin < 4
        trials = 1;
        if nargin < 3
            p = 0.5;
            if nargin < 2
                initial = goal/2;
            end
        end
    end

    bets = 0;
    success = 0;
    
    for t = 1:trials
        bankroll = initial;
        while bankroll > 0 && bankroll < goal
            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
