# [Python 3]
# Retrieve true random bits or numbers from Random.org
from urllib.request import urlopen
import time

def zero_pad(num):
    if num < 10:
        return "0"+str(num)
    return str(num)

def get_daily_stream():
    lt = time.localtime()
    try:
        s = urlopen("http://random.org/files/%d/%d-%s-%s.txt" % (lt.tm_year, lt.tm_year, zero_pad(lt.tm_mon), zero_pad(lt.tm_mday)))
    except:
        raise ValueError("Could not obtain stream!")
    return s

def randbit(stream):
    b = stream.read(1)
    if len(b) != 1:
        raise ValueError("Data has been exhausted!")
    return int(b, 2)

# 0 <= r <= max (max > 0)
def randint(stream, max):
    b = max.bit_length()
    while True:
        bits = stream.read(b)
        if len(bits) < b:
            raise ValueError("Data has been exhausted!")
        num = int(bits, 2)
        if num <= max:
            return num
        

