function smokerb ( trial_num )

%*****************************************************************************80
%
%% smokerb() considers a second version of the two matchbook problem.
%
%  Discussion:
%
%    A smoker buys two packs of 40 matches.
%    He then repeatedly selects a match from a randomly chosen pack.
%    At some point, the pack he chooses will be empty.
%    How many matches have been used by then?
%
%    This is a variation of the problem, because the process does not stop
%    when a pack is empty, but later, after a pack has been emptied, and
%    then selected again.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    24 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Digital Dice: Computational Solutions to Practical Probability Problems,
%    Princeton, 2008,
%    ISBN: 978-0-691-15821-1.
%
%  Input:
%
%    integer trial_num: the number of trials.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'smokerb():\n' );
  fprintf ( 1, '  A smoker buys two packs of 40 matches.\n' );
  fprintf ( 1, '  He then repeatedly selects a match from a randomly chosen pack.\n' );
  fprintf ( 1, '  At some point, the pack he chooses will be empty.\n' );
  fprintf ( 1, '  How many matches have been used by then?\n' );

  S = 0;
  matches = zeros ( 1, 80 );

  for k = 1 : trial_num

    booklet1 = 40;
    booklet2 = 40;
    while ( 0 < booklet1 && 0 < booklet2 )
      r = rand ( );
      if ( r < 0.5 )
        booklet1 = booklet1 - 1;
      else
        booklet2 = booklet2 - 1;
      end
    end

    empty = 0;

    while ( empty == 0 )
      r = rand ( );
      if ( r < 0.5 )
        if ( 0 < booklet1 )
          booklet1 = booklet1 - 1;
        else
          empty = 1;
        end
      else
        if ( 0 < booklet2 )
          booklet2 = booklet2 - 1;
        else
          empty = 1;
        end
      end
    end

    s = ( 40 - booklet1 ) + ( 40 - booklet2 );
    S = S + s;
    matches(s) = matches(s) + 1;

  end

  S = S / trial_num;
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Average total number of matches used = %g\n', S );
%
%  Graphics.
%
  clf ( );
  bar ( matches );
  title ( 'The Smoker''s Matchbook Problem #2' );
  grid ( 'on' );
  xlabel ( 'Number of matches removed from both booklets' );
  ylabel ( 'Number of simulations' );
  filename = 'smokerb.png';
  print ( '-dpng', filename );
  fprintf ( 1, '  Graphics saved as "%s"\n', filename );

  return
end
