import random


def sample_birth_death_count(n, t, birth, death):
    """
    Sample the gene count at time 't' with birth death rates
    'birth' and 'death' with starting count 'n'
    """

    t2 = 0.0
    bd = float(birth + death)

    while t2 < t and n > 0:
        rate = bd * n
        next_t = random.expovariate(rate)

        if t2 + next_t < t:
            if random.random() < birth / bd:
                # birth
                n += 1
            else:
                # death
                n -= 1

        t2 += next_t

    return n