function [ pay_in, pay_out, pay_age, value ] = insurance_simulation ( ...
  age, term, yearly_fee, death_benefit, verbose )

%*****************************************************************************80
%
%% insurance_simulation() simulates a term life insurance plan.
%

%
%  Get probability of dying in this year.
%
  [ age_this_year, total_this_year, male_this_year, female_this_year ] = ...
    mortality_this_year ( );
%
%  Initialize.
%
  pay_in = 0.0;
  pay_out = 0.0;
  pay_age = 0;
  value = 0.0;
  interest_rate = 0.04;

  if ( verbose )
    fprintf ( 1, '\n' );
    fprintf ( 1, '  Customer age: %d\n', age );
    fprintf ( 1, '  Number of years of coverage %d\n', term );
    fprintf ( 1, '  Annual payment = %g\n', yearly_fee );
    fprintf ( 1, '  Company benefit for death within term %g\n', death_benefit );
    fprintf ( 1, '  Annual interest rate is %g\n', interest_rate );
    fprintf ( 1, '\n' );
    fprintf ( 1, 'Bracket   P(Death)      Pay       Bank  Benefit\n' );
    fprintf ( 1, '\n' );
  end
%
%  Loop over the terms of the insurance coverage.
%
  for year_age = age : age + term - 1
%
%  Cover the interval [year_age,year_age+1].
%
    value = value * ( 1.0 + interest_rate );
    value = value + yearly_fee;

    pay_in = pay_in + yearly_fee;
    died = ( rand ( ) < total_this_year ( year_age ) );
    if ( died )
      pay_age = year_age;
      pay_out = death_benefit;
    end

    if ( verbose )
      fprintf ( 1, '[%2d,%2d]  %8.4f  %8.0f  %8.0f  %8.0f\n', ...
        year_age, year_age + 1, total_this_year ( year_age ), ...
        pay_in, value, pay_out );
    end

    if ( died )
      break;
    end

  end

  return
end

