Major refactor of internals

This PR replaces #30 to resolve upstream conflicts with #master.