Bottom-up rewrite of the code

Made much more modular by removing globals and simplifying API. Cleaned
up logic substantially, paving the way for some future changes.