import random


def sample_birth1_literal(T, birth, death):
    """
    Sample the next birth from a reconstructed birth death process
    starting with only 1 lineage.

    This function does not condition on the survival of the lineage.    

    T     -- stopping time
    birth -- rate of birth
    death -- rate of death

    Returns (t, alive)
    t is a float of the first birth or None if none occurs.
    alive is True if the lineage is still alive, False if extinct.

    NOTE: This function uses a very literal way of performing the sampling.
    It is only good for testing purposes.
    """
    
    # sample events
    t1 = random.expovariate(birth)
    t2 = random.expovariate(death)

    # both events occur after stopping time T, simulation is done
    if t1 >= T and t2 >= T:
        return None, True

    if t2 < t1:
        # death occurs
        return None, False
    else:
        # birth occurs

        # recurse
        t3, alive3 = sample_birth1_literal(T - t1, birth, death)
        t4, alive4 = sample_birth1_literal(T - t1, birth, death)

        if alive3 and alive4:
            # if both lineages are alive then our birth is in the
            # reconstructed process
            return t1, True
        elif alive3:
            # lineage 3 contains the first birth of the recon proc
            if t3 is not None:
                return t1 + t3, True
            else:
                return None, True
        elif alive4:
            # lineage 4 contains the first birth of the recon proc
            if t4 is not None:
                return t1 + t4, True
            else:
                return None, True
        else:
            # both lineages died, so we are dead
            return None, False