Scan pixels in a Hilbert curve pattern in the first quadrant. Modified
    algorithm from https://en.wikipedia.org/wiki/Hilbert_curve.

    :param size: Size of enclosing square
    :type size: int
    :param distance: Distance along curve (Must be smaller than  size**2 - 1)
    :type distance: int
    :returns: Coordinate generator
    :rtype: function

def hilbertscan(size, distance):
    """Scan pixels in a Hilbert curve pattern in the first quadrant. Modified
    algorithm from https://en.wikipedia.org/wiki/Hilbert_curve.

    :param size: Size of enclosing square
    :type size: int
    :param distance: Distance along curve (Must be smaller than  size**2 - 1)
    :type distance: int
    :returns: Coordinate generator
    :rtype: function
    """

    size = 2*(1<<(size-1).bit_length());
    if (distance > size**2 - 1): raise StopIteration("Invalid distance!")

    for d in range(distance):
        t = d
        x = 0
        y = 0
        s = 1
        while (s < size):
            rx = 1 & (t / 2)
            ry = 1 & (t ^ rx)
            x, y = hilbertrot(s, x, y, rx, ry)
            x += s * rx
            y += s * ry
            t /= 4
            s *= 2
        yield x, y