function [ top, bot ] = rat_mul ( top1, bot1, top2, bot2 )

%*****************************************************************************80
%
%% rat_mul() multiplies two fractions.
%
%  Discussion:
%
%    The routine computes
%
%      TOP / BOT = ( TOP1 / BOT1 ) * ( TOP2 / BOT2 ).
%
%    while avoiding integer overflow.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    05 August 2004
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer TOP1, BOT1, the first factor.
%
%    integer TOP2, BOT2, the second factor.
%
%  Output:
%
%    integer TOP, BOT, the product.
%
  i4_huge = 2147483647;

  if ( top1 == 0 || top2 == 0 )
    top = 0;
    bot = 1;
    return
  end
%
%  Get rid of all common factors in top and bottom.
%
  temp = gcd ( top1, bot1 );
  top1 = top1 / temp;
  bot1 = bot1 / temp;
  temp = gcd ( top1, bot2 );
  top1 = top1 / temp;
  bot2 = bot2 / temp;
  temp = gcd ( top2, bot1 );
  top2 = top2 / temp;
  bot1 = bot1 / temp;
  temp = gcd ( top2, bot2 );
  top2 = top2 / temp;
  bot2 = bot2 / temp;
%
%  The fraction (TOP1*TOP2)/(BOT1*BOT2) is in lowest terms.
%
%  Check the top TOP1*TOP2 for overflow.
%
  if ( i4_huge < abs ( top1 * top2 ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'rat_mul(): Fatal error!\n' );
    fprintf ( 1, '  Overflow of top of rational product.\n' );
    error ( 'rat_mul(): Fatal error!' );
  end

  top = top1 * top2;
%
%  Check the bottom BOT1*BOT2 for overflow.
%
  if ( i4_huge < abs ( bot1 * bot2 ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'rat_mul(): Fatal error!\n' );
    fprintf ( 1, '  Overflow of bottom of rational product.\n' );
    error ( 'rat_mul(): Fatal error!' );
  end

  bot = bot1 * bot2;
%
%  The bottom should be positive.
%
  if ( bot < 0 )
    bot = - bot;
    top = - top;
  end

  return
end

