Initial checkin of implementation.

Works for reasonably many (tens of thousands) of random tests. Still
many cleanup/optimization TODOs left.