Big refactoring and final cleanup that fixes #79.