import math


def _rescale_read_counts_if_necessary(n_ref_reads, n_total_reads,
                                      max_allowed_reads):
  """Ensures that n_total_reads <= max_allowed_reads, rescaling if necessary.

  This function ensures that n_total_reads <= max_allowed_reads. If
  n_total_reads is <= max_allowed_reads, n_ref_reads and n_total_reads are just
  returned. However, if n_total_reads > max_allowed_reads, then n_ref_reads and
  n_total_reads are rescaled to new values n_ref_reads' and n_total_reads' so
  that n_total_reads' == max_allowed_reads and n_ref_reads' / n_total_reads' ~
  n_ref_reads / n_total_reads.

  Args:
    n_ref_reads: int. Number of reference supporting reads.
    n_total_reads: int. Total number of reads.
    max_allowed_reads: int. The maximum value allowed for n_total after
      rescaling, if necessary.

  Returns:
    New values for n_ref_reads and n_total_reads.
  """
  if n_total_reads > max_allowed_reads:
    ratio = n_ref_reads / (1.0 * n_total_reads)
    n_ref_reads = int(math.ceil(ratio * max_allowed_reads))
    n_total_reads = max_allowed_reads
  return n_ref_reads, n_total_reads